def __init__(self, iface=None, type=ETH_P_ALL, filter=None, nofilter=0): if iface is None: iface = conf.iface self.iface = iface self.ins = open_pcap(iface, 1600, 0, 100) try: ioctl(self.ins.fileno(), BIOCIMMEDIATE, struct.pack("I", 1)) except: pass if nofilter: if type != ETH_P_ALL: # PF_PACKET stuff. Need to emulate this for pcap filter = "ether proto %i" % type else: filter = None else: if conf.except_filter: if filter: filter = "(%s) and not (%s)" % (filter, conf.except_filter) else: filter = "not (%s)" % conf.except_filter if type != ETH_P_ALL: # PF_PACKET stuff. Need to emulate this for pcap if filter: filter = "(ether proto %i) and (%s)" % (type, filter) else: filter = "ether proto %i" % type if filter: self.ins.setfilter(filter) self.outs = dnet.eth(iface)
def Process(self): while 1: try: # данные pktData = '00000001' + ''.join(packetBody(42)) # генерируем ethernet фрейм self.sPkt = dpkt.ethernet.Ethernet(dst="cf0000000000".decode('hex'), src=''.join(self.Mac.split(':')).decode('hex'), type=36864,data=pktData.decode('hex')) # расчет времени ожидания endTime = time.time() + self.timeout print "Send packet to %s" % self.iface # количество отправленных пакетов self.packetCount += 1 # отправка сгенерированного фрейма hw = dnet.eth(self.iface) hw.send(str(self.sPkt)) # количество полученных пакетов self.packetReceived = 0 # пока не вышло время ожидания while time.time() < endTime: try: # пробуем получить пакет # и проверяем на соответствие ранее отправленному self.pcaper.dispatch(-1,self.Capture) except socket.timeout: pass # Если было получено более одного пакета if self.packetReceived > 1: # Увеличиваем счетчик и информируем об этом self.loopCount += 1 print "Loop Detected. Duplication found %s" % self.packetReceived except KeyboardInterrupt: break print "Packets sent: ", self.packetCount , "Loops discovered : " , self.loopCount
def __init__(self, interface): threading.Thread.__init__(self) self.interface = interface self.sem = threading.Semaphore() self.running = True self.eth = dnet.eth(interface) self.out = None
def __init__(self, f=None, name=''): self.minSize = self.maxSize = False # These remain False until set self.clipboard = [] # Our buffer for yanking and pasting self.packets = [] # Our list of packets self.fName = name self.dataLink = pcap.DLT_EN10MB # Our default datalink # Set our default ethernet device # TODO: Need more OS's here if(os.getuid() or os.geteuid()): self.ifName = None else: osType = os.uname()[0].lower() if(osType == "openbsd"): self.ifName = "em0" elif(osType == "linux"): self.ifName = "eth0" else: self.ifName = "hme0" # Old skool Solaris self.iface = dnet.eth(self.ifName) if(f): self.read(f) # Read in and initialize capture else: self.packets.append(packet.Packet(self.dataLink, time.time(), defaultPacket, 1))
def bring_it_down(iface="en0", spam_packet='HOST:all|GET:spam'): datalink = dnet.eth(iface) h = datalink.get().encode('hex_codec') mac = ':'.join([h[i:i+2] for i in range(0, len(h), 2)]) print 'Interface: %s\nMAC Address: %s\nPayload: %s' % (iface, mac, spam_packet) while True: datalink.send(spam_packet)
def bring_it_down(iface="en4", spam_packet="HOST:all|GET:spam"): datalink = dnet.eth(iface) h = datalink.get().encode("hex_codec") mac = ":".join([h[i : i + 2] for i in range(0, len(h), 2)]) print "Interface: %s\nMAC Address: %s\nPayload: %s" % (iface, mac, spam_packet) while True: datalink.send(spam_packet)
def bring_it_down(iface="en0", spam_packet='HOST:all|GET:spam'): datalink = dnet.eth(iface) h = datalink.get().encode('hex_codec') mac = ':'.join([h[i:i + 2] for i in range(0, len(h), 2)]) print 'Interface: %s\nMAC Address: %s\nPayload: %s' % (iface, mac, spam_packet) while True: datalink.send(spam_packet)
def setInterface(self, name): name = name.strip() if(os.getuid() or os.geteuid()): return "Error:Requires root access" try: iface = dnet.eth(name) except: return "Error:Interface does not exist" try: iface.get() except: return "Error:Interface has no MAC" self.ifName = name self.iface = dnet.eth(self.ifName)
def update_devices(self): self.devices = {} devs = pcap.findalldevs() for (name, descr, addr, flags) in devs: try: test = dnet.eth(name) mac = test.get() self.devices[name] = { 'mac': mac, 'ip4': [], 'ip6': [], 'descr': descr, 'flags': flags } except: pass else: if len(addr) > 1: for (ip, mask, net, gw) in addr: try: dnet.ip_aton(ip) addr_dict = {} addr_dict['ip'] = ip addr_dict['mask'] = mask addr_dict['net'] = net addr_dict['gw'] = gw self.devices[name]['ip4'].append(addr_dict) except: pass try: dnet.ip6_aton(ip) addr_dict = {} addr_dict['ip'] = ip if PLATFORM == "Windows" and mask is None: addr_dict['mask'] = "ffff:ffff:ffff:ffff::" else: addr_dict['mask'] = mask addr_dict['net'] = net addr_dict['gw'] = gw if ip.startswith("fe80:"): addr_dict['linklocal'] = True else: addr_dict['linklocal'] = False self.devices[name]['ip6'].append(addr_dict) except: pass else: #???? pass
def run(self): self.d = dnet.eth(self.parent.interface) p = pcap.pcapObject() p.open_live(self.parent.interface, 1600, 1, 100) if not self.parent.platform == "Darwin": p.setnonblock(1) p.setfilter(self.filter, 0, 0) while self.running: try: p.dispatch(1, self.dispatch) except Exception, e: print e if DEBUG: print '-' * 60 traceback.print_exc(file=sys.stdout) print '-' * 60 time.sleep(0.001)
def run(self): self.d = dnet.eth(self.parent.interface) p = pcap.pcapObject() p.open_live(self.parent.interface, 1600, 1, 100) if not self.parent.platform == "Darwin": p.setnonblock(1) p.setfilter(self.filter, 0, 0) while self.running: try: p.dispatch(1, self.dispatch) except Exception, e: print e if DEBUG: print '-'*60 traceback.print_exc(file=sys.stdout) print '-'*60 time.sleep(0.001)
def update_devices(self): self.devices = {} devs = pcap.findalldevs() for (name, descr, addr, flags) in devs: try: test = dnet.eth(name) mac = test.get() self.devices[name] = { 'mac' : mac, 'ip4' : [], 'ip6' : [], 'descr' : descr, 'flags' : flags } except: pass else: if len(addr) > 1: for (ip, mask, net, gw) in addr: try: dnet.ip_aton(ip) addr_dict = {} addr_dict['ip'] = ip addr_dict['mask'] = mask addr_dict['net'] = net addr_dict['gw'] = gw self.devices[name]['ip4'].append(addr_dict) except: pass try: dnet.ip6_aton(ip) addr_dict = {} addr_dict['ip'] = ip if PLATFORM == "Windows" and mask is None: addr_dict['mask'] = "ffff:ffff:ffff:ffff::" else: addr_dict['mask'] = mask addr_dict['net'] = net addr_dict['gw'] = gw if ip.startswith("fe80:"): addr_dict['linklocal'] = True else: addr_dict['linklocal'] = False self.devices[name]['ip6'].append(addr_dict) except: pass else: #???? pass
def send(self, x): iff, a, gw = x.route() if iff is None: iff = conf.iface ifs, cls = self.iflist.get(iff, (None, None)) if ifs is None: iftype = self.intf.get(iff)["type"] if iftype == dnet.INTF_TYPE_ETH: try: cls = conf.l2types[1] except KeyError: warning("Unable to find Ethernet class. Using nothing") ifs = dnet.eth(iff) else: ifs = dnet.ip() self.iflist[iff] = ifs, cls if cls is None: sx = str(x) else: sx = str(cls() / x) x.sent_time = time.time() ifs.send(sx)
host_range = sys.argv[3] addr = host_range.split("-", 2) start = int(addr[0]) end = int(addr[1]) except: printUsage() sys.exit() if ((start > 255 or end > 255) or (start < 0 or end < 0) or end < start): printUsage() sys.exit() scanrange = range(start,end+1) try: interface = dnet.eth(ifname) except: print "Error opening interface. You probably aren't running as root, or the interface doesn't exist." def ip_header(dst,src,type): packet = dst + src + str(type) return packet def arp_header(hdr,op,sha,spa,tha,tpa): packet = hdr + op + sha + spa + tha + tpa return packet def arp_request(ipaddr): sha_str = str(dnet.intf().get(ifname)['link_addr']) sha = dnet.eth_aton(sha_str) spa_str = str(dnet.intf().get(ifname)['addr']).split("/")[0]
#!/usr/bin/env python import dnet from dpkt import dhcp from dpkt import udp from dpkt import ip from dpkt import ethernet sysintf = 'eth0' hw = dnet.eth(sysintf) intf = dnet.intf() # build a dhcp discover packet to request an ip d = dhcp.DHCP( chaddr=hw.get(), xid=1337, op=dhcp.DHCPDISCOVER, opts=( (dhcp.DHCP_OP_REQUEST, ''), (dhcp.DHCP_OPT_REQ_IP, ''), (dhcp.DHCP_OPT_ROUTER, ''), (dhcp.DHCP_OPT_NETMASK, ''), (dhcp.DHCP_OPT_DNS_SVRS, '') ) ) # build udp packet u = udp.UDP( dport=67, sport=68, data=d
def setUp(self): self.dev = dnet.intf().get_dst(dnet.addr('1.2.3.4'))['name'] self.eth = dnet.eth(self.dev) self.failUnless(self.eth, "couldn't open Ethernet handle")
#!/usr/bin/env python import dnet from dpkt import dhcp from dpkt import udp from dpkt import ip from dpkt import ethernet sysintf = 'eth0' hw = dnet.eth(sysintf) intf = dnet.intf() # build a dhcp discover packet to request an ip d = dhcp.DHCP(chaddr=hw.get(), xid=1337, op=dhcp.DHCPDISCOVER, opts=((dhcp.DHCP_OP_REQUEST, ''), (dhcp.DHCP_OPT_REQ_IP, ''), (dhcp.DHCP_OPT_ROUTER, ''), (dhcp.DHCP_OPT_NETMASK, ''), (dhcp.DHCP_OPT_DNS_SVRS, ''))) # build udp packet u = udp.UDP(dport=67, sport=68, data=d) u.ulen = len(u) # build ip packet i = ip.IP(dst=dnet.ip_aton('255.255.255.255'), src=intf.get(sysintf)['addr'].ip, data=u, p=ip.IP_PROTO_UDP) i.len = len(i)
def fuzz (self, this_node=None, path=[]): ''' Call this routine to get the ball rolling. No arguments are necessary as they are both utilized internally during the recursive traversal of the session graph. @type this_node: request (node) @param this_node: (Optional, def=None) Current node that is being fuzzed. @type path: List @param path: (Optional, def=[]) Nodes along the path to the current one being fuzzed. ''' # if no node is specified, then we start from the root node and initialize the session. if not this_node: # we can't fuzz if we don't have at least one target and one request. if not self.targets: raise sex.error("NO TARGETS SPECIFIED IN SESSION") if not self.edges_from(self.root.id): raise sex.error("NO REQUESTS SPECIFIED IN SESSION") this_node = self.root if self.start_webserver: try: self.server_init() except: return # XXX - TODO - complete parallel fuzzing, will likely have to thread out each target target = self.targets[0] # step through every edge from the current node. for edge in self.edges_from(this_node.id): # the destination node is the one actually being fuzzed. self.fuzz_node = self.nodes[edge.dst] num_mutations = self.fuzz_node.num_mutations() # keep track of the path as we fuzz through it, don't count the root node. # we keep track of edges as opposed to nodes because if there is more then one path through a set of # given nodes we don't want any ambiguity. path.append(edge) current_path = " -> ".join([self.nodes[e.src].name for e in path[1:]]) current_path += " -> %s" % self.fuzz_node.name self.logger.error("current fuzz path: %s" % current_path) self.logger.error("fuzzed %d of %d total cases" % (self.total_mutant_index, self.total_num_mutations)) done_with_fuzz_node = False crash_count = 0 # loop through all possible mutations of the fuzz node. while not done_with_fuzz_node: # if we need to pause, do so. self.pause() # if we have exhausted the mutations of the fuzz node, break out of the while(1). # note: when mutate() returns False, the node has been reverted to the default (valid) state. if not self.fuzz_node.mutate(): self.logger.error("all possible mutations for current fuzz node exhausted") done_with_fuzz_node = True continue # make a record in the session that a mutation was made. self.total_mutant_index += 1 # if we've hit the restart interval, restart the target. if self.restart_interval and self.total_mutant_index % self.restart_interval == 0: self.logger.error("restart interval of %d reached" % self.restart_interval) self.restart_target(target) # exception error handling routine, print log message and restart target. def error_handler (e, msg, target, sock=None): if sock and self.proto != "layer2": sock.close() msg += "\nException caught: %s" % repr(e) msg += "\nRestarting target and trying again" self.logger.critical(msg) self.restart_target(target) # if we don't need to skip the current test case. if self.total_mutant_index > self.skip: self.logger.error("fuzzing %d of %d" % (self.fuzz_node.mutant_index, num_mutations)) # attempt to complete a fuzz transmission. keep trying until we are successful, whenever a failure # occurs, restart the target. while 1: # instruct the debugger/sniffer that we are about to send a new fuzz. if target.procmon: try: target.procmon.pre_send(self.total_mutant_index) except Exception, e: error_handler(e, "failed on procmon.pre_send()", target) continue if target.netmon: try: target.netmon.pre_send(self.total_mutant_index) except Exception, e: error_handler(e, "failed on netmon.pre_send()", target) continue try: # establish a connection to the target. if self.layer2: sock = dnet.eth(self.iface) else: try: sock = socket.socket(self.af, self.proto) if self.af == socket.AF_INET6: sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if hasattr(socket, "SO_REUSEPORT"): sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) except Exception, e: error_handler(e, "failed creating socket", target) continue if self.bind: try: sock.bind(self.bind) except Exception, e: error_handler(e, "failed binding on socket", target, sock) continue try: if self.proto != "layer2": sock.settimeout(self.timeout) # Connect is needed only for TCP stream if self.connect_befor_send: sock.connect((target.host, target.port)) except Exception, e: error_handler(e, "failed connecting on socket", target, sock) continue # if SSL is requested, then enable it. if self.ssl: try: ssl = socket.ssl(sock) sock = httplib.FakeSocket(sock, ssl) except Exception, e: error_handler(e, "failed ssl setup", target, sock) continue
# print t2-t1 dip = struct.unpack(">I", socket.inet_aton("222.200.98.110"))[0] dport = 80 sip = struct.unpack(">I", socket.inet_aton("192.168.1.110"))[0] sport = 22222 seq = 1 ack = 0 flags = 0x02 payload = '' payload_length = 0 packet = a.GetTcpPacket(dip, dport, sip, sport, seq, ack, flags, payload, payload_length) print len(packet) print packet.encode('hex') e = dnet.eth("en0") e.send(packet) t1 = time.time() for i in range(1, 10000000): packet = a.GetTcpPacket(dip, dport, sip, sport, seq, ack, flags, payload, payload_length) e.send(packet) dip += 1 t2 = time.time() print t2 - t1 # t1=dpkt.tcp.TCP(sport=sport,dport=dport,flags=0x02,seq=1,ack=0,win=1200) # i1=dpkt.ip.IP(src=struct.pack('>I',sip),p=dpkt.ip.IP_PROTO_TCP,ttl=255,dst=struct.pack('>I',dip)) # e1=dpkt.ethernet.Ethernet(dst="\x8c\xab\x8e\x6e\x56\xd8",src="\x5c\xf9\x38\xa6\x66\xfe") # i1.len=i1.__len__()
except: printUsage() sys.exit() if ((start > 255 or end > 255) or (start < 0 or end < 0) or end < start): printUsage() sys.exit() if (len(sys.argv) > 4): printUsage() sys.exit() scanrange = range(start, end + 1) try: interface = dnet.eth(ifname) except: print "Error opening interface. You probably aren't running as root, or the interface doesn't exist." sys.exit() def ip_header(dst, src, type): packet = dst + src + str(type) return packet def arp_header(hdr, op, sha, spa, tha, tpa): packet = hdr + op + sha + spa + tha + tpa return packet
#成功获取到新的测试用例 try: self.post_mutate_callback(f_block) except Exception, e: self.logger.critical("post_mutate_callback() error. Exception: %s" % str(e)) os.kill(0 - os.getpid(), signal.SIGKILL) def error_handler (e, msg, sock=None): if not self.layer2 and not self.custom and sock: sock.close() self.logger.critical(msg + " Exception: %s" % str(e)) while True: #判断连接协议并创建连接 if self.layer2: sock = dnet.eth(self.iface) #create eth class elif self.custom: #用户自定义协议类型 sock = custom_sock(f_target, self.ex_send_callback) else: #TCP or UDP if sock is None: #创建socket try: (family, socktype, proto, canonname, sockaddr) = \ socket.getaddrinfo(f_target.host, f_target.port)[0] sock = socket.socket(family, self.proto) except Exception, e: error_handler(e, "failed creating socket.", sock) sock = None