Advertisement
tomerasher

agent.py

Jun 27th, 2017
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.28 KB | None | 0 0
  1. from scapy.all import *
  2. from scapy.layers.inet import IP, TCP, UDP
  3. import requests
  4. import socket
  5. from ipaddress import IPv4Address
  6. from subprocess import check_output
  7. import json
  8. import threading
  9.  
  10.  
  11. def filter(packet):
  12.     # Filter for sniffed packets
  13.     return IP in packet and (TCP in packet or UDP in packet)
  14.  
  15. def is_outgoing(packet):
  16.     # Returns if packet is outgoing by comparing own mac address with src of packet
  17.     return packet[Ether].src == MY_MAC
  18.  
  19. def get_IP(packet):
  20.     # Returns IP address of computer on the other hand
  21.     if is_outgoing(packet):
  22.         return packet[IP].dst
  23.     else:
  24.         return packet[IP].src
  25.  
  26. def get_country(IP):
  27.     # Returns country of computer on the other hand
  28.     if IP in found_addresses.keys():
  29.         return found_addresses[IP]
  30.  
  31.     # Checking if given IP argument is a global address, which is required to find source country.
  32.     if IPv4Address(IP).is_global:
  33.         r = requests.get('http://freegeoip.net/json/%s' % IP)
  34.     else:
  35.         # Finding global IP address using outer source.
  36.         global_ip = requests.get('http://ip.42.pl/raw').text
  37.         r = requests.get('http://freegeoip.net/json/%s' % global_ip)
  38.  
  39.     found_addresses[IP] = json.loads(r.text)['country_name']
  40.     return found_addresses[IP]
  41.  
  42. def get_port(packet):
  43.     # Returns port of computer on the other hand
  44.     if is_outgoing(packet):
  45.         return packet[TCP if TCP in packet else UDP].dport
  46.     else:
  47.         return packet[TCP if TCP in packet else UDP].sport
  48.  
  49. def get_self_port(packet):
  50.     # Returns local port
  51.     if is_outgoing(packet):
  52.         return packet[TCP if TCP in packet else UDP].sport
  53.     else:
  54.         return packet[TCP if TCP in packet else UDP].dport
  55.  
  56. def parse_netstat(packet):
  57.     # Function calls netstat and parses it every time called.
  58.     # The Function will parse to build dictionary of port to program.
  59.     # The Function will update global dictionary 'programs' every time.
  60.  
  61.     netstat = check_output('netstat -nb', shell=True).split(b'\r\n')[4:-1]
  62.     i = 0
  63.     while i < len(netstat):
  64.         try:
  65.             ports = [int(netstat[i][9:24].split(b':')[1])]
  66.             while i < len(netstat) and b'[' not in netstat[i]:
  67.                 ports.append(int(netstat[i][9:24].split(b':')[1]))
  68.                 i += 1
  69.  
  70.             if i < len(netstat) and b'[' in netstat[i]:
  71.                 program = netstat[i][netstat[i].index(b'[')+1:netstat[i].index(b']')]
  72.                 for port in ports:
  73.                     programs[port] = program
  74.         except (ValueError, IndexError):
  75.             continue
  76.         finally:
  77.             i += 1
  78.  
  79. def process(packet):
  80.     # Function receives packet and builds dictionary of data.
  81.     # The dictionary will be appended to global list 'packets'.
  82.     parse_netstat(packet)
  83.     packets.append(json.dumps(
  84.         {'IP': get_IP(packet),
  85.          'country': get_country(packet[IP].src),
  86.          'outgoing': is_outgoing(packet),
  87.          'PORT': get_port(packet),
  88.          'SIZE': len(packet),
  89.          'Process': programs.get(get_self_port(packet), b'Unknown').decode()}))
  90.  
  91. def start_thread(packet):
  92.     # Starts a thread for processing packet
  93.     process_thread = threading.Thread(target=process, args=packet)
  94.     process_thread.start()
  95.  
  96. def main():
  97.     SERVER_ADDR = '10.0.0.14'
  98.     SERVER_PORT = 42134
  99.  
  100.     # Defining dict globally for get_country function, which will update it (or use it) every time called
  101.     global found_addresses
  102.     found_addresses = {}
  103.  
  104.     # Finding mac address using a blank packet to check if packets are incoming or outgoing.
  105.     global MY_MAC
  106.     MY_MAC = (Ether() / IP(dst='localhost'))[Ether].src
  107.  
  108.     global programs
  109.     programs = {}
  110.  
  111.     # Holds data of all packets in current sniff round.
  112.     global packets
  113.  
  114.     manager = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  115.     while True:
  116.         packets = []
  117.         print('Sniffing Started')
  118.         sniff(lfilter=filter, prn=start_thread, count=100)
  119.         print('Done Sniffing')
  120.         print(packets)
  121.         # Separating every dictionary with an unlikely separator to split
  122.         # later in manager. (Converting to binary for socket)
  123.         data = '|||'.join(packets).encode()
  124.         manager.sendto(data, (SERVER_ADDR, SERVER_PORT))
  125.         print('Sent data')
  126. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement