Example #1
0
 def __init__(self, interface):
     """
     Init initialise all the variable either if there are not used (e.g: 
     server variable when used as a client). Note: The default state is Closed
     """
     Layer.__init__(self)
     self.name = "TCP"  #Should stay here ! (otherwise will override real tcp layer in transversal_layer_access)
     self.ipregex = re.compile("^(\d{1,3}.){3}.\d{1,3}$")
     self.state = State_CLOSED(self)
     self.interface = interface
     self.localIP = get_if_addr(interface)
     self.localPort = None
     self.remoteIP = None
     self.remotePort = None
     self.connectionID = None
     #--Server related variables
     self.connections = [
     ]  #Used when server to know how many clients are connected ..
     self.nbconntoaccept = 0
     self.currentconnection = 0
     self.newinstance = None  #When client connect either we send him on the same application or create a new instance
     #----
     self.seqNo = 0
     self.ackNo = 0
     self.toAck = 0
     self.nextAck = 0
     self.lastPacket = None
     self.local_mss = 1460  #TODO: change it to be dynamic (RFC 879 default value is 536
     self.remote_mss = None
     self.syn_retries = int(
         open("/proc/sys/net/ipv4/tcp_syn_retries", "r").read())
Example #2
0
class Responder(Plugin):
    name = "Responder"
    optname = "responder"
    desc = "Poison LLMNR, NBT-NS and MDNS requests"
    #implements = ["handleResponse"]
    has_opts = True

    def initialize(self, options):
        '''Called if plugin is enabled, passed the options namespace'''
        self.options = options
        self.interface = options.interface

        if os.geteuid() != 0:
            sys.exit("[-] Responder plugin requires root privileges")

        try:
            config = options.configfile['Responder']
        except Exception, e:
            sys.exit('[-] Error parsing config for Responder: ' + str(e))

        try:
            self.ip_address = get_if_addr(options.interface)
            if self.ip_address == "0.0.0.0":
                sys.exit("[-] Interface %s does not have an IP address" %
                         self.interface)
        except Exception, e:
            sys.exit("[-] Error retrieving interface IP address: %s" % e)
Example #3
0
def get_local_ip(all=True):
    """Fetches all the local network address
    """
    ips = OrderedSet()
    wan_ipv4 = get_host_ip()
    ips.add(wan_ipv4)
    if not all:
        return list(ips)

    wan_ipv6 = get_host_ipv6()
    if wan_ipv6:
        ips.add(wan_ipv6)

    if WINDOWS:
        from scapy.all import IFACES
        for iface in sorted(IFACES):
            dev = IFACES[iface]
            ips.add(dev.ip)
    else:
        for iface in get_if_list():
            ipv4 = get_if_addr(iface)
            if ipv4 != '0.0.0.0':
                ips.add(ipv4)

    return list(ips)
Example #4
0
def main():

    if len(sys.argv) < 3:
        print 'pass 2 arguments: <destination> "<message>"'
        exit(1)

    addr = socket.gethostbyname(sys.argv[1])
    iface = get_if()
    ip_addr = get_if_addr(iface)
    #print 'iface  %s' % iface
    #print 'iface ip @ %s' % ip_addr
    pkt = Ether(src=get_if_hwaddr(iface), dst="ff:ff:ff:ff:ff:ff") / IP(
        src=ip_addr, dst=addr, options=IPOption_MRI(
            count=0, swtraces=[])) / UDP(dport=4321, sport=1234) / sys.argv[2]

    #   pkt = Ether(src=get_if_hwaddr(iface), dst="ff:ff:ff:ff:ff:ff") / IP(
    #       dst=addr, options = IPOption_MRI(count=2,
    #           swtraces=[SwitchTrace(swid=0,qdepth=0), SwitchTrace(swid=1,qdepth=0)])) / UDP(
    #           dport=4321, sport=1234) / sys.argv[2]
    pkt.show2()
    #hexdump(pkt)
    try:
        for i in range(int(sys.argv[3])):
            sendp(pkt, iface=iface)
            sleep(1)
    except KeyboardInterrupt:
        raise
Example #5
0
def connectTCP():
    # create tcp socket
    tcpServerPort = 2019
    tcpServerSocket = socket(AF_INET, SOCK_STREAM)
    tcpServerSocket.bind((scapy.get_if_addr(scapy.conf.iface), tcpServerPort))
    tcpServerSocket.settimeout(10)
    tcpServerSocket.listen()
Example #6
0
def get_local_ip(all=True):
    """Fetches all the local network address
    """
    ips = OrderedSet()
    wan_ipv4 = get_host_ip()
    ips.add(wan_ipv4)
    if not all:
        return list(ips)

    wan_ipv6 = get_host_ipv6()
    if wan_ipv6:
        ips.add(wan_ipv6)

    # fix https://github.com/BVLC/caffe/issues/861
    os.environ["MPLBACKEND"] = "Agg"

    # fix https://github.com/secdev/scapy/issues/3216
    logging.getLogger("scapy").setLevel(logging.ERROR)

    from scapy.all import WINDOWS, get_if_list, get_if_addr

    if WINDOWS:
        from scapy.all import IFACES
        for iface in sorted(IFACES):
            dev = IFACES[iface]
            ips.add(dev.ip)
    else:
        for iface in get_if_list():
            ipv4 = get_if_addr(iface)
            if ipv4 != '0.0.0.0':
                ips.add(ipv4)

    return list(ips)
Example #7
0
    def __init__(self, **config_params):
        """Initialize the class with the required network and packet params.

        Args:
            config_params: contains all the necessary packet parameters.
              Some fields can be generated automatically. For example:
              {'subnet_mask': '255.255.255.0',
               'dst_ipv4': '192.168.1.3',
               'src_ipv4: 'get_local', ...
              The key can also be 'get_local' which means the code will read
              and use the local interface parameters
        """
        interf = config_params['interf']
        self.packet = None
        self.dst_mac = config_params['dst_mac']
        if config_params['src_mac'] == GET_FROM_LOCAL_INTERFACE:
            self.src_mac = scapy.get_if_hwaddr(interf)
        else:
            self.src_mac = config_params['src_mac']

        self.dst_ipv4 = config_params['dst_ipv4']
        if config_params['src_ipv4'] == GET_FROM_LOCAL_INTERFACE:
            self.src_ipv4 = scapy.get_if_addr(interf)
        else:
            self.src_ipv4 = config_params['src_ipv4']
Example #8
0
 def __init__(self, interface):
     """
     Init initialise all the variable either if there are not used (e.g: 
     server variable when used as a client). Note: The default state is Closed
     """
     Layer.__init__(self)
     self.name = "TCP" #Should stay here ! (otherwise will override real tcp layer in transversal_layer_access)
     self.ipregex = re.compile("^(\d{1,3}.){3}.\d{1,3}$")
     self.state = State_CLOSED(self)
     self.interface = interface
     self.localIP = get_if_addr(interface)
     self.localPort = None
     self.remoteIP = None
     self.remotePort = None
     self.connectionID = None
     #--Server related variables
     self.connections = []  #Used when server to know how many clients are connected ..
     self.nbconntoaccept = 0
     self.currentconnection = 0
     self.newinstance = None  #When client connect either we send him on the same application or create a new instance
     #----
     self.seqNo = 0
     self.ackNo = 0
     self.toAck = 0
     self.nextAck = 0
     self.lastPacket = None
     self.local_mss = 1460 #TODO: change it to be dynamic (RFC 879 default value is 536
     self.remote_mss = None
     self.syn_retries = int(open("/proc/sys/net/ipv4/tcp_syn_retries", "r").read())
Example #9
0
def wait_for_dhcp(interface_name):
    """Wait the DHCP address assigned to desired interface.

    Getting DHCP address takes time and the wait time isn't constant. Utilizing
    utils.timeout to keep trying until success

    Args:
        interface_name: desired interface name
    Returns:
        ip: ip address of the desired interface name
    Raise:
        TimeoutError: After timeout, if no DHCP assigned, raise
    """
    log = logging.getLogger()
    reset_host_interface(interface_name)
    start_time = time.time()
    time_limit_seconds = 60
    ip = '0.0.0.0'
    while start_time + time_limit_seconds > time.time():
        ip = scapy.get_if_addr(interface_name)
        if ip == '0.0.0.0':
            time.sleep(1)
        else:
            log.info('DHCP address assigned to %s as %s' %
                     (interface_name, ip))
            return ip
    raise TimeoutError('Timed out while getting if_addr after %s seconds.' %
                       time_limit_seconds)
Example #10
0
def poison():
    iface = raw_input("Interface [eth0]:") or "eth0"
    target = raw_input("Enter target IP:")
    forged = raw_input("Enter fake IP:")
    if target != "" and forged != "" and ip_misc.check_IP(
            target) and ip_misc.check_IP(forged):
        try:
            mac = get_if_hwaddr(iface)
            my_ip = get_if_addr(iface)
            ip_misc.enable_forward()
            if mac != "00:00:00:00:00:00":
                #targeted attack (one machine's arp cache poisoned)
                packet = Ether() / ARP(
                    op="who-has", hwsrc=mac, psrc=forged, pdst=target)
                print "Now poisoning and redirecting traffic... Start a sniffer to check!\nPress Ctrl+C to stop."
                try:
                    while True:
                        sendp(packet)
                        time.sleep(2)
                except KeyboardInterrupt:
                    ip_misc.disable_forward()
                return True
        except IOError:
            print "Wrong interface, check again."
            return False
Example #11
0
def main():
    """ Entry point to the program. """
    pkt_cfg = vars(__parse_args())
    print pkt_cfg
    pkt_cfg['sip'] = get_if_addr(pkt_cfg['interface'])

    tcp_send(pkt_cfg)
Example #12
0
    def sniff(self):
        s = socket.socket(socket.PF_PACKET, socket.SOCK_RAW,
                          socket.htons(0x0003))
        r = redis.Redis(unix_socket_path='/var/run/redis/redis.sock')
        src_ip = get_if_addr("eth0")  # dstip?
        parse1 = parse.parse()

        while True:
            data = s.recv(2048)
            if not data:
                print("Client has exist")
                break
            rs = parse1.filter(data)
            # rs= dip,dmac,port1,port2,port3,delta_time # srcip? srcmac? port_list, delta_time
            if rs != None:
                # Convert each element in port_list into str
                for i in range(len(rs[2])):
                    rs[2][i] = str(rs[2][i])
                fmt = [src_ip, rs[0], rs[1]] + rs[2]
                key = "+".join(fmt)
                value = rs[3]
                print("{}, {}".format(key, value))
                r.set(key, value)
                r.pexpire(key, 3000)
        s.close()
Example #13
0
    def __get_mac_of_ip(self, my_iface, srv_ip):
        srv_mac = 'FF:FF:FF:FF:FF:FF'
        my_ip = get_if_addr(my_iface)
        reply = None
        Retries = ARP_RETRIES

        #        print('    ... sending ARP-Request %s -> %s ...' % (my_ip,srv_ip))

        while reply is None and Retries > 0:
            Retries -= 1
            reply = sr1(ARP(op='who-has', psrc=my_ip, pdst=srv_ip),
                        timeout=1,
                        verbose=False)

        if reply is not None:
            if reply.psrc == srv_ip:
                srv_mac = reply.hwsrc
#                print('    ++ ARP = %s -> %s' % (reply.hwsrc,reply.psrc))
            else:
                print('    !! ERROR on ARP: Invalid Response = %s -> %s' %
                      (reply.hwsrc, reply.psrc))
        else:
            print('    !! ERROR on ARP: No Resonse for %s !!' % (srv_ip))

        return srv_mac
Example #14
0
 def __init__(self, filter):
     super().__init__()
     self.filter = "host %s" % filter
     self.daemon = True
     self.socket = None
     self.use_pcap = True
     self.is_admin = False
     logger.info(
         'Local network adapter information, choose a network you want to '
         'capture.')
     message = '----- Local IP Address -----\n'
     ifaces = []
     if WINDOWS:
         import ctypes
         from scapy.all import IFACES
         if ctypes.windll.shell32.IsUserAnAdmin():
             self.is_admin = True
         for i, iface in enumerate(sorted(IFACES)):
             dev = IFACES[iface]
             ifaces.append(dev.description)
             message += "{0}   {1}    {2}\n".format(i, dev.description,
                                                    dev.ip)
     else:
         if os.getuid() == 0:
             self.is_admin = True
         ifaces = get_if_list()
         for i, iface in enumerate(ifaces):
             ip = get_if_addr(iface)
             message += "{0}   {1}    {2}\n".format(i, iface, ip)
     data_to_stdout(message)
     choose = input('Choose>: ').strip()
     self.interface = ifaces[int(choose)]
     self.use_pcap = True
     self.stop_sniffer = Event()
     self.pcap = None
 def __init__(self):
     self.MAC = get_if_hwaddr(conf.iface)
     self.IP = get_if_addr(conf.iface)
     self.IPv6_1 = get_if_addr6(conf.iface)
     self.IPv6_2 = conf.route6.route()[1]
     self.IPv6_3 = "fe80::" + ":".join(self.IPv6_1.split(":")[-4:])
     self.RAW_IP = bytes([int(number) for number in self.IP.split(".")])
     self.run = True
Example #16
0
 def __init__(self,serverPort,udp_port):
     self.serverIP= get_if_addr("eth1")
     self.serverPort = serverPort
     self.UdpPort=udp_port
     self.Game=False
     self.bufferSize = 2048
     self.group_number=0
     self.all_teams={}
Example #17
0
def get_ip(interface):
    try:
        ip_address = get_if_addr(interface)
        if (ip_address == "0.0.0.0") or (ip_address is None):
            shutdown("Interface {} does not have an assigned IP address".format(interface))

        return ip_address
    except Exception as e:
        shutdown("Error retrieving IP address from {}: {}".format(interface, e))
Example #18
0
 def __init__(self, iface):
     """
     Takes the interface in argument to be able to distinguish
     the local MAC from others. The arp_cache is also instantiated empty.
     """
     Layer.__init__(self)
     self.arp_cache = {}
     self.hwaddr = ARP().hwsrc
     self.ip = get_if_addr(iface)
Example #19
0
def get_ip_of_interface(interfaces_list):
    interfaces = {}
    for iface in interfaces_list:
        ip_address = get_if_addr(iface)
        if (ip_address == "0.0.0.0") or (ip_address is None):
            interfaces[iface] = "None"
        else:
            interfaces[iface] = ip_address

    return interfaces
Example #20
0
def main():
    host = socket.gethostname()
    port = 2074  #  port number that gave us
    client_socket = socket.socket()
    client_socket.bind((scapy.get_if_addr('wlp2s0'), 8080))
    while True:
        try_to_connect(client_socket, host, port)
        client_socket.close()
        print("Server disconnected, listening for offer requests...")
        client_socket = socket.socket()
Example #21
0
    def run(self):
        if self.target == "" or self.target.lower() == "localhost":
            self.gom.echo("[!] No target (or valid target) selected.")
            return False

        conf.verb = 2
        self.address = get_if_addr(get_working_if())
        self.gom.echo("[+] Using " + str(self.address))
        dns_spoof(joker=self.address, match={"any": self.target})
        return True
Example #22
0
    def run(self):
        if self.target == "" or self.target.lower() == "localhost":
            self.gom.echo( "[!] No target (or valid target) selected." )
            return False

        conf.verb = 2
        self.address = get_if_addr(get_working_if())
        self.gom.echo( "[+] Using " + str(self.address) )
        dns_spoof(joker=self.address, match={"any":self.target})
        return True
Example #23
0
def main():

    iface = get_if()

    pkt = Ether(src=get_if_hwaddr(iface), dst='ff:ff:ff:ff:ff:ff', type=1793)
    pkt = pkt / '\x00\x00' / '\x08\x00' / IP(src=get_if_addr(iface),
                                             dst='255.255.255.255')

    while True:
        sendp(pkt, iface=iface, verbose=False)
        time.sleep(0.09)
def default(gateway_ip=""):
    if not gateway_ip:
        gateway_ip = net.conf.route.route("0.0.0.0")[2]

    return {
        "this":
        Machine(net.get_if_addr(net.conf.iface),
                net.get_if_hwaddr(net.conf.iface)),
        "gateway":
        Machine(gateway_ip)  #set manually if needed
    }
def getAddresses():
    from scapy.all import get_if_addr, get_if_list
    from ipaddr import IPAddress
    addresses = set()
    for i in get_if_list():
        try:
            addresses.add(get_if_addr(i))
        except:
            pass
    if '0.0.0.0' in addresses:
        addresses.remove('0.0.0.0')
    return [IPAddress(addr) for addr in addresses]
def get_mac(ip, interface):
    local_ip = scapy.get_if_addr(interface)
    if local_ip == ip:
        return scapy.Ether().src

    arp_request = scapy.ARP(pdst=ip)
    broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
    arp_request_broadcast = broadcast/arp_request
    response = scapy.srp(arp_request_broadcast, timeout=1, verbose=False)[0]

    for packet in response:
        return packet[1].hwsrc
Example #27
0
    def __init__(self):
        # setting logger
        root_logger = logging.getLogger()
        root_logger.setLevel(logging.DEBUG)

        handler = logging.FileHandler(os.path.dirname(os.path.realpath(__file__)) + r'\logs\{:%Y-%m-%d-%H-%M}.log'.format(datetime.datetime.now()),
                                      'w', 'utf-8')  # or whatever
        root_logger.addHandler(handler)
        self.ip = scapy.get_if_addr(scapy.conf.iface)
        self.pck_counter = 0
        self.timeout = 60
        self.period = 60
Example #28
0
def send_offers(sock, port):  #for sending the offers through UDP
    CLIENT_PORT = 13117
    BROADCAST_ADDR = ".255.255"
    adds = get_if_addr('eth1').split(".")
    SEND_UDP_TO = adds[0] + "." + adds[1] + BROADCAST_ADDR
    while True:
        if lock.locked(
        ):  #continue sending until 10 seconds have passed, then the lock will lock and func will end
            return
        sock.sendto(struct.pack("!IbH", 0xfeedbeef, 0x02, port),
                    (SEND_UDP_TO, CLIENT_PORT))
        time.sleep(1.0)
Example #29
0
    def sniff(self):
        s = socket.socket(socket.PF_PACKET, socket.SOCK_RAW,
                          socket.htons(0x0003))
        r = redis.Redis(
            unix_socket_path='/var/run/redis/redis.sock')  # aging database
        r2 = redis.Redis(unix_socket_path='/var/run/redis/redis.sock',
                         db=1)  # persist database
        r4 = redis.Redis(unix_socket_path='/var/run/redis/redis.sock',
                         db=3)  # data database
        src_ip = get_if_addr("eth0")
        parse1 = parse.parse()
        while True:
            data = s.recv(2048)
            if not data:
                print("Client has exist")
                continue

            rs = parse1.filter(
                data
            )  # None: data packet without int info; False: not data packet

            # rs= dip,dmac,port1,port2,port3,delta_time
            if rs != None:
                if rs != False:
                    r4.incr('receive')
                    # continue
                else:
                    continue
                for int_info in rs:
                    # print(int_info)
                    key = str(int_info[0]) + '-' + str(int_info[1])
                    # value=[int_info[2],int_info[3]]
                    if r2.exists(key) == True:  # find this key
                        v = int(r2.lindex(key, 0))
                        if v < int_info[2]:
                            r2.lset(key, 0, int_info[2])
                            r2.lset(key, 1, int_info[3])
                            if r.exists(key) == True:
                                r.persist(key)
                                r.lset(key, 0, int_info[2])
                                r.lset(key, 1, int_info[3])
                                r.pexpire(key, TIME_OUT)
                            else:
                                # print(key)
                                r.lpush(key, int_info[2], int_info[3])
                                r.pexpire(key, TIME_OUT)
                    else:  #not find this key
                        r2.lpush(key, int_info[2], int_info[3])
                        r.lpush(key, int_info[2], int_info[3])
                        r.pexpire(key, TIME_OUT)

        s.close()
Example #30
0
def main():
    """ Entry point to the program. """
    pkt_cfg = vars(__parse_args())

    pkt_cfg['sip4'] = get_if_addr(pkt_cfg['interface'])
    pkt_cfg['smac'], pkt_cfg['dmac'] = \
        mac_get(pkt_cfg['sip4'], pkt_cfg['dip4'])
    print pkt_cfg

    load_contrib('vxlan')
    outer_pkt = build_outer_pkt(pkt_cfg)
    inner_pkt = build_inner_pkt(pkt_cfg)
    send_pkt(pkt_cfg, outer_pkt/inner_pkt)
Example #31
0
    def initialize(self, options):
        Inject.initialize(self, options)
        self.target_ip = options.host
        self.html_payload = self._get_data()

        if self.target_ip is None:
            try:
                self.target_ip = get_if_addr(options.interface)
                if self.target_ip == "0.0.0.0":
                    sys.exit("[-] Interface %s does not have an IP address" %
                             options.interface)
            except Exception, e:
                sys.exit("[-] Error retrieving interface IP address: %s" % e)
Example #32
0
    def run(self):
        if self.target == "" or self.target.lower() == "localhost":
            self.gom.echo( "[!] No target (or valid target) selected." )
            return False

        conf.verb = 2
        self.address = get_if_addr(get_working_if())
        self.gom.echo( "[+] Using " + str(self.address) )
        self.gom.echo( "  --> Cache poisoning, interval " + str(self.interval) )
        if user_data['isGui'] == False:
            self.gom.echo( "Press Ctrl+C to cancel" )
        arpcachepoison(self.address, self.target, self.interval)
        return True
def main():

    iface = get_if()

    pkt = Ether(src=get_if_hwaddr(iface), dst='ff:ff:ff:ff:ff:ff', type=1793)
    #pkt = pkt / '\x00\x00' / '\x08\x00' / IP(src=get_if_addr(iface),dst='255.255.255.255')
    pkt = pkt / Custom(intopt=0x0000, proto=0x0800) / IP(
        src=get_if_addr(iface), dst='255.255.255.255')

    while True:
        sendp(pkt, iface=iface, verbose=False)
        print(pkt.show(dump=False), flush=True)
        time.sleep(1)
Example #34
0
def getAddresses():
    from scapy.all import get_if_addr, get_if_list
    from ipaddr import IPAddress

    addresses = set()
    for i in get_if_list():
        try:
            addresses.add(get_if_addr(i))
        except:
            pass
    if '0.0.0.0' in addresses:
        addresses.remove('0.0.0.0')
    return [IPAddress(addr) for addr in addresses]
Example #35
0
 def __init__(self, iface=None):
     """
     Init instantiate quite a lot of class attribute like
     ips, ports, datas etc..
     """
     Layer.__init__(self)
     self.data = []
     self.mutex = Lock()
     self.connectionID = None
     self.ipregex = re.compile("^(\d{1,3}.){3}.\d{1,3}$")
     self.interface = iface if iface else conf.route.route("0.0.0.0")[0]
     self.localIP = get_if_addr(self.interface)
     self.remoteIP = None
     self.localPort = random.randrange(0, (2**16) - 1)
     self.remotePort = None
Example #36
0
  def pinger(self, host_num):
    """thread pinger function"""
    hostadrr = get_if_addr(conf.iface).split('.')[:-1]
    hostadrr = '.'.join(hostadrr) + '.' + repr(host_num)
    line = getoutput("ping -n -c 1 %s 2> /dev/null" % hostadrr)

    while True:
      if line.find(hostadrr) and line.find("bytes from") > -1:  # Host Active
        is_active = []
        is_active.append(hostadrr)
        alive_host = is_active.pop()
        print("Host %s is \033[92m Active \033[0m" % alive_host)
        break
      elif line.find(hostadrr) and line.find(
          "Unreachable") > -1:  # No response from host
        not_active = []
        not_active.append(hostadrr)
        not_alive_host = not_active.pop()
        print("\033[91m No response from \033[0m", not_alive_host)
        break
      else:
        exit(0)
Example #37
0
try:
    cmd_opts = "d:g:i:s:"
    opts, args = getopt.getopt(sys.argv[1:], cmd_opts)
except getopt.GetoptError:
    usage()

for opt in opts:
    if opt[0] == "-i":
        dev = opt[1]
    elif opt[0] == "-g":
        gateway = opt[1]
    elif opt[0] == "-d":
        nameserver = opt[1]
    elif opt[0] == "-s":
        dhcpserver = opt[1]
    else:
        usage()

if not gateway:
    gateway = scapy.get_if_addr(dev)

if not nameserver:
    nameserver = gateway

if not dhcpserver:
    dhcpserver = gateway

print "Hijacking DHCP requests on %s" % (dev)
scapy.sniff(iface=dev, filter=filter, prn=handle_packet)

Example #38
0
 def run(self):
     conf.verb = 2
     self.address = get_if_addr(get_working_if())
     self.gom.echo("[+] Using " + str(self.address))
     farpd()
     return True
Example #39
0
    def _analyze_packets_no_host(self, packets):
        """
        Analyze a list of packets for interesting traffic when the host is
        unknown.
        """
        from scapy.all import get_if_addr
        from scapy.all import IP
        from scapy.all import TCP
        from scapy.all import UDP

        # This is hard to do...
        possible_packets = []
        possible_hosts = {}
        good_ports = []
        good_hosts = []

        for p in packets:

            # Analyze TCP
            #
            # 0x2 flag is SYN
            if p.haslayer(TCP) and p[TCP].dport in self._tcp_ports and\
            p[IP].dst in get_if_addr(self._iface) and p[TCP].flags == 0x2:

                possible_packets.append(p)
                if p[IP].src in possible_hosts:
                    possible_hosts[p[IP].src] += 1
                else:
                    possible_hosts[p[IP].src] = 1

            # Analyze UDP
            if p.haslayer(UDP) and p[UDP].dport in self._udp_ports and\
                    p[IP].dst in get_if_addr(self._iface):

                possible_packets.append(p)
                if p[IP].src in possible_hosts:
                    possible_hosts[p[IP].src] += 1
                else:
                    possible_hosts[p[IP].src] = 1

        for p in possible_packets:
            om.out.debug('[extrusionServer] Possible packet: ' + p.summary())

        # Now get the one that has more probability of being the one... and
        # report the list of ports
        def sortfunc(x, y):
            return cmp(x[1], y[1])
        items = possible_hosts.items()
        items.sort(sortfunc)

        # Now I report the ports for the hosts with more connections
        i = 0
        while i < len(items) and items[0][1] == items[i][1]:
            good_hosts.append(items[i][0])
            i += 1

        for p in possible_packets:
            if p[IP].src in good_hosts:
                if p.haslayer(TCP):
                    _tuple = (p[IP].src, p[TCP].dport, 'TCP')
                    if _tuple not in good_ports:
                        good_ports.append(_tuple)
                        om.out.debug('[extrusionServer] Adding ' + str(_tuple))

                if p.haslayer(UDP):
                    _tuple = (p[IP].src, p[UDP].dport, 'UDP')
                    if _tuple not in good_ports:
                        good_ports.append(_tuple)
                        om.out.debug('[extrusionServer] Adding ' + str(_tuple))

        return good_ports
Example #40
0
    def _analyzePackets( self, packetList ):
        '''
        Analyze the packets and return a list of ports that can be used by the remote host
        to connect back to the extrusionServer.
        '''
        
        if self._host is None:
            # This is hard to do...
            possiblePackets = []
            possibleHosts = {}
            goodPorts = []
            goodHosts = []
            
            for p in packetList:
                # Analyze TCP
                if p[TCP] is not None and p[TCP].dport in self._tcpPortList and p[IP].dst in get_if_addr( self._iface )\
                and p[TCP].flags == 0x2: # is SYN
                    possiblePackets.append( p )
                    if p[IP].src in possibleHosts:
                        possibleHosts[ p[IP].src ] += 1
                    else:
                        possibleHosts[ p[IP].src ] = 1
                
                # Analyze UDP
                if p[UDP] is not None and p[UDP].dport in self._udpPortList and p[IP].dst in get_if_addr( self._iface ):
                    possiblePackets.append( p )
                    if p[IP].src in possibleHosts:
                        possibleHosts[ p[IP].src ] += 1
                    else:
                        possibleHosts[ p[IP].src ] = 1
            
            for p in possiblePackets:
                om.out.debug('[extrusionServer] Possible packet: ' + p.summary() )
                
            # Now get the one that has more probability of being the one... and report the list of ports
            def sortfunc(x,y):
                return cmp(x[1],y[1])
            items = possibleHosts.items()
            items.sort(sortfunc)
            
            # Now I report the ports for the hosts with more connections
            i = 0
            while i < len(items) and items[0][1] == items[i][1]:
                goodHosts.append( items[i][0] )
                i += 1
            
            for p in possiblePackets:
                if p[IP].src in goodHosts:
                    if p[TCP] is not None:
                        tuple = ( p[IP].src , p[TCP].dport, 'TCP' )
                        if tuple not in goodPorts:
                            goodPorts.append( tuple )
                            om.out.debug('[extrusionServer] Adding ' + str(tuple) )
                    
                    if p[UDP] is not None:
                        tuple = ( p[IP].src , p[UDP].dport, 'UDP' )
                        if tuple not in goodPorts:
                            goodPorts.append( tuple )
                            om.out.debug('[extrusionServer] Adding ' + str(tuple) )
                        
            return goodPorts
            
        else:
            goodPorts = []
            for p in packetList:
                if p[TCP] is not None and p[TCP].dport in self._tcpPortList and p[IP].src == self._host \
                and p[TCP].flags == 0x2:
                    
                    if ( p[IP].src , p[TCP].dport, 'TCP') not in goodPorts:
                        goodPorts.append( ( p[IP].src , p[TCP].dport, 'TCP') )
                
                if p[UDP] is not None and p[UDP].dport in self._udpPortList and p[IP].src == self._host:

                    if ( p[IP].src , p[UDP].dport, 'UDP') not in goodPorts:
                        goodPorts.append( ( p[IP].src , p[UDP].dport, 'UDP') )
                        
            return goodPorts
Example #41
0
 def getLocalIP(self):
     return scapy.get_if_addr(scapy.conf.iface)
Example #42
0
                    help='interface to use')
parser.add_argument('type',
                    choices=['discover', 'offer', 'request', 'ack'],
                    help='DHCP message type (for Ether and IP layers setup)')
parser.add_argument('hexpayload',
                    help='hexadecimal payload')
args = parser.parse_args()

if args.transactionid:
    if len(args.hexpayload) < 16:
        argparse.error("Payload too short to modify transaction id")
    args.hexpayload = args.hexpayload[:8] + "%.8x" % args.transactionid + args.hexpayload[16:]
    print("Modified payload with transaction id:\n%s" % args.hexpayload)

if args.type == 'discover' or args.type == 'request':
    pkt = scapy.Ether(src=scapy.get_if_hwaddr(args.iface), dst="ff:ff:ff:ff:ff:ff") \
            / scapy.IP(src="0.0.0.0", dst="255.255.255.255") \
            / scapy.UDP(sport=68, dport=67) \
            / binascii.a2b_hex(args.hexpayload)
elif args.type == 'offer' or args.type == 'ack':
    pkt = scapy.Ether(src=scapy.get_if_hwaddr(args.iface), dst="ff:ff:ff:ff:ff:ff") \
            / scapy.IP(src=scapy.get_if_addr(args.iface), dst="255.255.255.255") \
            / scapy.UDP(sport=67, dport=68) \
            / binascii.a2b_hex(args.hexpayload)

print("[+] Sending payload")
ans, unans = scapy.srp(pkt, iface=args.iface, timeout=2)

print("ans: %s" % ans)
print("unans: %s" % unans)
Example #43
0
    configfile = ConfigObj(args.configfile)
except Exception, e:
    sys.exit("[-] Error parsing config file: " + str(e))

config_args = configfile['MITMf']['args']
if config_args:
    print "[*] Loading arguments from config file"
    for arg in config_args.split(' '):
        sys.argv.append(arg)
    args = parser.parse_args()

####################################################################################################

# Here we check for some variables that are very commonly used, and pass them down to the plugins
try:
    args.ip_address = get_if_addr(args.interface)
    if (args.ip_address == "0.0.0.0") or (args.ip_address is None):
        sys.exit("[-] Interface %s does not have an assigned IP address" % args.interface)
except Exception, e:
    sys.exit("[-] Error retrieving interface IP address: %s" % e)

try:
    args.mac_address = get_if_hwaddr(args.interface)
except Exception, e:
    sys.exit("[-] Error retrieving interface MAC address: %s" % e)

args.configfile = configfile #so we can pass the configobj down to all the plugins

####################################################################################################

log_level = logging.__dict__[args.log_level.upper()]