0

What is the easiest way to compare IP addresses using Scapy (in Python3.6) and Docker? I have a piece of code that sniffs my Docker bridge network using Scapy sniff(). I want to look at each packet's source IP address, and if it matches the IP address for my container named "plc1", do additional steps. If they don't match, I just return an empty list and move on.

However I cannot figure out how to compare a packet's source IP address to a container name. It really needs to be the container's name and not the ID, since I am running a ton of containers in parallel and looking up ID's to plug into my Python3.6 script is tedious. Any thoughts? I've tried using the Docker SDK but it needs the Container ID, which is what I am trying to avoid...

Sample Python3.6 code, which does not work, included below:

#!/usr/bin/env python3
from scapy.all import *

def find_ports(pkt):
    # if src IPaddr matches IP addr of container plc1...
    if pkt[IP].src == 'plc1': # THIS DOES NOT WORK
        # if there is a match, get some additional packet info
        if TCP in pkt:
            tcp_dport = pkt[TCP].dport
            ip_total_len = pkt.getlayer(IP).len
            ip_header_len = pkt.getlayer(IP).ihl * 32 / 8
            tcp_header_len = pkt.getlayer(TCP).dataofs * 32 / 8
            tcp_seg_len = ip_total_len - ip_header_len - tcp_header_len
            sequence_num = pkt[1].ack
            return [tcp_dport, tcp_seg_len, sequence_num]
    # else if NO MATCHING ip addr's, return blank list...
    else:
        return []


tempList = sniff(filter="ip", prn=find_ports, iface="br-19f0ba1cf88f")

# if templist not empty...
if tempList:
    # send a TCP RST packet...
    ip = IP(src="plc1", dst="hmi_pass_thru")
    tcp = TCP(sport=502, dport=tempList[0], flags="R", seq=int(tempList[1]), ack=int(tempList[2]) + 1)
    pkt = ip / tcp
    ls(pkt)
    send(pkt, verbose=0)
Vic
  • 33
  • 1
  • 9
  • If you're using docker-py, I might start by [`client.containers.list`](https://docker-py.readthedocs.io/en/stable/containers.html#docker.models.containers.ContainerCollection.list) all of the containers, and using that listing to find the IP address(es) of interest (or, if it's not just a single container, build a map from IP address to container name). – David Maze Apr 12 '21 at 04:26
  • @DavidMaze So I added some lines to my `find_ports` function to match your suggestion. Before the IF statement, I do: `client = docker.DockerClient()` then `container = client.containers.list(filters={"name": "5extraextranodes_plc1_1"})` then `ip_add = container.attrs['NetworkSettings']['IPAddress']` to find the IP address of container plc1. I get a "no such file or directory" error running this python container on the same bridge network as `plc1`. Get the same error if I change this python code's `network` to `host` mode. – Vic Apr 12 '21 at 15:15

0 Answers0