Exemple #1
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)
Exemple #2
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()
 def decode(self, aBuffer):
     t = ImpactPacket.TCP(aBuffer)
     self.set_decoded_protocol(t)
     off = t.get_header_size()
     self.data_decoder = DataDecoder()
     packet = self.data_decoder.decode(aBuffer[off:])
     t.contains(packet)
     return t
    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)
Exemple #5
0
    def buildAnswer(self, in_onion):
        out_onion = IPResponder.buildAnswer(self, in_onion)
        tcp = ImpactPacket.TCP()

        out_onion[O_IP].contains(tcp)
        out_onion.append(tcp)

        tcp.set_th_dport(in_onion[O_TCP].get_th_sport())
        tcp.set_th_sport(in_onion[O_TCP].get_th_dport())

        return out_onion
Exemple #6
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
Exemple #7
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))
Exemple #8
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))
Exemple #9
0
def tcppacket(con, data):
    """Function returning a tcppacket for the given connection with data as
    payload with target con.tail."""
    datalength = len(str(data))
    data = ImpactPacket.Data(data)
    tcp = ImpactPacket.TCP()
    tcp.set_th_dport(con.tail.port)
    tcp.set_th_sport(con.head.port)
    # Set ack to the expected value.
    tcp.set_th_ack(con.tail.expectedAcknr(0))
    # Increment expected seqnr (tail) by number of sent bytes.
    tcp.set_th_seq(con.tail.expectedSeqnr(datalength))
    if s.verbosity > 1:
        s.logfile.write("SeqNr: " + str(tcp.get_th_seq()) + "\n")
    tcp.set_ACK()
    tcp.contains(data)
    con.tail.acknr(datalength)
    ethhead = con.packet(Connection.TAIL, tcp)
    packet = vdepad(cksum(ethhead))
    return packet
Exemple #10
0
 def reset(self, target):
     """Function returning a TCP-RST packet to target.
     """
     tcp = ImpactPacket.TCP()
     if target == Connection.HEAD:
         thost = self.head
         shost = self.tail
     # target == TCPConnection.TAIL
     else:
         thost = self.tail
         shost = self.head
     tcp.set_th_dport(thost.port)
     tcp.set_th_sport(shost.port)
     tcp.set_th_seq(thost.expectedSeqnr())
     tcp.set_th_ack(thost.expectedAcknr())
     tcp.set_RST()
     tcp.set_ACK()
     if s.verbosity:
         s.logfile.write("RST packet sent!\n")
         s.logfile.write("SeqNr: " + str(tcp.get_th_seq()) + "\n")
         s.logfile.write("AckNr: " + str(tcp.get_th_ack()) + "\n")
     return self.packet(target, tcp)
Exemple #11
0
    def sendfin(self, target, answer, datalen=0):
        """Method sending a FIN/ACK to target. If answer is set, this should
        be the answer to a received FIN/ACK. Else this is the initiation of
        the connection closing mechanism."""
        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_seq(thost.expectedSeqnr(1))
        if answer:
            tcp.set_th_ack(thost.expectedAcknr(datalen + 1))
            # Increment seqnr.
            thost.seqnr(1)
        else:
            tcp.set_th_ack(thost.expectedAcknr(0))
        tcp.set_th_win(shost.winsize)

        tcp.set_FIN()
        tcp.set_ACK()
        if s.verbosity:
            s.logfile.write("FIN/ACK packet sent!\n")
            s.logfile.write("SeqNr: " + str(tcp.get_th_seq()) + "\n")
            s.logfile.write("AckNr: " + str(tcp.get_th_ack()) + "\n")
        # Acknr changed, even if there was no data.
        packet = self.packet(target, tcp)
        packet = encode(packet)
        thost.acknr(1)
        send(target, self, packet)
Exemple #12
0
    def build_rst(self, packet, path, personality, win, ip_id, tcp_seq):
        """Function creates a response RST packet according to personality of the device
        Args:
            packet : intercepted packet
            path : length of path in the virtual network
            personality : personality description of the device
            win : window size used in the RST packet
            ip_id : IP ID used in the RST packet
            tcp_seq : TCP SEQ number used in the RST packet
        Return:
            reply ip packet
        """
        tcp_pkt = packet.child()

        # tcp packet
        reply_tcp = ImpactPacket.TCP()
        reply_tcp.set_th_sport(tcp_pkt.get_th_dport())
        reply_tcp.set_th_dport(tcp_pkt.get_th_sport())
        # reply_tcp.set_th_flags(20) # RST + ACK
        reply_tcp.set_RST()
        reply_tcp.set_ACK()
        reply_tcp.set_th_ack(tcp_pkt.get_th_seq() + 1)
        reply_tcp.set_th_seq(tcp_seq())
        reply_tcp.set_th_win(win)
        reply_tcp.auto_checksum = 1
        reply_tcp.calculate_checksum()

        # ip packet
        reply_ip = ImpactPacket.IP()
        reply_ip.set_ip_v(4)
        reply_ip.set_ip_p(1)
        reply_ip.set_ip_rf(True)
        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(ip_id())
        # check T
        ttl = 0x7f
        if 'T' in personality:
            try:
                ttl = personality['T'].split('-')
                # using minimum ttl
                ttl = int(ttl[0], 16)
            except BaseException:
                raise Exception('Unsupported Ti:T=%s', personality['T'])

        # check TG
        if 'TG' in personality:
            try:
                ttl = int(personality['TG'], 16)
            except BaseException:
                raise Exception('Unsupported Ti:TG=%s', personality['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_tcp)

        return reply_ip
Exemple #13
0
    def build_reply(self, packet, path, personality, cb_ip_id, cb_tcp_seq, cb_tcp_ts):
        """Function creates a reply according to the personality of the device
        Args:
            packet : intercepted packet
            path : length of path in the virtual network
            personality : personality description of the device
            cb_ipid, cb_tcp_seq, cb_tcp_ts : callback functions for IP ID, TCP SEQ and TCP TS generation
        Return
            reply ip packet
        """
        # fingerprint fields R, DF, T, TG, W, S, A, F, O, RD, Q & CC

        # tcp packet
        tcp_pkt = packet.child()
        reply_tcp = ImpactPacket.TCP()
        reply_tcp.set_th_sport(tcp_pkt.get_th_dport())
        reply_tcp.set_th_dport(tcp_pkt.get_th_sport())
        reply_tcp.set_th_flags(0)
        reply_tcp.auto_checksum = 1

        # ip packet
        reply_ip = ImpactPacket.IP()
        reply_ip.set_ip_v(4)
        reply_ip.set_ip_p(6)
        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(cb_ip_id())
        reply_ip.auto_checksum = 1

        # check DF
        if 'DF' in personality:
            if personality['DF'] == 'N':
                reply_ip.set_ip_df(False)
            elif personality['DF'] == 'Y':
                reply_ip.set_ip_df(True)
            else:
                raise Exception('Unsupported Ti:DF=%s', personality['DF'])

        # check T
        ttl = 0x7f
        if 'T' in personality:
            try:
                ttl = personality['T'].split('-')
                # using minimum ttl
                ttl = int(ttl[0], 16)
            except BaseException:
                raise Exception('Unsupported Ti:T=%s', personality['T'])

        # check TG
        if 'TG' in personality:
            try:
                ttl = int(personality['TG'], 16)
            except BaseException:
                raise Exception('Unsupported Ti:TG=%s', personality['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)

        # check W
        win = 0
        if 'W' in personality:
            try:
                win = int(personality['W'], 16)
            except BaseException:
                raise Exception('Unsupported Ti:W=%s', personality['W'])
        reply_tcp.set_th_win(win)

        # check CC
        if 'CC' in personality:
            if personality['CC'] == 'N':
                reply_tcp.reset_ECE()
                reply_tcp.reset_CWR()
            elif personality['CC'] == 'Y':
                reply_tcp.set_ECE()
                reply_tcp.reset_CWR()
            elif personality['CC'] == 'S':
                reply_tcp.set_ECE()
                reply_tcp.set_CWR()
            elif personality['CC'] == 'O':
                reply_tcp.reset_ECE()
                reply_tcp.set_CWR()

        # check S
        if 'S' in personality:
            if personality['S'] == 'Z':
                reply_tcp.set_th_seq(0)
            elif personality['S'] == 'A':
                reply_tcp.set_th_seq(tcp_pkt.get_th_ack())
            elif personality['S'] == 'A+':
                reply_tcp.set_th_seq(tcp_pkt.get_th_ack() + 1)
            elif personality['S'] == 'O':
                seq = cb_tcp_seq()
                reply_tcp.set_th_seq(seq)
            else:
                raise Exception('Unsupported Ti:S=%s', personality['S'])

        # check A
        if 'A' in personality:
            if personality['A'] == 'Z':
                reply_tcp.set_th_ack(0)
            elif personality['A'] == 'S':
                reply_tcp.set_th_ack(tcp_pkt.get_th_seq())
            elif personality['A'] == 'S+':
                reply_tcp.set_th_ack(tcp_pkt.get_th_seq() + 1)
            elif personality['A'] == 'O':
                temp = random.randint(1, 10)
                reply_tcp.set_th_ack(temp)
            else:
                try:
                    temp = int(personality['A'], 16)
                    reply_tcp.set_th_ack(temp)
                except BaseException:
                    raise Exception('Unsupported Ti:A=%s', personality['A'])

        # check O
        if 'O' in personality:
            options = personality['O']
            i = 0
            while i < len(options):
                opt = options[i]
                i += 1
                if opt == 'L':
                    reply_tcp.add_option(ImpactPacket.TCPOption(ImpactPacket.TCPOption.TCPOPT_EOL))
                if opt == 'N':
                    reply_tcp.add_option(ImpactPacket.TCPOption(ImpactPacket.TCPOption.TCPOPT_NOP))
                if opt == 'S':
                    reply_tcp.add_option(ImpactPacket.TCPOption(ImpactPacket.TCPOption.TCPOPT_SACK_PERMITTED))
                if opt == 'T':
                    opt = ImpactPacket.TCPOption(ImpactPacket.TCPOption.TCPOPT_TIMESTAMP)
                    if options[i] == '1':
                        ts = cb_tcp_ts()
                        opt.set_ts(ts)
                    if options[i + 1] == '1':
                        opt.set_ts_echo(0xffffffff)
                    reply_tcp.add_option(opt)
                    i += 2
                if opt == 'M':
                    maxseg, i = self.get_value(options, i)
                    reply_tcp.add_option(ImpactPacket.TCPOption(ImpactPacket.TCPOption.TCPOPT_MAXSEG, maxseg))
                if opt == 'W':
                    window, i = self.get_value(options, i)
                    reply_tcp.add_option(ImpactPacket.TCPOption(ImpactPacket.TCPOption.TCPOPT_WINDOW, window))

        # check F
        if 'F' in personality:
            if 'E' in personality['F']:
                reply_tcp.set_ECE()
            if 'U' in personality['F']:
                reply_tcp.set_URG()
            if 'A' in personality['F']:
                reply_tcp.set_ACK()
            if 'P' in personality['F']:
                reply_tcp.set_PSH()
            if 'R' in personality['F']:
                reply_tcp.set_RST()
            if 'S' in personality['F']:
                reply_tcp.set_SYN()
            if 'F' in personality['F']:
                reply_tcp.set_FIN()

        # check Q
        if 'Q' in personality:
            if 'R' in personality['Q']:
                reply_tcp.set_flags(0x800)
            if 'U' in personality['Q']:
                reply_tcp.set_th_urp(0xffff)

        # check RD
        if 'RD' in personality:
            try:
                crc = int(personality['RD'], 16)
                if crc != 0:
                    data = 'TCP Port is closed\x00'
                    data += self.compensate(data, crc)
                    pkt_data = ImpactPacket.Data(data)
                    reply_tcp.contains(pkt_data)
            except BaseException:
                raise Exception('Unsupported Ti:RD=%s', personality['RD'])

        reply_tcp.calculate_checksum()
        reply_ip.contains(reply_tcp)
        return reply_ip
Exemple #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:
    #    #源IP
    #    src = sys.argv[1]
    #    #目标IP
    #    dst = sys.argv[2]
    #    #发送次数
    #    cnt = 1
    #elif len(sys.argv) == 4:
    #    #源IP
    #    src = sys.argv[1]
    #    #目标IP
    #    dst = sys.argv[2]
    #    #发送次数
    #    cnt = sys.argv[3]
    #else:
    #    print
    #    "Input error!"
    #    sys.exit(1)

    src="127.0.0.1"
    dst="127.0.0.1"
    cnt=10
    # 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(8081)
    tcp.set_th_dport(8009)
    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: 172.16.11.4\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, 8007))
        cnt = cnt - 1
        print("已发送:源IP:{},".format(ip.get_ip_src()))
        print("目标IP{}\n".format(ip.set_ip_dst()))