def injection_attack(self): # Packet creation based on: # https://raidersec.blogspot.pt/2013/01/wireless-deauth-attack-using-aireplay.html if len(self.plugins) == 0: self.add_plugin(Deauthenticator( )) # Deauthentication is default behaviour of injector injection_socket = conf.L2socket(iface=self.injection_interface) for plugin in self.plugins: plugin.interpret_targets(self._ap_targets, self._client_targets) plugin.set_injection_socket(injection_socket) # Launches all added plugins' post injection methods and waits for finish self.injection_thread_pool_start("pre_injection") # Launches all added plugins' injection attacks and waits for finish self.injection_thread_pool_start("inject_packets") print "[+] Injection attacks finished executing." print "[+] Starting post injection methods" # Launches all added plugins' post injection methods and waits for finish self.injection_thread_pool_start("post_injection") del self.plugins[:] # Plugin cleanup for next use print "[+] Post injection methods finished" # Restore state after all threads finishing injection_socket.close() self.injection_running = False self._restore_injection_state()
def receive(interface): while True: sock = conf.L2socket( iface=interface ) # scapy socket which connects to a network e.g "en0", "en1" pkt = bytes(sock.recv()) # the packets get read and converted to bytes if pkt[12: 14] != b'\x70\x00': # only the packets with protocol "0x7000" get filtered continue dest_mac, src_mac, eth_proto, data = ethernet_frame( pkt ) # calls the function to convert the information of the packets print('\nEthernet Frame:') print("Destination MAC: {}".format( dest_mac)) # prints the converted destination MAC-address print("Source MAC: {}".format( src_mac)) # prints the converted source MAC-address print( "Protocol: {}".format(eth_proto)) # prints the converted protocol print("Packet: ", data) # prints the payout break return data
def start(self): sock = conf.L2socket(iface=self.iface) # create all sessions for _ in range(self.count): ses = DHSession(sock=sock, opt82=self.opt82) self.sessions[ses.mac[:6]] = ses print(f"Created {len(self.sessions)} sessions") # handle retransmits try: while True: print(".", end='') for ses in self.sessions.values(): # if still waiting for offer, retransmit if ses.state in ["discover", "init"]: ses.discover() sleep(self.ipd) if ses.state in ["request"]: ses.request() sleep(self.ipd) if ses.state in ["ack"]: # ses.ping() sleep(self.ipd) # wait 5 seconds between retransmits sleep(5) except KeyboardInterrupt: print("DHSlave Interrupting due to ^C") if self.release_on_exit: print("Releasing all sessions") for ses in self.sessions.values(): if ses.state in ["ack", "release"]: ses.release()
def setup(self): ''' Open the L2socket. ''' self._packets = None self._sock = conf.L2socket(iface=self._iface) super(NetworkMonitor, self).setup()
def test_configure_sockets(self, socket_mock, *args, **kwargs): socket_mock.return_value.recv = lambda x: '{"success":0}' socket_mock.return_value.getsockname = lambda: "/tmp/blafoo" scapy_unroot.sockets.configure_sockets() self.assertEqual("L2listen", conf.L2listen().scapy_conf_type) self.assertEqual("L2socket", conf.L2socket().scapy_conf_type) self.assertEqual("L3socket", conf.L3socket().scapy_conf_type) self.assertEqual("L3socket6", conf.L3socket6().scapy_conf_type)
def __init__( self, config: dict, boot_time: datetime.datetime, lock: Lock, sequence_number: Value, queue: Queue, ): self.log = logging.getLogger(inspect.stack()[0][1].split("/")[-1]) self.log.debug("sniffer %s; parent pid: %s", os.getpid(), os.getppid()) self.queue = queue self.boot_time = boot_time self.config = config self.sequence_number = sequence_number self.ssid = config.get("GENERAL").get("ssid") self.interface = config.get("GENERAL").get("interface") self.channel = int(config.get("GENERAL").get("channel")) self.assoc_reqs = {} self.bpf_filter = "type mgt subtype probe-req or type mgt subtype auth or type mgt subtype assoc-req or type mgt subtype reassoc-req" # mgt bpf filter: assoc-req, assoc-resp, reassoc-req, reassoc-resp, probe-req, probe-resp, beacon, atim, disassoc, auth, deauth # ctl bpf filter: ps-poll, rts, cts, ack, cf-end, cf-end-ack scapyconf.iface = self.interface self.l2socket = scapyconf.L2socket(iface=self.interface) self.log.debug(self.l2socket.outs) self.received_frame_cb = self.received_frame self.dot11_probe_request_cb = self.probe_response self.dot11_assoc_request_cb = self.assoc_req self.dot11_auth_cb = self.auth with lock: probe_resp_ies = build_fake_frame_ies(self.config) self.mac = get_mac(self.interface) self.probe_response_frame = ( RadioTap() / Dot11( subtype=DOT11_SUBTYPE_PROBE_RESP, addr2=self.mac, addr3=self.mac ) / Dot11ProbeResp(cap=0x1111) / probe_resp_ies ) self.auth_frame = ( RadioTap() / Dot11(subtype=DOT11_SUBTYPE_AUTH_REQ, addr2=self.mac, addr3=self.mac) / Dot11Auth(seqnum=0x02) ) sniff( iface=self.interface, prn=self.received_frame_cb, store=0, filter=self.bpf_filter, )
def start(self, controllers): """ Starts the switch """ for intf in self.intfs.values(): if intf.name == "lo": continue socket = conf.L2socket(iface=intf.name) self.listening_sockets[intf] = socket thread = threading.Thread(target=self.launch, kwargs={"intf": intf.name}) thread.daemon = True thread.start() self.threads.append(thread) super(UmbrellaScapy, self).start(controllers)
def __init__(self, iface, request_handler=None, dst_mac=None): """ Init ICMP sniffer. @param ifaces: interfaces to listen for ICMP reqest @param request_handler: handler function that will be called when receives ICMP request """ self.sniff_sockets = [] self.iface_hwaddr = {} self.sniff_sockets.append(conf.L2socket(type=ETH_P_IP, iface=iface, filter="icmp")) self.iface_hwaddr[iface] = get_if_hwaddr(iface) self.request_handler = request_handler self.dst_mac = dst_mac
def replay_attack(self): socket = conf.L2socket(iface = self.sniffing_interface) flipped_packets = [] print "[+] Starting replay attack" while self.replay_attack_running: # Always send fresh new packets try: for p in self.flipped_arp_packets: socket.send(p) self.n_arp_packets_sent += 1 except: pass # No buffer space available.. skip and keep sending print "[+] Stopped replay attack from last ARP packet" socket.close()
def restore_update_kernel_neighbors(intf_neigh_map, timeout=DEF_TIME_OUT): # create object for netlink calls to kernel ipclass = IPRoute() mtime = monotonic.time.time start_time = mtime() is_intf_up.counter = 0 db = swsssdk.SonicV2Connector(host='127.0.0.1') db.connect(db.STATE_DB, False) while (mtime() - start_time) < timeout: for intf, family_neigh_map in intf_neigh_map.items(): # only try to restore to kernel when link is up if is_intf_up(intf, db): src_mac = get_if_hwaddr(intf) intf_idx = ipclass.link_lookup(ifname=intf)[0] # create socket per intf to send packets s = conf.L2socket(iface=intf) # Only two families: 'IPv4' and 'IPv6' for family in ip_family.keys(): # if ip address assigned and if we have neighs in this family, restore them src_ip = first_ip_on_intf(intf, family) if src_ip and (family in family_neigh_map): neigh_list = family_neigh_map[family] for dst_ip, dmac in neigh_list: # use netlink to set neighbor entries set_neigh_in_kernel(ipclass, family, intf_idx, dst_ip, dmac) log_info( 'Sending Neigh with family: {}, intf_idx: {}, ip: {}, mac: {}' .format(family, intf_idx, dst_ip, dmac)) # sending arp/ns packet to update kernel neigh info s.send( build_arp_ns_pkt(family, src_mac, src_ip, dst_ip)) # delete this family on the intf del intf_neigh_map[intf][family] # close the pkt socket s.close() # if all families are deleted, remove the key if len(intf_neigh_map[intf]) == 0: del intf_neigh_map[intf] # map is empty, all neigh entries are restored if not intf_neigh_map: break time.sleep(CHECK_INTERVAL) db.close(db.STATE_DB)
def replay_attack(self): socket = conf.L2socket(iface = self.sniffing_interface) print "[+] Starting replay attack" while self.replay_attack_running: # Always send fresh new packets try: for p in self.flipped_arp_packets: socket.send(p) self.n_arp_packets_sent += 1 except: # No buffer space available.. wait and keep sending sleep(.25) print "[+] Stopped replay attack from last ARP packet" socket.close() SessionManager().log_event(NeutralEvent("Stopped Caffe-Latte attack. Logged {} WEP Data packets." .format(self.tcpdump_logger.get_wep_data_count())))
def arp_replay(self): if self.arp_packet is None: print "[-] No ARP packet to try replay attack." return s = conf.L2socket(iface=self.sniffing_interface) self.injection_running = True while self.injection_working: try: s.send(self.arp_packet) self.n_arp_packets_sent += 1 except: pass # No buffer space available.. skip and keep sending print "[+] Stopped replay attack from last ARP packet." self.injection_running = False self.arp_packet = None self.n_arp_packets_sent = 0 s.close()
def restore_update_kernel_neighbors(intf_neigh_map): # create object for netlink calls to kernel ipclass = IPRoute() mtime = monotonic.time.time start_time = mtime() while (mtime() - start_time) < TIME_OUT: for intf, family_neigh_map in intf_neigh_map.items(): # only try to restore to kernel when link is up if is_intf_oper_state_up(intf): src_mac = get_if_hwaddr(intf) intf_idx = ipclass.link_lookup(ifname=intf)[0] # create socket per intf to send packets s = conf.L2socket(iface=intf) # Only two families: 'IPv4' and 'IPv6' for family in ip_family.keys(): # if ip address assigned and if we have neighs in this family, restore them src_ip = first_ip_on_intf(intf, family) if src_ip and (family in family_neigh_map): neigh_list = family_neigh_map[family] for dst_ip, dmac in neigh_list: # use netlink to set neighbor entries set_neigh_in_kernel(ipclass, family, intf_idx, dst_ip, dmac) # best effort to update kernel neigh info # this will be updated by arp_update later too s.send( build_arp_ns_pkt(family, src_mac, src_ip, dst_ip)) # delete this family on the intf del intf_neigh_map[intf][family] # close the pkt socket s.close() # if all families are deleted, remove the key if len(intf_neigh_map[intf]) == 0: del intf_neigh_map[intf] # map is empty, all neigh entries are restored if not intf_neigh_map: break time.sleep(CHECK_INTERVAL)
def __init__( self, config: dict, boot_time: datetime.datetime, lock: Lock, sequence_number: Value, ): self.log = logging.getLogger(inspect.stack()[0][1].split("/")[-1]) self.log.debug("beacon pid: %s; parent pid: %s", os.getpid(), os.getppid()) self.boot_time = boot_time self.config = config self.sequence_number = sequence_number self.ssid = config.get("GENERAL").get("ssid") self.interface = config.get("GENERAL").get("interface") self.channel = int(config.get("GENERAL").get("channel")) scapyconf.iface = self.interface self.l2socket = scapyconf.L2socket(iface=self.interface) self.log.debug(self.l2socket.outs) self.beacon_interval = 0.102_400 with lock: self.mac = get_mac(self.interface) dot11 = Dot11( type=DOT11_TYPE_MANAGEMENT, subtype=DOT11_SUBTYPE_BEACON, addr1="ff:ff:ff:ff:ff:ff", addr2=self.mac, addr3=self.mac, ) dot11beacon = Dot11Beacon(cap=0x1111) beacon_frame_ies = build_fake_frame_ies(self.config) self.beacon_frame = RadioTap() / dot11 / dot11beacon / beacon_frame_ies # self.log.debug(f"origin beacon hexdump {hexdump(self.beacon_frame)}") self.log.info("starting beacon transmissions") self.every(self.beacon_interval, self.beacon)
#!/usr/bin/python from scapy.all import Ether, IP, UDP, DNS, DNSRR, sendp, conf from scapy.contrib import gtp # from scapy_http import http import pcap import sys import socket teids = {} conf.verb = 0 s = conf.L2socket(iface=sys.argv[4]) def usage(): print "program -i pcap | interface -t interface" sys.exit() def main(): sniffer = pcap.pcap(sys.argv[2], snaplen=65535) sniffer.setfilter("ip") for ts, pkt in sniffer: pkt1 = IP(str(pkt)[14:]) outpkt = Ether(dst="80:fa:5b:3e:f2:4a", src="98:54:1b:a1:fc:70")/\ IP(dst="1.1.1.1", src="2.2.2.2")/\ UDP(dport=2152, sport=2158)/\ gtp.GTP_U_Header(version=1, PT=1, S=1, teid=1, length=len(pkt1)+4)/pkt1 try: s.send(outpkt)
import random import struct import time from scapy.all import IP, UDP, Ether, conf range = xrange intf = 'lo' DSTIP = str("127.0.0.1") # Change to attack target DPORT = 1234 # attack target RATIO = 0.1 base = (Ether() / IP(dst=DSTIP) / UDP(dport=DPORT)).build() sender = conf.L2socket(iface=intf) senders = [struct.pack(">I", 0x6fde2100 + i) for i in range(256)] random.shuffle(senders) VALID_SENDER = senders[:int(len(senders) * RATIO)] INVALID_SENDER = senders[int(len(senders) * RATIO):] HEAD = base[:26] TAIL = base[30:] def genPkt(ip): return HEAD + ip + TAIL def genAtkPktInterval(): global INVALID_SENDER Count = {i: random.randint(0, 10) for i in VALID_SENDER} Count.update({i: random.randint(40, 60) for i in INVALID_SENDER})
# TODO : Fetch automatically the MAC address OUR_MAC = "aa:bb:cc:dd:ee:ff" # This interface MAC address OUR_IP = "10.1.10.2" # This interface IP address VICTIM_MAC = None # Fetched automatically VICTIM_IP = "10.1.10.3" # The victim IP address ROUTER_MAC = "aa:bb:cc:dd:ee:ff" # The MAC address of the gateway # The "(!port 514)" here avoids the SYSLOG packets. # TODO : test if I can remove it. # If a packet doesn't match the filter, it will not be detected and forwarded. CUSTOM_FILTER = f"ip and host {VICTIM_IP} and (!port 514)" # This is the socket used to forward packets my_socket = conf.L2socket(iface=INTERFACE) def quick_send(packet): """Send the packet quicker than a scapy sendp().""" try: my_socket.send(packet) except OSError as err: # TODO : only catch the "Message too long" exception print(err) def handle_packet(eth_packet): """Forward the packet. The packet can be altered if needed.""" # Declare variables for the process
Dot11FCS, Dot11Beacon, Dot11Elt, sendp, hexdump, conf, ) channel = 100 interface = "wlan0" dest = "ff:ff:ff:ff:ff:ff" source = "40:a5:ef:0c:16:81" conf.use_pcap = False # use libpcap instead of raw sockets conf.iface = interface l2socket = conf.L2socket(iface=interface) l2socket.outs def ssid(name): return bytes(str(name), "utf-8") def build(name): dot11_header = Dot11(type=0, subtype=8, addr1=dest, addr2=source, addr3=source) beacon = Dot11Beacon(cap=0x1111) data = (
def start(self): for (in_intf, out_intf) in self.intf_list: t = threading.Thread(target=self.middlebox, args=(in_intf, out_intf, conf.L2socket(iface=out_intf))) t.start()
''' def get_protocol(bytes_proto): bytes_str = map('{:02x}'.format, bytes_proto) protocol = ''.join(bytes_str).upper() return protocol ''' Within the loop the program filters every packet with the protocol "0x7000" and prints the information. ''' while True: sock = conf.L2socket( iface=sys.argv[1] ) # scapy socket which connects to a network e.g "en0", "en1" pkt = bytes(sock.recv()) # the packets get read and converted to bytes if pkt[12: 14] != b'\x70\x00': # only the packets with protocol "0x7000" get filtered continue dest_mac, src_mac, eth_proto, data = ethernet_frame( pkt) # calls the function to convert the information of the packets print('\nEthernet Frame:') print("Destination MAC: {}".format( dest_mac)) # prints the converted destination MAC-address print("Source MAC: {}".format( src_mac)) # prints the converted source MAC-address print("Protocol: {}".format(eth_proto)) # prints the converted protocol