Using Python for IP addresses

Part of the day to day tasks of any Information Security professional may include transforming system input and output text and calculating IP addresses. In this article I demonstrate how use Python to work with IP addresses and transform system input/output.

A system that I manage at work doesn’t allow you to enter networks in CIDR notation like 192.168.0.0/24, it requires starting and ending IP addresses in a range like 192.168.0.1-192.168.0.254. In the past I’ve used ipcalc on Linux to calculate IP addresses when I have something other than a simple netmask to calculate. Today I had a list of IP subnets of various netmasks that I needed to transform into a comma separated list in the format of 192.168.0.1-192.168.0.254, 10.128.0.1-10.128.0.254…

I’m going to use the ipcalc module for Python to demonstrate how to do this. You can install it from an administrator cmd prompt or using root or sudo in a Linux terminal with the following command:

pip install ipcalc

Pretty simple to install. Now lets move on to a demonstration of how to use it. After importing the ipcalc module, I created a new object and attempted to output the first and last host on the network but it didn’t work quite as expected until I cast the output to string.

Python 2.7.12 (v2.7.12:d33e0cf91556, Jun 27 2016, 15:19:22) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import ipcalc
>>> subnet = ipcalc.Network('192.168.0.0/24')
>>> print subnet.host_first
<bound method Network.host_first of Network('192.168.0.0/24')>
>>> print str(subnet.host_first)
<bound method Network.host_first of Network('192.168.0.0/24')>
>>> print(str(subnet.host_first()))
192.168.0.1
>>> print str(subnet.host_first())
192.168.0.1
>>> print str(subnet.host_last())
192.168.0.254
>>> print str(subnet.broadcast())
192.168.0.255
>>> print str(subnet.info())
PRIVATE
>>> print str(subnet.to_ipv6())
2002:c0a8:0000:0000:0000:0000:0000:0000
>>> print str(subnet.size())
256
>>> ipaddress = ipcalc.IP('192.168.0.128/24')
>>> print str(ipaddress.subnet())
24
>>> print str(ipaddress.info())
PRIVATE
>>> print str(ipaddress.guess_network())
192.168.0.0/24
>>>

Now I’m going to take an input file with a network name followed by network address in CIDR format on each line, cut out just the subnet, and output the networks in firsthost-lasthost,firsthost-lasthost,…” format.

>>> with open('ips.txt') as f:
    content = f.readlines()

    
>>> content = [x.strip() for x in content]

>>> import sys
>>> for x in content:
    subnet = x.split(' ')[-1]
    networkobj = ipcalc.Network(subnet)
    sys.stdout.write("%s-%s," % (str(networkobj.host_first()),str(networkobj.host_last())))

In the code above, I loop through each line of the file and get the last word in the string which is the subnet address. It was necessary to use sys.stdout.write() to get rid of the space between each network start and end addresses using Python 2.7. I’m not going to show you the output. If you want to know my public IP addresses then you’ll have to work to find them yourself. 🙂

I’m sure that there are more than one way to write the code for this exercise. If you have any constructive feedback please leave a comment. Thanks for visiting!

Python Exploits – Generate all hex chars to find badchars

While preparing for my OSCP exam, I’m reviewing the buffer overflow lessons and needed an easy way to generate all hex characters to test for bad characters in my exploit. Using “print(“\x” + format(x, ‘x’))” results in a character on each line, and adding a comma after the print statement keeps it all on the same line, but the output has spaces between characters. You can generate the output you need, all on the same line and without spaces using “sys.stdout.write”.

Here’s a simple python snippet to do that:

Hacking the network with Scapy and Python

I’ve been learning Python for infosec work. Scapy is built on Python and allows you to interact with the network at a much lower level than the Python sockets library. If I were to say it allows you to build your own packets/frames that would be an understatement.

From the Scapy home page:

What is Scapy

Scapy is a powerful interactive packet manipulation program. It is able to forge or decode packets of a wide number of protocols, send them on the wire, capture them, match requests and replies, and much more. It can easily handle most classical tasks like scanning, tracerouting, probing, unit tests, attacks or network discovery (it can replace hping, 85% of nmap, arpspoof, arp-sk, arping, tcpdump, tethereal, p0f, etc.). It also performs very well at a lot of other specific tasks that most other tools can’t handle, like sending invalid frames, injecting your own 802.11 frames, combining technics (VLAN hopping+ARP cache poisoning, VOIP decoding on WEP encrypted channel, …), etc. See interactive tutorial and the quick demo: an interactive session (some examples may be outdated).

What makes scapy different from most other networking tools

First, with most other tools, you won’t build someting the author did not imagine. These tools have been built for a specific goal and can’t deviate much from it. For example, an ARP cache poisoning program won’t let you use double 802.1q encapsulation. Or try to find a program that can send, say, an ICMP packet with padding (I said padding, not payload, see?). In fact, each time you have a new need, you have to build a new tool.

Second, they usually confuse decoding and interpreting. Machines are good at decoding and can help human beings with that. Interpretation is reserved to human beings. Some programs try to mimic this behaviour. For instance they say “this port is open” instead of “I received a SYN-ACK”. Sometimes they are right. Sometimes not. It’s easier for beginners, but when you know what you’re doing, you keep on trying to deduce what really happened from the program’s interpretation to make your own, which is hard because you lost a big amount of information. And you often end up using tcpdump -xX to decode and interpret what the tool missed.
Third, even programs which only decode do not give you all the information they received. The network’s vision they give you is the one their author thought was sufficient. But it is not complete, and you have a bias. For instance, do you know a tool that reports the padding ?
Scapy tries to overcome those problems. It enables you to build exactly the packets you want. Even if I think stacking a 802.1q layer on top of TCP has no sense, it may have some for somebody else working on some product I don’t know. Scapy has a flexible model that tries to avoid such arbitrary limits. You’re free to put any value you want in any field you want, and stack them like you want. You’re an adult after all.
In fact, it’s like building a new tool each time, but instead of dealing with a hundred line C program, you only write 2 lines of Scapy.
After a probe (scan, traceroute, etc.) Scapy always gives you the full decoded packets from the probe, before any interpretation. That means that you can probe once and interpret many times, ask for a traceroute and look at the padding for instance.

Here are my notes on Scapy. For detailed usage examples see the link below.

  • The ls() command shows a list of all available protocols.
    • For a listing of individual protocol options and defaults, use ls(protocol). For example ls(TCP)
  • To see a list of scapy commands: lsc()
  • Packets need to be created from a header perspective:
    • Ethernet | IP | TCP/UDP | Application
    • Ether()/IP()/TCP()/Data
  • Send a layer 3 packet ICMP example: (scapy handles the ethernet frame for you)
    • pkt = IP(dst=”google.com”)/ICMP()/”data”)
    • send(pkt)
  • To send a layer 3 TCP packet, you must add a port.
    • pkt = IP(dst=”google.com”)/TCP()/(dport=23))
  • For an easier to read format of your sent or received packet, use: variablename.show()
  • To add a layer 2 frame you must add the ethernet header and include the interface. Note that we are now using sendp vs send.
    • example: sendp(Ether()/IP(dst=”google.com”)/ICMP()/”data”, iface=”eth0″)
  • Sending a packet repeatedly:
    • sendp(Ether()/IP(dst=”google.com”)/ICMP()/”data”, iface=”eth0″, loop=1)
  • To add a sending interval: (Interval is seconds)
    • sendp(Ether()/IP(dst=”google.com”)/ICMP()/”data”, iface=”eth0″, inter=1)
  • So far we have only seen the sent packets. To send and receive:
    • Layer 3:
      • sr() returns answers and unanswered packets
        • sr(IP(dst=”google.com”)/ICMP()/”data”)
      • To see the response (or lack of)
        • response, no_response = _
        • response[0]
        • no_response[0]
        • In Python,  the “_” variable is used to store the result of the last evaluation.
      • sr1() returns only answer or sent packets (1 packet)
    • Layer 2:
      • srp()
      • srp1()
  • You can manipulate the routing table in scapy without affecting the global routing table which is useful when you have a multihomed host.
    • Show the routing table: conf.route
    • add a host route: conf.route.add(host=”192.168.1.10″, gw=”192.168.1.22″)
    • add a network route: conf.route.add(net=”192.168.10.1/24″, gw=”192.168.1.23″)
    • To reset scapy’s routing table: conf.route.resync()
  • Packet sniffing: pkts = sniff(iface=”eth0″, filter=”arp”, count=3)
    • Allows the use of bpf (Berkely packet filters)
    • Save sniffed packets to a file: pkts = sniff(offline=”offline.pcap”)
    • Print packets live while sniffing:
      • pkts=sniff(iface=”eth0″, filter=”arp”, count=20, prn=lambda x: x.summary())
  • Write packets to a pcap file: wrpcap(“demo.pcap”, pkts)

  • Read packets from a pcap file: rdpcap(“demo.pcap”)

Python script to search Cisco CUCM Call Detail Records

If you manage Cisco CUCM and get requests for Call Detail Records, you know how frustrating it can be to have to:
  1. import the csv file to Excel
  2. delete out all but 4 of over 60 columns
  3. search thousands of rows of data to narrow down to the one extension
  4. convert epoch time to something a human understands
The first time I had to fulfill a request for call records, it took me most of the day to figure it out. Before I wrote this script it took me an average of a couple hours. That’s two hours too long. With this script and Python installed, you can have a csv file to import into Excel in seconds.