Top Python Libraries Used In Hacking

Python is the most important language for pentesters/ security researchers. Python has many pre-build libraries which helps in scanning the network and gives many options to send request/ receive different packets to host. Now days python has become the most usable language among pentesters, as per ethical hacking researcher of international institute of cyber security. We will showing some most popular python libraries which will help users to understand how python is useful in ethical hacking.

You can install python on OS. We will using Kali Linux 2019.1 amd64. Kali Linux comes with many pre-installed python libraries. So you just need to import such python modules in order to use them.

  • Open terminal :
    • Type sudo apt-get update
    • Type sudo apt-get install python3
    • If using Kali Linux type pip3 install scapy

Top Python Libraries

Scapy

Scapy is most popular among many pentesters/ security tools developers. Scapy gives some tremendous options to send, sniff or forge data packets. Users can use it interactively or can import it directly. Users has to specify functions to use scapy. Scapy provides the functionality of nmap, arpspoof, wireshark and many other network scanners tools which are used in initial phase of pentesting.

  • Open terminal type python This command will open python environment.
  • Then type below commands
>>>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")
  • Above script is importing sys from scapy. Then sending 1 packet of ICMP. After getting response from target ip address it will print. The host is up.
  • Here you can enter any network protocol for checking if the host is up. Scapy provides large no of network protocols support.
  • Make sure to enter destination ip address in line : 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          
  • After running we ran wireshark to capture the packets send by python script.
  • Above screenshot from wireshark shows the sending & receiving of ICMP packet.

Impacket

Impacket works with network protocols & gives low level programming access to data packets. Core Impacket easily interacts with Windows like – MSSQL, SMB, NETBIOS and other protocols. Core impact provides pass the key attack scenarios. Network protocols like – TCP, UDP, ARP are featured with impacket. Impacket is designed as all in one module of python.

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 is comes with some samples. Which are used to collect information of any IP address in local network.
  • For that
    • Type cd examples
    • Type 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
  • We will showing some examples to show how impacket is used can be used to sniff/ reconnaissance.
  • We will start with 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)
  • Type 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
  • Above command will ping the specific ip address until you press Ctrl + C.
  • Type python sniffer.py/ python sniff.py shows the same output. The only diff in python sniff.py. It will ask for default network interface.
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 use raw socket for listening data packets & python sniff.py, use pcapy for listening data packets.
  • This query will show local traffic of your default IP. This command can be used by network administrators.This query listens traffic on ICMP, TCP, UDP
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
  • It will only show local traffic.

Requests/ Beautiful Soup

This the very popular module. Still used while developing python tools. Requests helps programmers to send HTTP without encoding. Beautiful Soup is used in grabbing data from HTML & XML. Beautiful Soup is perfectly designed for creating attacks & payloads. Many popular security tools like Eyewitness, SQLmap, theharvester uses such python libraries.

  • Below script extracts the data from any url. For example we have used github.com/events
>>>from bs4 import BeautifulSoup
>>>import requests
>>>url = raw_input("www.github.com/events: ")
>>>www.github.com/events:
>>>r  = requests.get("http://www.github.com" +url)     
>>>     
>>>     data = r.text
>>>soup = BeautifulSoup(data)
>>>for link in soup.find_all('a'):
…     print(link.get('href'))
…  
  • Below data will be received after compiling above script.
 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 which is used in port scanning. Python-nmap is implemented to automate the scanning. Generally used in Network administrators. Many scripts for libmap are used from nmap-scripts. Nmap is very popular network analyzer used by many pentesters. This is top python library used in hacking.

  • Below script works as nmap port scan. This script will show desired ports. For ex – port 22, 443 are entered.
>>>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'}}}}         
  • Above script shows both ports are open.

Cryptography

Python cryptography is another implementation for cryptographic functions. We will show how we can generate secret/ confidential messages with a key. Key can consists letters, numbers, special character.

  • We will show how cryptography library can be used to encrypt any plain text string, and then further to recover plain text message from encrypted message. Below code an small encryption & decryption implementation.
>>>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'         
  • Above script has randomly generated the encrypted key & it has run decrypt token to show secret message. Above are the most used python libraries in hacking.
  • The another most popular cryptography module which is widely known as base64. The most popular algorithm still used by many organization in password hiding.
>>>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=     
  • Then we will decrypt the above base64 string. Script is as under:
>>>import base64
>>>decoded_data = base64.b64decode("aGVsbG8gaW50ZXJuYXRpb25hbCBpbnN0aXR1dGUgb2YgY3liZXIgc2VjdXJpdHk=")
>>>print("decoded text is ")
>>>decoded text is 
>>>print(decoded_data)
hello international institute of cyber security         
  • Above shows base64 decoded string.