Ejemplo n.º 1
0
    def icmp_reply(self, eth_src, eth_dst, ip_src, ip_dst, i_type, i_code,
                   ip_pkt):
        # TODO: we have access to the personality here
        """Function creates and sends back an ICMP reply
        Args:
            eth_src : ethernet source address
            eth_dst : ethernet destination address
            ip_src : ip source address
            ip_dst : ip destination address
            i_type : type of the icmp reply
            i_code : code of the icmp reply
        """
        # truncate inner packet
        l = ip_pkt.get_ip_len()
        hdr = None
        if l > 1472:  # (MTU) 1500 - (IPv4) 20 - (ICMP) 8 = 1472
            hdr = ip_pkt.get_packet()[:1472]
        else:
            hdr = ip_pkt.get_packet()

        # icmp packet
        reply_icmp = ImpactPacket.ICMP()
        reply_icmp.set_icmp_type(i_type)
        reply_icmp.set_icmp_code(i_code)
        reply_icmp.set_icmp_id(0)
        reply_icmp.set_icmp_seq(0)
        reply_icmp.set_icmp_void(0)
        reply_icmp.contains(ImpactPacket.Data(hdr))
        reply_icmp.calculate_checksum()
        reply_icmp.auto_checksum = 1

        # ip packet
        reply_ip = ImpactPacket.IP()
        reply_ip.set_ip_v(4)
        reply_ip.set_ip_p(1)
        reply_ip.set_ip_rf(False)
        reply_ip.set_ip_df(False)
        reply_ip.set_ip_mf(False)
        reply_ip.set_ip_src(ip_src)
        reply_ip.set_ip_dst(ip_dst)
        reply_ip.set_ip_id(
            random.randint(0, 50000)
        )  # TODO: provide IP IDs according to personality, altough tracepath does not care
        reply_ip.contains(reply_icmp)

        # ethernet frame
        reply_eth = ImpactPacket.Ethernet()
        reply_eth.set_ether_type(0x800)
        eth_src = [int(i, 16) for i in eth_src.split(':')]
        eth_dst = [int(i, 16) for i in eth_dst.split(':')]
        reply_eth.set_ether_shost(eth_src)
        reply_eth.set_ether_dhost(eth_dst)
        reply_eth.contains(reply_ip)

        logger.debug('Sending reply: %s', reply_eth)
        # send raw frame
        try:
            self.pcapy_object.sendpacket(reply_eth.get_packet())
        except pcapy.PcapError as ex:
            logger.exception('Exception: Cannot send reply packet: %s', ex)
Ejemplo n.º 2
0
def flood(src, dst):
    # create packet
    ip = ImpactPacket.IP()
    ip.set_ip_src(src)
    ip.set_ip_dst(dst)

    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)

    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 packet
        s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
        s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
        # Send it to the target host.
        s.sendto(ip.get_packet(), (dst, 0))
        print("sent from %s of sid: %d" % (src, seq_id))
        continue
Ejemplo n.º 3
0
    def send_message(self, source_ip, dest_ip, current_socket, msg, seq_number,
                     is_ret):

        #Create a new IP packet and set its source and destination IP addresses
        src = source_ip
        dst = dest_ip
        ip = ImpactPacket.IP()
        #print(src.__str__() + " to " + dst.__str__())
        ip.set_ip_src(src)
        ip.set_ip_dst(dst)

        #Create a new ICMP ECHO_REQUEST packet
        icmp = ImpactPacket.ICMP()
        icmp.set_icmp_type(icmp.ICMP_ECHO)

        #inlude a small payload inside the ICMP packet
        #and have the ip packet contain the ICMP packet
        icmp.contains(ImpactPacket.Data(msg))
        ip.contains(icmp)

        #give the ICMP packet some ID
        if is_ret:
            icmp.set_icmp_id(0x04)
        else:
            icmp.set_icmp_id(0x03)

        #set the ICMP packet checksum
        icmp.set_icmp_cksum(0)
        icmp.auto_checksum = 1

        icmp.set_icmp_seq(seq_number)
        self.send_packet(current_socket, ip.get_packet(), dst)
Ejemplo n.º 4
0
def sendReply(nonce):
    #build ethernet frame
    eth = ImpactPacket.Ethernet()
    eth.set_ether_type(0x88b5)
    eth.set_ether_shost(ETH_MY_MAC)
    eth.set_ether_dhost(ETH_MY_MAC)

    #build ip packet
    ip = ImpactPacket.IP()
    ip.set_ip_v(4)
    ip.set_ip_len(32)
    ip.set_ip_src("127.0.0.1")
    ip.set_ip_dst("127.0.0.1")

    #build UDP packet
    udp = ImpactPacket.UDP()
    udp.set_uh_sport(62001)
    udp.set_uh_dport(62000)
    udp.set_uh_ulen(12)
    payload = nonce
    udp.contains(ImpactPacket.Data(payload))

    ip.contains(udp)
    eth.contains(ip)

    device = findalldevs()[0]

    s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(0x88b5))
    s.bind(('lo', 0))

    s.send(eth.get_packet())
    print "Sent: " + nonce
    signal.alarm(0)  #disable the alarm
Ejemplo n.º 5
0
 def send_ns_packet(self,
                    source_link,
                    send_frequency,
                    target_address,
                    vlan_id=0):
     ip = IP6.IP6()
     ip.set_source_address(self.get_source_address())
     ip.set_destination_address(self.get_target_address())
     ip.set_traffic_class(0)
     ip.set_flow_label(0)
     ip.set_hop_limit(255)
     s = socket(AF_PACKET, SOCK_RAW, IPPROTO_ICMPV6)
     s.bind((self.network_card, N))
     payload = self.create_ns_message(source_link, target_address)
     print send_frequency
     for i in range(0, send_frequency):
         icmp = ICMP6.ICMP6()
         icmp.set_byte(0, 135)  # Put Type?
         icmp.set_byte(1, 00)  # Put Code?
         payloadObject = ImpactPacket.Data()
         payloadObject.set_data(payload)
         icmp.contains(payloadObject)
         ip.contains(icmp)
         ip.set_next_header(ip.child().get_ip_protocol_number())
         ip.set_payload_length(ip.child().get_size())
         eth = ImpactPacket.Ethernet(
             '\x33\x33\x00\x00\x00\x01\xff\xff\xff\xff\xff\xff\x81\x00')
         eth.pop_tag()
         if vlan_id != 0:
             vlan = ImpactPacket.EthernetTag()
             vlan.set_vid(vlan_id)
             eth.push_tag(vlan)
         icmp.calculate_checksum()
         eth.contains(ip)
         s.send(eth.get_packet())
Ejemplo n.º 6
0
def ip_tcp_pack(src_ip="127.0.0.1",
                dst_ip="127.0.0.1",
                src_port=2333,
                dst_port=80,
                ip_id=0,
                seq_num=0,
                ack_num=0,
                syn=0,
                ack=0,
                windows=64):
    ip = ImpactPacket.IP()
    ip.set_ip_src(src_ip)
    ip.set_ip_dst(dst_ip)
    if ip_id != 0:
        ip.set_ip_id(ip_id)
    ip.set_ip_p(6)
    # ip.set_ip_len(40)

    tcp = ImpactPacket.TCP()
    tcp.set_th_sport(src_port)
    tcp.set_th_dport(dst_port)
    if seq_num != 0:
        tcp.set_th_seq(seq_num)
    if ack_num != 0:
        tcp.set_th_ack(ack_num)
    if syn:
        tcp.set_SYN()
    if ack:
        tcp.set_ACK()
    tcp.set_th_win(windows)
    ip.contains(tcp)
    tcp.calculate_checksum()
    return ip.get_packet()
Ejemplo n.º 7
0
    def send_one_ping(cls, current_socket, src, dst, icmp_packet_id, payload):
        # print("SEND : " + src[-1] + " -> " + dst[-1] + " Payload : " + payload)

        #Create a new IP packet and set its source and destination IP addresses
        ip = ImpactPacket.IP()
        ip.set_ip_src(src)
        ip.set_ip_dst(dst)

        #Create a new ICMP ECHO_REQUEST packet
        icmp = ImpactPacket.ICMP()
        icmp.set_icmp_type(icmp.ICMP_ECHO)

        #inlude a small payload inside the ICMP packet
        #and have the ip packet contain the ICMP packet
        icmp.contains(ImpactPacket.Data(payload))
        ip.contains(icmp)

        #give the ICMP packet some ID
        icmp.set_icmp_id(icmp_packet_id)

        #set the ICMP packet checksum
        icmp.set_icmp_cksum(0)
        icmp.auto_checksum = 1

        send_time = default_timer()

        # send the provided ICMP packet over a 3rd socket
        try:
            current_socket.sendto(
                ip.get_packet(),
                (dst, 1))  # Port number is irrelevant for ICMP
        except socket.error as e:
            print("# socket creation failed.")
            current_socket.close()
            return
Ejemplo n.º 8
0
    def filtered(self, packet, path, personality, **kwargs):
        """Function defines filtered port behavior - filtered is defined according to nmap"""
        callback_ipid = kwargs.get('cb_ipid', None)
        callback_icmpid = kwargs.get('cb_icmpid', None)

        # respond with ICMP error type 3 code 13 OR ignore
        # icmp packet
        reply_icmp = ImpactPacket.ICMP()
        reply_icmp.set_icmp_type(ImpactPacket.ICMP.ICMP_UNREACH)
        reply_icmp.set_icmp_code(ImpactPacket.ICMP.ICMP_UNREACH_FILTERPROHIB)
        reply_icmp.set_icmp_id(callback_icmpid())  # unused field
        reply_icmp.set_icmp_seq(0)  # unused field
        reply_icmp.calculate_checksum()
        reply_icmp.auto_checksum = 1

        # ip packet
        reply_ip = ImpactPacket.IP()
        reply_ip.set_ip_v(4)
        reply_ip.set_ip_p(1)
        reply_ip.set_ip_rf(False)
        reply_ip.set_ip_df(False)
        reply_ip.set_ip_mf(False)
        reply_ip.set_ip_src(packet.get_ip_dst())
        reply_ip.set_ip_dst(packet.get_ip_src())
        reply_ip.set_ip_id(callback_ipid())
        reply_ip.auto_checksum = 1
        reply_ip.contains(reply_icmp)

        return reply_ip
Ejemplo n.º 9
0
    def filtered(self, packet, path, personality, **kwargs):
        """Function defines filtered port behavior - filtered is defined according to nmap"""
        callback_ipid = kwargs.get('cb_ipid', None)
        # respond with ICMP error type 3 code 13 OR ignore
        # icmp packet
        reply_icmp = ImpactPacket.ICMP()
        reply_icmp.set_icmp_type(ImpactPacket.ICMP.ICMP_UNREACH)
        reply_icmp.set_icmp_code(ImpactPacket.ICMP.ICMP_UNREACH_FILTERPROHIB)
        reply_icmp.set_icmp_void(0)
        reply_icmp.set_icmp_id(0)
        reply_icmp.set_icmp_seq(0)
        hdr = None
        l = packet.get_ip_len()
        if l > 1472:  # 1500 - 20 - 8 (MTU - IP - ICMP)
            hdr = packet.get_packet()[:1472]
        else:
            hdr = packet.get_packet()
        reply_icmp.contains(ImpactPacket.Data(hdr))
        reply_icmp.calculate_checksum()
        reply_icmp.auto_checksum = 1

        # ip packet
        reply_ip = ImpactPacket.IP()
        reply_ip.set_ip_v(4)
        reply_ip.set_ip_p(1)
        reply_ip.set_ip_rf(False)
        reply_ip.set_ip_df(False)
        reply_ip.set_ip_mf(False)
        reply_ip.set_ip_src(packet.get_ip_dst())
        reply_ip.set_ip_dst(packet.get_ip_src())
        reply_ip.set_ip_id(callback_ipid())
        # check T
        ttl = 0x7f
        if 'T' in personality.fp_ie:
            try:
                ttl = personality.fp_ie['T'].split('-')
                # using minimum ttl
                ttl = int(ttl[0], 16)
            except BaseException:
                raise Exception('Unsupported IE:T=%s', personality.fp_ie['T'])

        # check TG
        if 'TG' in personality.fp_ie:
            try:
                ttl = int(personality.fp_ie['TG'], 16)
            except BaseException:
                raise Exception('Unsupported IE:TG=%s',
                                personality.fp_ie['TG'])

        delta_ttl = ttl - path
        if delta_ttl < 1:
            logger.debug(
                'Reply packet dropped: TTL reached 0 within virtual network.')
            return None
        reply_ip.set_ip_ttl(delta_ttl)
        reply_ip.auto_checksum = 1
        reply_ip.contains(reply_icmp)

        return reply_ip
Ejemplo n.º 10
0
 def sendpacket(self, data):
     ipe = ImpactPacket.Ethernet()
     ipe.set_ether_dhost(self.MACADDRESS)
     ipd = ImpactPacket.Data(data)
     ipd.ethertype = 0x86dd  # Ethertype for IPv6
     ipe.contains(ipd)
     p = ipe.get_packet()
     self.s.send(p)
Ejemplo n.º 11
0
    def fakeConnection(self, argv, argc):
        
        dhost = argv[1]           # The remote host
        dport = int(argv[2])      # The same port as used by the server
        sport = dport             # The source port
        shost = argv[3]           # The source host

        if argc >= 5:
            SYN = int(argv[4])
        if argc == 6:
            ACK = int(argv[5])
            
        # Create a new IP packet and set its source and destination addresses.
        ip = ImpactPacket.IP()
        ip.set_ip_src(shost)
        ip.set_ip_dst(dhost)

        # Create a new TCP
        tcp = ImpactPacket.TCP()
        
        # Set the parameters for the connection
        tcp.set_th_sport(sport)
        tcp.set_th_dport(dport)
        tcp.set_th_seq(SYN)
        tcp.set_SYN()
        if argc == 6:
            tcp.set_th_ack(ACK)
            tcp.set_ACK()
        
        
        # Have the IP packet contain the TCP packet
        ip.contains(tcp)

        # Open a raw socket. Special permissions are usually required.
        protocol_num = socket.getprotobyname('tcp')
        self.s = socket.socket(socket.AF_INET, socket.SOCK_RAW, protocol_num)
        self.s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)

        # Calculate its checksum.
	tcp.calculate_checksum()
	tcp.auto_checksum = 1

        # Send it to the target host.
	self.s.sendto(ip.get_packet(), (dhost, dport))

        # Instantiate an IP packets decoder.
        # As all the packets include their IP header, that decoder only is enough.
        decoder = ImpactDecoder.IPDecoder()

        while 1:
            packet = self.s.recvfrom(4096)[0]
            # Packet received. Decode and display it.
            packet = decoder.decode(packet)
            print 'source:', packet.get_ip_src()
            #print packet.get_ip_src(), packet.child().get_th_sport()
            if isinstance(packet.child(),ImpactPacket.TCP)  and \
                   packet.child().get_th_sport() > 50000:
                self._sniffed(packet)
Ejemplo n.º 12
0
    def emitter(self):
        """ The emitter method is responsible for establishing the connections or sending the packets associated with
        the plugin. Emitter MUST use the encoder() method to assemble payloads
        :return: True if successful
        """

        try:

            src = self.getlocaladdr()

            try:
                dst = socket.gethostbyname(self.target)
            except Exception as e:
                dst = self.target
                self.logger.error('Failed to resolve target hostname for %s: %s' % (self.__class__.__name__, e))
                raise e

            # Fetch the icmptype property as a list
            icmptypes = self.listproperty('icmptype')
            print icmptypes
            if not icmptypes:
                icmptypes = [8]

            # Send the payload to the encoder which returns a generator, then iterate over the chunked and encoded
            # payload
            for payload in self.encoder(self.payload):
                # Iterate over all of the specified types for this payload and execute the delivery
                for icmptype in icmptypes:
                    ip = ImpactPacket.IP()
                    ip.set_ip_src(src)
                    ip.set_ip_dst(dst)

                    icmp = ImpactPacket.ICMP()
                    icmp.set_icmp_type(icmptype)

                    seq_id = 0

                    s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
                    s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)

                    icmp.contains(ImpactPacket.Data(payload))
                    ip.contains(icmp)

                    icmp.set_icmp_id(seq_id)
                    icmp.set_icmp_cksum(0)
                    icmp.auto_checksum = 1

                    s.sendto(ip.get_packet(), (self.target, 0))
                    seq_id += 1


        except socket.error:
            raise
        except Exception:
            raise

        return True
Ejemplo n.º 13
0
def udppacket(con, data):
    """Function returning a udppacket for the given connection with data as
    payload with target con.tail."""
    data = ImpactPacket.Data(data)
    udp = ImpactPacket.UDP()
    udp.set_uh_dport(con.tail.port)
    udp.set_uh_sport(con.head.port)
    udp.contains(data)
    ethhead = con.packet(Connection.TAIL, udp)
    packet = vdepad(cksum(ethhead))
    return packet
Ejemplo n.º 14
0
def main():
    if len(sys.argv) < 3:
        print("Use: %s <src ip> <dst ip>" % sys.argv[0])

        print("Use: %s <src ip> <dst ip> <cnt>" % sys.argv[0])
        sys.exit(1)
    elif len(sys.argv) == 3:
        src = sys.argv[1]
        dst = sys.argv[2]
        cnt = 1
    elif len(sys.argv) == 4:
        src = sys.argv[1]
        dst = sys.argv[2]
        cnt = sys.argv[3]
    else:
        print("Input error!")
        sys.exit(1)
    # print src, dst
    ip = ImpactPacket.IP()
    ip.set_ip_src(src)
    ip.set_ip_dst(dst)

    # Create a new ICMP packet of type ECHO.
    icmp = ImpactPacket.ICMP()
    tcp = ImpactPacket.TCP()
    tcp.set_th_sport(55968)
    tcp.set_th_dport(80)
    tcp.set_th_seq(1)
    tcp.set_th_ack(1)
    tcp.set_th_flags(0x18)
    tcp.set_th_win(64)

    tcp.contains(
        ImpactPacket.Data(
            "GET /att/DIYLife/41264/528 HTTP/1.1\r\nHost: 192.168.111.1\r\nAccept-Encoding: identity\r\n\r\n"
        ))

    ip.contains(tcp)

    # Open a raw socket. Special permissions are usually required.
    s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_TCP)
    s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
    seq_id = 0
    while cnt >= 1:
        # Calculate its checksum.
        seq_id = seq_id + 1
        tcp.set_th_seq(seq_id)
        tcp.calculate_checksum()

        # Send it to the target host.
        s.sendto(ip.get_packet(), (dst, 80))
        cnt = cnt - 1
Ejemplo n.º 15
0
 def create_packet(self):
     # IP paket
     self.ip = ImpactPacket.IP()
     # ICMP paket
     self.icmp = ImpactPacket.ICMP()
     if self.operating_as == CLIENT:
         # ako smo CLIENT koristimo ECHO, inace ECHOREPLY
         self.icmp.set_icmp_type(self.icmp.ICMP_ECHO)
     else:
         self.icmp.set_icmp_type(self.icmp.ICMP_ECHOREPLY)
         self.ip.set_ip_ttl(64)  # emulacija linux OS-a
     self.ip.set_ip_src(self.src_ip_addr)
     self.ip.set_ip_dst(self.dst_ip_addr)
Ejemplo n.º 16
0
def alive(src, dst):
    # 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
    # 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))

    for i in range(3):
        # 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():
                return True

            time.sleep(1)
    return False
Ejemplo n.º 17
0
    def buildAnswer(self, in_onion):
        eth = ImpactPacket.Ethernet()
        ip = ImpactPacket.IP()

        eth.contains(ip)

        eth.set_ether_shost(in_onion[O_ETH].get_ether_dhost())
        eth.set_ether_dhost(in_onion[O_ETH].get_ether_shost())

        ip.set_ip_src(in_onion[O_IP].get_ip_dst())
        ip.set_ip_dst(in_onion[O_IP].get_ip_src())
        ip.set_ip_id(self.machine.getIPID())

        return [eth, ip]
Ejemplo n.º 18
0
 def encodePacket(self, src, dst, type, code, ttl, payload):
     payload = ImpactPacket.Data(payload)
     icmpDatagram = ImpactPacket.ICMP()
     icmpDatagram.set_icmp_type(type)
     if code:
         icmpDatagram.set_icmp_code(code)
     icmpDatagram.set_icmp_lifetime(ttl)
     icmpDatagram.set_icmp_ttime(ttl)
     icmpDatagram.contains(payload)
     ipDatagram = ImpactPacket.IP()
     ipDatagram.set_ip_src(src)
     ipDatagram.set_ip_dst(dst)
     ipDatagram.contains(icmpDatagram)
     self.raw = ipDatagram.get_packet()
Ejemplo n.º 19
0
    def send_one_ping(self,src,dst,current_socket,icmp_payload):
        ip = ImpactPacket.IP()
        ip.set_ip_src(src)
        ip.set_ip_dst(dst)
        icmp = ImpactPacket.ICMP()
        icmp.set_icmp_type(icmp.ICMP_ECHO)
        icmp.contains(ImpactPacket.Data(icmp_payload))
        ip.contains(icmp)
        icmp.set_icmp_id(0x03)
        icmp.set_icmp_cksum(0)
        icmp.auto_checksum = 1

        send_time = default_timer()
        current_socket.sendto(ip.get_packet(), (dst, 1))
Ejemplo n.º 20
0
    def opened(self, packet, path, personality, **kwargs):
        """Function defines open port behavior"""
        callback_ipid = kwargs.get('cb_ipid', None)
        # send rUDP
        udp_packet = packet.child()

        # udp datagram
        reply_udp = ImpactPacket.UDP()
        reply_udp.set_uh_sport(udp_packet.get_uh_dport())
        reply_udp.set_uh_dport(udp_packet.get_uh_sport())
        reply_udp.auto_checksum = 1
        reply_udp.calculate_checksum()

        # ip packet
        reply_ip = ImpactPacket.IP()
        reply_ip.set_ip_v(4)
        reply_ip.set_ip_p(17)
        reply_ip.set_ip_rf(False)
        reply_ip.set_ip_df(False)
        reply_ip.set_ip_mf(False)
        reply_ip.set_ip_src(packet.get_ip_dst())
        reply_ip.set_ip_dst(packet.get_ip_src())
        reply_ip.set_ip_id(callback_ipid())
        # check T
        ttl = 0x7f
        if 'T' in personality.fp_u1:
            try:
                ttl = personality.fp_u1['T'].split('-')
                # using minimum ttl
                ttl = int(ttl[0], 16)
            except BaseException:
                raise Exception('Unsupported U1:T=%s', personality.fp_u1['T'])

        # check TG
        if 'TG' in personality.fp_u1:
            try:
                ttl = int(personality.fp_u1['TG'], 16)
            except BaseException:
                raise Exception('Unsupported U1:TG=%s',
                                personality.fp_u1['TG'])
        delta_ttl = ttl - path
        if delta_ttl < 1:
            logger.debug(
                'Reply packet dropped: TTL reached 0 within virtual network.')
            return None
        reply_ip.set_ip_ttl(delta_ttl)
        reply_ip.auto_checksum = 1
        reply_ip.contains(reply_udp)

        return reply_ip
Ejemplo n.º 21
0
	def read(self, timeout):
		try:
			data = self.mySniffer.read(timeout)
		except:
			raise ReadTimeout
		# so we have data, now process it
		ip_pkt = ImpactPacket.IP(data)
		offset = ip_pkt.get_header_size()
		if not ip_pkt.get_ip_p() == ImpactPacket.UDP.protocol:
			raise NotUDP

		udp_pkt = ImpactPacket.UDP(data[offset:])
		offset += udp_pkt.get_header_size()
		dnsmsg = dns.message.from_wire(data[offset:])
		return dnsmsg
Ejemplo n.º 22
0
    def sendack(self, target, bytecount, keepalive=0):
        """Function sending an acknowledgement to target. bytes is the number
        of bytes which get acknowledged."""
        tcp = ImpactPacket.TCP()
        if target == Connection.HEAD:
            thost = self.head
            shost = self.tail
            out = TCPConnection.stdout
        else:
            thost = self.tail
            shost = self.head
            out = TCPConnection.alt_stdout

        tcp.set_th_dport(thost.port)
        tcp.set_th_sport(shost.port)
        tcp.set_th_ack(thost.expectedAcknr(bytecount))
        # ACK does not increment seq-nr.
        tcp.set_th_seq(thost.expectedSeqnr(0))
        tcp.set_th_win(thost.winsize)

        tcp.set_ACK()

        packet = self.packet(target, tcp)
        if s.verbosity:
            s.logfile.write("ACK sent to " + target + ".\n")
            s.logfile.write("Seqnr.: " + str(tcp.get_th_seq()) + "\n")
            s.logfile.write("ACKNr.: " + str(tcp.get_th_ack()) + "\n")
            if s.verbosity > 9:
                s.logfile.write(str(packet) + "\n")
        packet = vdepad(cksum(packet))
        send(target, self, packet, 0)
Ejemplo n.º 23
0
 def send_raw(self, data):
     # posljednja obrada podataka prije slanja
     if data not in [TUNNEL_STS, TUNNEL_RET, TUNNEL_NOOP]:
         # ako podaci nisu SwitchToServer niti Retrieve/NOOP naredbe
         # dodajemo CLIENT/SERVER prefixe ovisno o trenutnom modu rada
         if self.operating_as == CLIENT:
             data = CLIENT_PREFIX + data
         else:
             data = SERVER_PREFIX + data
     cipher = mData.DataMangler(data)  # kreiramo novi kriptoobjekt
     # podaci se u kriptoobjektu kriptiraju sa odabranim passwordom i algoritmom,
     # uzima se samo prvih 1408 znakova (Ethernet ogranicenje 1500 bytes frame size, broj mora biti djeljiv sa 16 zbog AESa) i stavlja u ICMP data polje
     self.icmp.contains(
         ImpactPacket.Data(
             cipher.obfuscate(self.password, self.algo)[:1408]))
     # Uvecavamo ICMP paketu ID samo ako smo klijent
     if self.operating_as == CLIENT:
         self.seq_id += 1
         if self.seq_id > 65535:
             # ID je samo 2 byta, treba paziti na preljev
             self.seq_id = 0
     # vrijednost iz seq_id postavljamo i u ID polje i u SEQ polje
     self.icmp.set_icmp_id(self.seq_id)
     self.icmp.set_icmp_seq(self.seq_id)
     # automatsko racunanje checkshuma
     self.icmp.set_icmp_cksum(0)
     self.icmp.auto_checksum = 1
     # ICMP paket pakira se u IP paket
     self.ip.contains(self.icmp)
     # saljemo finalni paket
     self.tunnel_sock.sendto(self.ip.get_packet(), (self.dst_ip_addr, 0))
Ejemplo n.º 24
0
 def sendSYN(self, target, ethhead):
     """Method sending a given SYN packet to target. The SYN packet will be
     changed to not support TCPOPT_TIMESTAMP.
     """
     eth = ethhead
     iphead = eth.child()
     tcphead = iphead.child()
     if target == TCPConnection.TAIL:
         out = TCPConnection.alt_stdout
         host = self.head
     # target == Connection.HEAD
     else:
         out = TCPConnection.stdout
         host = self.tail
     nop = ImpactPacket.TCPOption(ImpactPacket.TCPOption.TCPOPT_NOP)
     # If there is a Maximum Segment Size (MSS) give, we need to set it as
     # the upper threshold for the packet size.
     for option in tcphead.get_options():
         if option.get_kind() == ImpactPacket.TCPOption.TCPOPT_MAXSEG:
             host.mss = option.get_mss()
     # We need to check the availiable options and only delete all
     # non MSS options. (TODO: Very bad practice. Do this properly!!)
     i = 0
     for option in tcphead.get_options():
         if option.get_kind() != ImpactPacket.TCPOption.TCPOPT_MAXSEG:
             # Bad practice, but seems like the only possible way.
             tcphead._TCP__option_list[i] = nop
         i += 1
     # Recalculate the ipheader length
     iphead.set_ip_len(0)
     packet = encode(eth)
     if s.verbosity > 9:
         s.logfile.write("Syn packet sent: " + str(eth) + "\n")
     send(target, self, packet)
    def decode(self, aBuffer):
        i = ImpactPacket.IP(aBuffer)
        self.set_decoded_protocol(i)
        off = i.get_header_size()
        end = i.get_ip_len()
        # If ip_len == 0 we might be facing TCP segmentation offload, let's calculate the right len
        if end == 0:
            LOG.warning(
                'IP len reported as 0, most probably because of TCP segmentation offload. Attempting to fix its size'
            )
            i.set_ip_len(len(aBuffer))
            end = i.get_ip_len()

        if i.get_ip_p() == ImpactPacket.UDP.protocol:
            self.udp_decoder = UDPDecoder()
            packet = self.udp_decoder.decode(aBuffer[off:end])
        elif i.get_ip_p() == ImpactPacket.TCP.protocol:
            self.tcp_decoder = TCPDecoder()
            packet = self.tcp_decoder.decode(aBuffer[off:end])
        elif i.get_ip_p() == ImpactPacket.ICMP.protocol:
            self.icmp_decoder = ICMPDecoder()
            packet = self.icmp_decoder.decode(aBuffer[off:end])
        elif i.get_ip_p() == ImpactPacket.IGMP.protocol:
            self.igmp_decoder = IGMPDecoder()
            packet = self.igmp_decoder.decode(aBuffer[off:end])
        else:
            self.data_decoder = DataDecoder()
            packet = self.data_decoder.decode(aBuffer[off:end])
        i.contains(packet)
        return i
 def decode(self, aBuffer):
     ig = ImpactPacket.IGMP(aBuffer)
     off = ig.get_header_size()
     self.data_decoder = DataDecoder()
     packet = self.data_decoder.decode(aBuffer[off:])
     ig.contains(packet)
     return ig
    def decode(self, aBuffer):
        e = ImpactPacket.Ethernet(aBuffer)
        self.set_decoded_protocol(e)
        off = e.get_header_size()
        if e.get_ether_type() == ImpactPacket.IP.ethertype:
            self.ip_decoder = IPDecoder()
            packet = self.ip_decoder.decode(aBuffer[off:])
        elif e.get_ether_type() == IP6.IP6.ethertype:
            self.ip6_decoder = IP6Decoder()
            packet = self.ip6_decoder.decode(aBuffer[off:])
        elif e.get_ether_type() == ImpactPacket.ARP.ethertype:
            self.arp_decoder = ARPDecoder()
            packet = self.arp_decoder.decode(aBuffer[off:])
        elif e.get_ether_type() == eap.DOT1X_AUTHENTICATION:
            self.eapol_decoder = EAPOLDecoder()
            packet = self.eapol_decoder.decode(aBuffer[off:])
        # LLC ?
        elif e.get_ether_type() < 1500:
            self.llc_decoder = LLCDecoder()
            packet = self.llc_decoder.decode(aBuffer[off:])
        else:
            self.data_decoder = DataDecoder()
            packet = self.data_decoder.decode(aBuffer[off:])

        e.contains(packet)
        return e
Ejemplo n.º 28
0
    def fakeConnection(self, table):

        for i in (0, 1):
            port = 50007
            dhost = table[i][0][0]  # The remote host
            shost = table[(i + 1) % 2][0][0]  # The source host
            dport = port  # The same port as used by the server
            sport = dport  # The source port

            SYN = table[(i + 1) % 2][1]
            ACK = table[i][1] + 1

            # Create a new IP packet and set its source and destination addresses.
            ip = ImpactPacket.IP()
            print 'IPs:', shost, dhost
            ip.set_ip_src(shost)
            ip.set_ip_dst(dhost)

            # Create a new TCP
            tcp = ImpactPacket.TCP()

            # Set the parameters for the connection
            print 'Ports:', sport, dport
            tcp.set_th_sport(sport)
            tcp.set_th_dport(dport)
            print 'SYN-ACK:', SYN, ACK
            tcp.set_th_seq(SYN)
            tcp.set_SYN()
            tcp.set_th_ack(ACK)
            tcp.set_ACK()

            # Have the IP packet contain the TCP packet
            ip.contains(tcp)

            # Open a raw socket. Special permissions are usually required.
            protocol_num = socket.getprotobyname('tcp')
            self.s = socket.socket(socket.AF_INET, socket.SOCK_RAW,
                                   protocol_num)
            self.s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
            #self._bind()

            # Calculate its checksum.
            tcp.calculate_checksum()
            tcp.auto_checksum = 1

            # Send it to the target host.
            self.s.sendto(ip.get_packet(), (dhost, dport))
Ejemplo n.º 29
0
def main():
    signal.signal(signal.SIGALRM, lambda *args: handle_alarm())
    #build ethernet frame
    eth = ImpactPacket.Ethernet()
    eth.set_ether_type(0x88b5)
    eth.set_ether_shost(ETH_MY_MAC)
    eth.set_ether_dhost(ETH_MY_MAC)

    #build ip packet
    ip = ImpactPacket.IP()
    ip.set_ip_v(4)
    ip.set_ip_len(32)
    ip.set_ip_src("127.0.0.1")
    ip.set_ip_dst("127.0.0.1")

    #build UDP packet
    udp = ImpactPacket.UDP()
    udp.set_uh_sport(62000)
    udp.set_uh_dport(62001)
    udp.set_uh_ulen(12)

    inp1 = ''

    print "Client.... Port: " + str(udp.get_uh_sport())
    print "--------------------------------------------"

    while (len(inp1) != 4):
        inp1 = raw_input('Enter 4-bit ASCII nonce to send: ')
        if (len(inp1) != 4):
            print "Enter 4-bit ASCII"

    payload = inp1
    udp.contains(ImpactPacket.Data(payload))

    ip.contains(udp)
    eth.contains(ip)

    device = 'lo'

    s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(0x88b5))
    s.bind((device, 0))

    s.send(eth.get_packet())

    print "Sent: " + inp1

    receiveReply()
Ejemplo n.º 30
0
def handle_icmp(pcap, wire_packet, ip):
    icmp = ip.child()
    if icmp.get_icmp_type() == ImpactPacket.ICMP.ICMP_ECHO:
        reply = build_ethernet_reply(wire_packet, ImpactPacket.IP.ethertype)
        ip_reply = build_ip_reply(ip, ImpactPacket.ICMP.protocol)

        icmp_reply = ImpactPacket.ICMP()
        icmp_reply.set_icmp_type(ImpactPacket.ICMP.ICMP_ECHOREPLY)
        icmp_reply.set_icmp_seq(icmp.get_icmp_seq())
        icmp_reply.set_icmp_id(icmp.get_icmp_id())
        icmp_reply.contains(ImpactPacket.Data(icmp.get_data_as_string()))

        ip_reply.contains(icmp_reply)
        reply.contains(ip_reply)

        pcap_sendpacket(pcap, cast(reply.get_packet(), POINTER(u_char)),
                        reply.get_size())