Bibliotecas de Python empleadas en el hacking

Python es el lenguaje de programación más empleado por pentesters/investigadores de seguridad, y sus múltiples bibliotecas pre compiladas ayudan a escanear redes y ofrecen diferentes opciones para enviar y recibir solicitudes y paquetes. El siguiente es un listado de las bibliotecas de Python más populares, elaborado por los expertos en hacking ético del Instituto Internacional de Seguridad Cibernética (IICS).

En este tutorial utilizaremos Kali Linux 2019.1, que cuenta con varias bibliotecas de Python instaladas por defecto, de modo que sólo se requiere importar los módulos para ser utilizados.

  • Abra el terminal
    • Escriba sudo apt-get update
    • Escriba sudo apt-get install python3
    • Si usa Kali Linux  escriba pip3 install scapy

Bibliotecas de Python

Scapy

Esta es la biblioteca más popular entre muchos desarrolladores de herramientas de seguridad y pentesters. Scapy ofrece eficaces funciones de envío, rastreo y falsificación de paquetes de datos. Los usuarios pueden emplear esta herramienta de forma interactiva o importarla directamente. Además, cuenta con las funcionalidades de Wireshark, Nmap, Arpspoof, entre otros escáneres de red, por lo que es realmente útil en las fases iniciales de pentesting.

  • Abrir terminal y escriba python; este comando abrirá el entorno de Python
  • Luego escriba los siguientes comandos:
>>>import sys
>>>from scapy.all import *
>>>print("pinging the target….")
>>>icmp = IP(dst=ip)/ICMP()
>>>resp = sr1(icmp,timeout=10)
>>>if resp == None:
>>>    print("This host is down")
>>>else:
>>>    print("This host is up")
  • El script anterior está importando sys de scapy. Luego enviando 1 paquete de ICMP. Después de obtener la respuesta de la dirección IP objetivo, se imprimirá. El host está arriba
  • Aquí puede ingresar cualquier protocolo de red para verificar si el host está activo. Scapy proporciona gran cantidad de soporte de protocolos de red
  • Asegúrese de ingresar la dirección IP objetivo en la línea: 4
    • icmp = IP (dst = ”10.10.10.179 ″) / ICMP ()
>>import sys
>>>from scapy.all import *
>>>print("pinging the target….")
>>>pinging the target….
>>>icmp = IP(dst="10.10.10.179")/ICMP()
>>>resp = sr1(icmp,timeout=10)
>>>Begin emission:
>>>…….Finished sending 1 packets.
>>>*
>>>Received 8 packets, got 1 answers, remaining 0 packets
>>>if resp == None:
>>>…     print("This host is down")
>>>… else:
>>>…     print("This host is up")
>>>…
This host is up          
  • Después de ejecutar, ejecutamos Wireshark para capturar los paquetes enviados por el script python
  • La captura de pantalla anterior de Wireshark muestra el envío y la recepción del paquete ICMP

Impacket

Impacket funciona con protocolos de red y brinda acceso de programación de bajo nivel a paquetes de datos. Core Impacket interactúa fácilmente con Windows como: MSSQL, SMB, NETBIOS y otros protocolos. Core Impacket proporciona pasar los escenarios de ataque clave. Los protocolos de red como: TCP, UDP, ARP se presentan con impacket. Impacket está diseñado como un módulo todo en uno de python, mencionan los expertos en hacking ético.

  • Para usar Impacket, se debe instalar Python. Para eso repita los pasos iniciales. Escriba git clone https://github.com/SecureAuthCorp/impacket.git
  • Luego escriba cd impacket
  • Escriba chmod u+x requerimientos.txt setup.py
root@kali:/home/iicybersecurity# cd Downloads/impacket/
root@kali:/home/iicybersecurity/Downloads/impacket# ls
 ChangeLog  impacket  MANIFEST.in  requirements.txt  tests
 examples   LICENSE   README.md    setup.py          tox.ini
root@kali:/home/iicybersecurity/Downloads/impacket# pip install -r requirements.txt
 DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7.
 Requirement already satisfied: future in /usr/lib/python2.7/dist-packages (from -r requirements.txt (line 1)) (0.15.2)
 Requirement already satisfied: six in /usr/lib/python2.7/dist-packages (from -r requirements.txt (line 2)) (1.11.0)
 Requirement already satisfied: pyasn1>=0.2.3 in /usr/lib/python2.7/dist-packages (from -r requirements.txt (line 3)) (0.4.2)
 Requirement already satisfied: pycryptodomex in /usr/local/lib/python2.7/dist-packages (from -r requirements.txt (line 4)) (3.8.1)
 Requirement already satisfied: pyOpenSSL>=0.16.2 in /usr/local/lib/python2.7/dist-packages (from -r requirements.txt (line 5)) (17.2.0)
 Requirement already satisfied: ldap3==2.5.1 in /usr/local/lib/python2.7/dist-packages (from -r requirements.txt (line 6)) (2.5.1)
 Requirement already satisfied: ldapdomaindump>=0.9.0 in /usr/local/lib/python2.7/dist-packages (from -r requirements.txt (line 7)) (0.9.1)
 Requirement already satisfied: flask>=1.0 in /usr/lib/python2.7/dist-packages (from -r requirements.txt (line 8)) (1.0.2)
  • Impacket viene con algunas muestras. Que se utilizan para recopilar información de cualquier dirección IP en la red local
  • Para eso:
    • Escriba ejemplos de cd
    • Escriba ls
root@kali:/home/iicybersecurity/Downloads/impacket/examples# ls
 addcomputer.py  getST.py        mqtt_check.py         ping.py           secretsdump.py  ticketer.py
 atexec.py       getTGT.py       mssqlclient.py        psexec.py         services.py     wmiexec.py
 dcomexec.py     GetUserSPNs.py  mssqlinstance.py      raiseChild.py     smbclient.py    wmipersist.py
 dpapi.py        goldenPac.py    netview.py            rdp_check.py      smbexec.py      wmiquery.py
 esentutl.py     ifmap.py        nmapAnswerMachine.py  registry-read.py  smbrelayx.py
 GetADUsers.py   karmaSMB.py     ntfs-read.py          reg.py            smbserver.py
 getArch.py      kintercept.py   ntlmrelayx.py         rpcdump.py        sniffer.py
 GetNPUsers.py   lookupsid.py    opdump.py             sambaPipe.py      sniff.py
 getPac.py       mimikatz.py     ping6.py              samrdump.py       split.py
  • Vamos a mostrar algunos ejemplos para mostrar cómo se utiliza Impacket se puede utilizar para rastreo/reconocimiento
  • Comenzaremos con ping.py
PING.PY

import select
import socket
import time
import sys

from impacket import ImpactDecoder, ImpactPacket

if len(sys.argv) < 3:
    print("Use: %s <src ip> <dst ip>" % sys.argv[0])
    sys.exit(1)

src = sys.argv[1]
dst = sys.argv[2]

# Create a new IP packet and set its source and destination addresses.

ip = ImpactPacket.IP()
ip.set_ip_src(src)
ip.set_ip_dst(dst)

# Create a new ICMP packet of type ECHO.

icmp = ImpactPacket.ICMP()
icmp.set_icmp_type(icmp.ICMP_ECHO)

# Include a 156-character long payload inside the ICMP packet.
icmp.contains(ImpactPacket.Data("A"*156))

# Have the IP packet contain the ICMP packet (along with its payload).
ip.contains(icmp)

# Open a raw socket. Special permissions are usually required.
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)

seq_id = 0
while 1:
    # Give the ICMP packet the next ID in the sequence.
    seq_id += 1
    icmp.set_icmp_id(seq_id)

    # Calculate its checksum.
    icmp.set_icmp_cksum(0)
    icmp.auto_checksum = 1

    # Send it to the target host.
    s.sendto(ip.get_packet(), (dst, 0))

    # Wait for incoming replies.
    if s in select.select([s],[],[],1)[0]:
       reply = s.recvfrom(2000)[0]

       # Use ImpactDecoder to reconstruct the packet hierarchy.
       rip = ImpactDecoder.IPDecoder().decode(reply)
       # Extract the ICMP packet from its container (the IP packet).
       ricmp = rip.child()

       # If the packet matches, report it to the user.
       if rip.get_ip_dst() == src and rip.get_ip_src() == dst and icmp.ICMP_ECHOREPLY == ricmp.get_icmp_type():
           print("Ping reply for sequence #%d" % ricmp.get_icmp_id())

       time.sleep(1)
  • Escriba python ping.py <src ip> <dst ip>
root@kali:/home/iicybersecurity/Downloads/impacket/examples# python ping.py 10.10.11.70 10.10.10.1
 Ping reply for sequence #1
 Ping reply for sequence #2
 Ping reply for sequence #3
 Ping reply for sequence #4
 Ping reply for sequence #5
 Ping reply for sequence #6
 Ping reply for sequence #7
  • El comando anterior hará ping a la dirección IP específica hasta que presione Ctrl + C
  • Escriba python sniffer.py/ python sniff.py muestra el mismo resultado. La única diferencia en python sniff.py. Solicitará la interfaz de red predeterminada
SNIFF.PY

import sys
from threading import Thread
import pcapy
from pcapy import findalldevs, open_live

from impacket.ImpactDecoder import EthDecoder, LinuxSLLDecoder


class DecoderThread(Thread):
    def __init__(self, pcapObj):
        # Query the type of the link and instantiate a decoder accordingly.
        datalink = pcapObj.datalink()
        if pcapy.DLT_EN10MB == datalink:
            self.decoder = EthDecoder()
        elif pcapy.DLT_LINUX_SLL == datalink:
            self.decoder = LinuxSLLDecoder()
        else:
            raise Exception("Datalink type not supported: " % datalink)

        self.pcap = pcapObj
        Thread.__init__(self)

    def run(self):
        # Sniff ad infinitum.
        # PacketHandler shall be invoked by pcap for every packet.
        self.pcap.loop(0, self.packetHandler)

    def packetHandler(self, hdr, data):
        # Use the ImpactDecoder to turn the rawpacket into a hierarchy
        # of ImpactPacket instances.
        # Display the packet in human-readable form.
        print(self.decoder.decode(data))


def getInterface():
    # Grab a list of interfaces that pcap is able to listen on.
    # The current user will be able to listen from all returned interfaces,
    # using open_live to open them.
    ifs = findalldevs()

    # No interfaces available, abort.
    if 0 == len(ifs):
        print("You don't have enough permissions to open any interface on this system.")
        sys.exit(1)

    # Only one interface available, use it.
    elif 1 == len(ifs):
        print('Only one interface present, defaulting to it.')
        return ifs[0]

    # Ask the user to choose an interface from the list.
    count = 0
    for iface in ifs:
        print('%i - %s' % (count, iface))
        count += 1
    idx = int(input('Please select an interface: '))

    return ifs[idx]

def main(filter):
    dev = getInterface()

    # Open interface for catpuring.
    p = open_live(dev, 1500, 0, 100)

    # Set the BPF filter. See tcpdump(3).
    p.setfilter(filter)

    print("Listening on %s: net=%s, mask=%s, linktype=%d" % (dev, p.getnet(), p.getmask(), p.datalink()))

    # Start sniffing thread and finish main thread.
    DecoderThread(p).start()

# Process command-line arguments. Take everything as a BPF filter to pass
# onto pcap. Default to the empty filter (match all).
filter = ''
if len(sys.argv) > 1:
    filter = ' '.join(sys.argv[1:])

main(filter)
  • python sniffer.py usa socket sin procesar para escuchar paquetes de datos y python sniff.py, usa pcapy para escuchar paquetes de datos
  • Esta consulta mostrará el tráfico local de su IP predeterminada. Este comando puede ser utilizado por los administradores de red. Esta consulta escucha el tráfico en ICMP, TCP, UDP
  • Solo mostrará el tráfico local
root@kali:/home/iicybersecurity/Downloads/impacket/examples# python sniffer.py
 Using default set of protocols. A list of protocols can be supplied from the command line, eg.: sniffer.py  [proto2] …
 ('Listening on protocols:', ('icmp', 'tcp', 'udp'))
 IP DF 10.10.10.179 -> 10.10.11.70
 TCP ack 1617 -> 22
 IP DF 10.10.10.179 -> 10.10.11.70
 TCP ack 1617 -> 22
 IP DF 10.10.10.179 -> 10.10.11.70
 TCP ack 1617 -> 22
 IP DF 10.10.10.179 -> 10.10.11.70
 TCP ack 1617 -> 22
 IP DF 10.10.10.179 -> 10.10.11.70
 TCP ack 1617 -> 22
IP DF 10.10.10.179 -> 10.10.11.70
 TCP ack 1617 -> 22
 IP 10.10.10.62 -> 10.10.11.255
 UDP 137 -> 137
 fa98 0110 0001 0000 0000 0000 2045 4545    ………… EEE
 4646 4445 4c46 4545 5046 4143 4e45 4e45    FFDELFEEPFACNENE
 4846 4146 4445 4f44 4746 4243 4100 0020    HFAFDEODGFBCA..
 0001                                       ..
1102 d5b6 0a0a 0b19 008a 00bb 0000 2045    ………….. E
 4545 4646 4445 4c46 4545 5046 4143 4e46    EEFFDELFEEPFACNF
 4546 4245 4244 4944 4945 4345 4343 4100    EFBEBDIDIECECCA.
 2046 4845 5046 4345 4c45 4846 4345 5046     FHEPFCELEHFCEPF
 4646 4143 4143 4143 4143 4143 4143 4142    FFACACACACACACAB
 4e00 ff53 4d42 2500 0000 0000 0000 0000    N..SMB%………
 0000 0000 0000 0000 0000 0000 0000 0000    …………….
 0000 1100 0021 0000 0000 0000 0000 00e8    …..!……….
 0300 0000 0000 0000 0021 0056 0003 0001    ………!.V….
 0000 0002 0032 005c 4d41 494c 534c 4f54    …..2.\MAILSLOT
 5c42 524f 5753 4500 0100 80fc 0a00 4445    \BROWSE…….DE
 534b 544f 502d 5451 4138 3842 4200 0a00    SKTOP-TQA88BB…
 0310 0000 0f01 55aa 00                     ……U..
 IP DF 10.10.10.179 -> 10.10.11.70
 TCP ack 1617 -> 22

Requests/Beautiful Soup

Este es el módulo muy popular. Todavía se usa al desarrollar herramientas de Python. Requests ayuda a los programadores a enviar HTTP sin codificación. Beautiful Soup se utiliza para obtener datos de HTML y XML. Beautiful Soup está perfectamente diseñado para crear ataques y cargas útiles. Muchas herramientas de seguridad populares como Eyewitness, SQLmap, theharvester utilizan dichas bibliotecas de Python.

  • El siguiente script extrae los datos de cualquier url. Por ejemplo, hemos usado github.com/events
>>>from bs4 import BeautifulSoup
>>>import requests
>>>url = raw_input("www.github.com/events: ")
>>>www.github.com/events:
>>>r  = requests.get("https://www.github.com" +url)     
>>>     
>>>     data = r.text
>>>soup = BeautifulSoup(data)
>>>for link in soup.find_all('a'):
…     print(link.get('href'))
…  
  • Los datos a continuación se recibirán después de compilar el script anterior
 start-of-content
https://github.com/
/join?source=header-home
/features
/features/code-review/
/features/project-management/
/features/integrations
/features/actions
/features/packages
/features/security
/features#team-management
/features#hosting
/customer-stories
/security
/enterprise
/explore
/topics
/collections
/trending
https://lab.github.com/
https://opensource.guide
https://github.com/events
https://github.community
https://education.github.com
/marketplace
/pricing
/pricing#feature-comparison
https://enterprise.github.com/contact
/nonprofit
https://education.github.com 

Libmap/Nmap

Libmap/Nmap que se utiliza en el escaneo de puertos. Python-nmap se implementa para automatizar el escaneo. Generalmente utilizado en administradores de red. Muchos scripts para libmap se usan desde nmap-scripts. Nmap es un analizador de redes muy popular utilizado por muchos pentesters. Esta es la mejor biblioteca de Python utilizada en el hacking ético.

  • El siguiente script funciona como escaneo de puertos nmap. Este script mostrará los puertos deseados. Para el ex puerto 22, se ingresan 443
>>>import nmap
>>>import sys
>>>import socket
>>>nmap = nmap.PortScanner()
… nmap.scan('74.50.111.244', '22-443')
{'nmap': {'scanstats': {'uphosts': '1', 'timestr': 'Sat Dec 14 02:58:57 2019', 'downhosts': '0', 'totalhosts': '1', 'elapsed': '128.20'}, 'scaninfo': {'tcp': {'services': '22-443', 'method': 'syn'}}, 'command_line': 'nmap -oX - -p 22-443 -sV 74.50.111.244'}, 'scan': {'74.50.111.244': {'status': {'state': 'up', 'reason': 'echo-reply'}, 'hostnames': [{'type': '', 'name': ''}], 'vendor': {}, 'addresses': {'ipv4': '74.50.111.244'}}}}      
  • La secuencia de comandos anterior muestra que ambos puertos están abiertos

Criptografía

La criptografía de Python es otra implementación para funciones criptográficas. Mostraremos cómo podemos generar mensajes secretos/confidenciales con una clave. Las claves podrán componerse de letras, números y caracteres especiales.

  • Mostraremos cómo se puede usar la biblioteca de criptografía para encriptar cualquier cadena de texto sin formato y luego para recuperar mensajes de texto sin formato de un mensaje encriptado. Debajo del código, una pequeña implementación de cifrado y descifrado
>>>from cryptography.fernet import Fernet
>>>key = Fernet.generate_key()
>>>f = Fernet(key)
>>>token = f.encrypt(b"hello international institute of cyber security")
>>>token       'gAAAAABd9LpH60RO0C4rN717L3CbHYsLaKlUxakNMFDRzROKIPZsmF04opFuIj2vvk6z2MJohuxEbDp5WrTuU2NWJq0fSwj_sUk81E6w3hNlz5zy4Sh7o_L5_AMWrES9DoenrkHlpDOr'
>>>'…'
'…'
>>>f.decrypt(token)
'hello international institute of cyber security'         
  • El script anterior ha generado aleatoriamente la clave cifrada y ha ejecutado el token de descifrado para mostrar un mensaje secreto. Arriba están las bibliotecas de python más utilizadas en hacking ético
  • El otro módulo de criptografía más popular que es ampliamente conocido como base64. El algoritmo más popular aún utilizado por muchas organizaciones para ocultar contraseñas
>>>import base64
>>>encoded_data = base64.b64encode("hello international institute of cyber security")
>>>print("Encoded text with base 64 is")
>>>Encoded text with base 64 is
>>>print(encoded_data)

aGVsbG8gaW50ZXJuYXRpb25hbCBpbnN0aXR1dGUgb2YgY3liZXIgc2VjdXJpdHk=     
  • Luego, descifraremos la cadena base64 anterior. La secuencia de comandos es la siguiente:
>>>import base64
>>>decoded_data = base64.b64decode("aGVsbG8gaW50ZXJuYXRpb25hbCBpbnN0aXR1dGUgb2YgY3liZXIgc2VjdXJpdHk=")
>>>print("decoded text is ")
>>>decoded text is 
>>>print(decoded_data)
hello international institute of cyber security   
  • Arriba muestra la cadena decodificada base64