rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
if ASN == 1: ASNlist = getASNlist_cymru(map(lambda x:x.split(":")[0],ips)) elif ASN == 2: ASNlist = getASNlist_radb(map(lambda x:x.split(":")[0],ips)) | ASN_query_list = dict.fromkeys(map(lambda x:x.split(":")[0],ips)).keys() if ASN in [1,2]: ASNlist = getASNlist_cymru(ASN_query_list) elif ASN == 3: ASNlist = getASNlist_radb(ASN_query_list) | def getASNlist_cymru(list): ASNlist = [] s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("whois.cymru.com",43)) s.send("begin\r\n"+"\r\n".join(list)+"\r\nend\r\n") r = "" while 1: l = s.recv(8192) if l == "": break r += l s.close() for l in r.splitlines()[1:]: asn,ip,desc = map(str.strip, l.split("|"))... |
if ASN == 1: ASN_ans_list = map(lambda x:x[0], ASNlist) ASN_remain_list = filter(lambda x: x not in ASN_ans_list, ASN_query_list) if ASN_remain_list: ASNlist += getASNlist_radb(ASN_remain_list) | def getASNlist_cymru(list): ASNlist = [] s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("whois.cymru.com",43)) s.send("begin\r\n"+"\r\n".join(list)+"\r\nend\r\n") r = "" while 1: l = s.recv(8192) if l == "": break r += l s.close() for l in r.splitlines()[1:]: asn,ip,desc = map(str.strip, l.split("|"))... | |
if self.type == 0: if self.addr3 != other.addr3: return0 | if self.type == 0: if self.addr1 != other.addr2: return 0 | def answers(self, other): if isinstance(other,Dot11): if self.type == 0: # mangement if self.addr3 != other.addr3: return0 if (other.subtype,self.subtype) in [(0,1),(2,3),(4,5)]: return 1 if self.subtype == other.subtype == 11: # auth return self.payload.answers(other.payload) elif self.type == 1: # control return 0 el... |
remain = reduce(list.__add__, hsent.values()) | remain = reduce(list.__add__, hsent.values(), []) | def sndrcv(pks, pkt, timeout = 2, inter = 0, verbose=None, chainCC=0,retry=0): if not isinstance(pkt, Gen): pkt = SetGen(pkt) if verbose is None: verbose = conf.verb debug.recv = PacketList([],"Unanswered") debug.sent = PacketList([],"Sent") debug.match = SndRcvList([]) nbrecv=0 ans = [] # do it here to fix random fie... |
fields_desc = [ LongField("timestamp", 0), ShortField("beacon_interval", 0x6400), | fields_desc = [ LELongField("timestamp", 0), LEShortField("beacon_interval", 0x6400), | def unwep(self, key=None, warn=1): if self.FCfield & 0x40 == 0: if warn: warning("No WEP to remove") return if isinstance(self.payload.payload, NoPayload): if key or conf.wepkey: self.payload.decrypt(key) if isinstance(self.payload.payload, NoPayload): if warn: warning("Dot11 can't be decrypted. Check conf.wepkey.") r... |
class LELongField(Field): def __init__(self, name, default): Field.__init__(self, name, default, "@Q") class LEFieldLenField(Field): def __init__(self, name, default, fld, fmt = "@H", shift=0): Field.__init__(self, name, default, fmt) self.fld = fld self.shift = shift def i2m(self, pkt, x): if x is None: x = len(geta... | def post_build(self, p): if self.len is None: l = len(p)-14 p = p[:10]+struct.pack("!H", l)+p[12:] return p | |
if type(iface) is list: | if iface.__class__ is list: | def __init__(self, type = ETH_P_ALL, filter=None, promisc=None, iface=None): self.type = type self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type)) self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 2**30) if conf.except_filter: if filter: filter = "(%s) and not (%s)" % (filter, conf.exc... |
if type(iface) is list: | if iface.__class__ is list: | def __init__(self, iface = None, type = ETH_P_ALL, promisc=None, filter=None): self.type = type self.outs = None self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type)) if iface is not None: self.ins.bind((iface, type)) if conf.except_filter: if filter: filter = "(%s) and not (%s)" % (filter, co... |
for f in self.fields_desc: fvalue_gen = SetGen(self.__getattr__(f),_iterpacket=0) | for f in self.packetfields: fvalue_gen = self.__getattr__(f) if fvalue_gen is None: continue if not f.islist: fvalue_gen = SetGen(fvalue_gen,_iterpacket=0) | def haslayer(self, cls): """true if self has a layer that is an instance of cls. Superseded by "cls in self" syntax.""" if self.__class__ == cls or self.__class__.__name__ == cls: return 1 for f in self.fields_desc: fvalue_gen = SetGen(self.__getattr__(f),_iterpacket=0) for fvalue in fvalue_gen: if isinstance(fvalue, P... |
for f in self.fields_desc: fvalue_gen = SetGen(self.__getattr__(f),_iterpacket=0) | for f in self.packetfields: fvalue_gen = self.__getattr__(f) if fvalue_gen is None: continue if not f.islist: fvalue_gen = SetGen(fvalue_gen,_iterpacket=0) | def getlayer(self, cls, nb=1, _track=None): """Return the nb^th layer that is an instance of cls.""" if type(cls) is str and "." in cls: ccls,fld = cls.split(".",1) else: ccls,fld = cls,None if self.__class__ == cls or self.__class__.name == ccls: if nb == 1: if fld is None: return self else: return getattr(self, fld) ... |
return (atol(thenet),(1L<<msk)-1, gw, dev, ifaddr) | return (atol(thenet), itom(msk), gw, dev, ifaddr) | def make_route(self, host=None, net=None, gw=None, dev=None): if host is not None: thenet,msk = host,32 elif net is not None: thenet,msk = net.split("/") msk = int(msk) else: raise Exception("make_route: Incorrect parameters. You should specify a host or a net") if gw is None: gw="0.0.0.0" if dev is None: if gw: nhop =... |
the_msk = (1L << int(the_msk))-1 | the_msk = itom(int(the_msk)) | def ifchange(self, iff, addr): the_addr,the_msk = (addr.split("/")+["32"])[:2] the_msk = (1L << int(the_msk))-1 the_rawaddr, = struct.unpack("I",inet_aton(the_addr)) the_net = the_rawaddr & the_msk for i in range(len(self.routes)): net,msk,gw,iface,addr = self.routes[i] if iface != iff: continue if gw == '0.0.0.0': s... |
the_msk = (1L << int(the_msk))-1 | the_msk = itom(int(the_msk)) | def ifadd(self, iff, addr): the_addr,the_msk = (addr.split("/")+["32"])[:2] the_msk = (1L << int(the_msk))-1 the_rawaddr, = struct.unpack("I",inet_aton(the_addr)) the_net = the_rawaddr & the_msk self.routes.append((the_net,the_msk,'0.0.0.0',iff,the_addr)) |
netmask = (1L << int(netmask))-1 | netmask = itom(int(netmask)) | def read_routes(): f=os.popen("netstat -rn") # -f inet ok = 0 mtu = False routes = [] for l in f.readlines(): if not l: break l = l.strip() if l.find("Destination") >= 0: ok = 1 if l.find("Mtu") >= 0: mtu = True continue if ok == 0: continue if not l: break if mtu: dest,gw,fl,ref,use,mtu,netif = l.split()[:7] else: des... |
netmask = (1L << ((dest.count(".")+1)*8))-1 | netmask = itom((dest.count(".") + 1) * 8) | def read_routes(): f=os.popen("netstat -rn") # -f inet ok = 0 mtu = False routes = [] for l in f.readlines(): if not l: break l = l.strip() if l.find("Destination") >= 0: ok = 1 if l.find("Mtu") >= 0: mtu = True continue if ok == 0: continue if not l: break if mtu: dest,gw,fl,ref,use,mtu,netif = l.split()[:7] else: des... |
print responses if responses is None: return False return True | return responses is not None def promiscping(net, timeout=2, fake_bcast="ff:ff:ff:ff:ff:fe", **kargs): """Send ARP who-has requests to determine which hosts are in promiscuous mode promiscping(net, iface=conf.iface)""" ans,unans = srp(Ether(dst=fake_bcast)/ARP(pdst=net), filter="arp and arp[7] = 2", timeout=timeout, i... | def is_promisc(ip, fake_bcast="ff:ff:00:00:00:00",**kargs): """Try to guess if target is in Promisc mode. The target is provided by its ip.""" responses = srp1(Ether(dst=fake_bcast) / ARP(op="who-has", pdst=ip),type=ETH_P_ARP, iface_hint=ip, timeout=1, verbose=0,**kargs) print responses if responses is None: return F... |
user_commands = [ sr, sr1, srp, srp1, srloop, srploop, sniff, p0f, arpcachepoison, send, sendp, traceroute, arping, ls, lsc, queso, nmap_fp, report_ports, dyndns_add, dyndns_del, is_promisc ] | user_commands = [ sr, sr1, srp, srp1, srloop, srploop, sniff, p0f, arpcachepoison, send, sendp, traceroute, arping, ls, lsc, queso, nmap_fp, report_ports, dyndns_add, dyndns_del, is_promisc, promiscping ] | def ls(obj=None): """List available layers, or infos on a given layer""" if obj is None: import __builtin__ all = __builtin__.__dict__.copy() all.update(globals()) objlst = filter(lambda (n,o): type(o) is types.TypeType and issubclass(o,Packet), all.items()) objlst.sort(lambda x,y:cmp(x[0],y[0])) for n,o in objlst: pr... |
def i2len(self, pkt, s): return self.length+self.shift | def i2len(self, pkt, s): return self.length+self.shift | |
addrfamily, mac = struct.unpack("16xh6s8x",get_if(iff,SIOCGIFHWADDR)) | addrfamily, mac = get_if_raw_hwaddr(iff) | def get_if_hwaddr(iff): addrfamily, mac = struct.unpack("16xh6s8x",get_if(iff,SIOCGIFHWADDR)) if addrfamily in [ARPHDR_ETHER,ARPHDR_LOOPBACK]: return str2mac(mac) else: raise Exception("Unsupported address family (%i)"%addrfamily) |
return self.make_table(lambda x: x[0].sprintf("%IP.dst%:{TCP:tcp%TCP.dport%}{UDP:udp%UDP.dport%}{ICMP:ICMP}"), lambda x: x[0].ttl, lambda x: x[1].sprintf("%-15s,IP.src% {TCP:%TCP.flags%}{ICMP:%ir,ICMP.type%}")) | return self.make_table(lambda (s,r): (s.sprintf("%IP.dst%:{TCP:tcp%TCP.dport%}{UDP:udp%UDP.dport%}{ICMP:ICMP}"), s.ttl, r.sprintf("%-15s,IP.src% {TCP:%TCP.flags%}{ICMP:%ir,ICMP.type%}"))) | def show(self): |
l += pkt.fields_desc[pkt.fields_desc.index(self.fld)].shift | f = pkt.fields_desc[pkt.fields_desc.index(self.fld)] if isinstance(f, FieldLenField): l += f.shift | def getfield(self, pkt, s): l = getattr(pkt, self.fld) # add the shift from the length field l += pkt.fields_desc[pkt.fields_desc.index(self.fld)].shift return s[l:], self.m2i(pkt,s[:l]) |
or (self.id == socket.htons(other.id) and conf.checkIPID == 1))) and | or (conf.checkIPID == 1 and self.id == socket.htons(other.id)))) and | def answers(self, other): if not isinstance(other, IP): return 0 if not ( ((conf.checkIPsrc == 0) or (self.dst == other.dst)) and (self.src == other.src) and ( ((conf.checkIPID == 0) or (self.id == other.id) or (self.id == socket.htons(other.id) and conf.checkIPID == 1))) and (self.proto == other.proto) ): return 0 ret... |
l = l[l.find(" ")+3:] l = l[:l.find(" ")] l = "".join(l.split()) | l = l.strip() l = l[l.find(" "):] l = l.strip() l = l[:40] l = l.replace(" ","") | def import_hexcap(): p = "" try: while 1: l = raw_input() l = l[l.find(" ")+3:] l = l[:l.find(" ")] l = "".join(l.split()) p += l except EOFError: pass p2="" for i in range(len(p)/2): p2 += chr(int(p[2*i:2*i+2],16)) return p2 |
return a | return a,b | def traceroute(target, dport=80, minttl=1, maxttl=30, sport=RandShort(), l4 = None, timeout=2, **kargs): """Instant TCP traceroute |
return ans | return ans,unans | def arping(net, **kargs): """Send ARP who-has requests to determine which hosts are up |
def dhcp_request(**kargs): | def dhcp_request(iface=None,**kargs): | def dhcp_request(**kargs): if conf.checkIPaddr != 0: warning("conf.checkIPaddr is not 0, I may not be able to match the answer") return srp1(Ether(dst="ff:ff:ff:ff:ff:ff")/IP(src="0.0.0.0",dst="255.255.255.255")/UDP(sport=68,dport=67)/BOOTP()/DHCP(options=[("message-type","discover"),"end"]),**kargs) |
return srp1(Ether(dst="ff:ff:ff:ff:ff:ff")/IP(src="0.0.0.0",dst="255.255.255.255")/UDP(sport=68,dport=67)/BOOTP()/DHCP(options=[("message-type","discover"),"end"]),**kargs) | if iface is None: iface = conf.iface fam,hw = get_if_raw_hwaddr(iface) return srp1(Ether(dst="ff:ff:ff:ff:ff:ff")/IP(src="0.0.0.0",dst="255.255.255.255")/UDP(sport=68,dport=67) /BOOTP(chaddr=hw)/DHCP(options=[("message-type","discover"),"end"]),iface=iface,**kargs) | def dhcp_request(**kargs): if conf.checkIPaddr != 0: warning("conf.checkIPaddr is not 0, I may not be able to match the answer") return srp1(Ether(dst="ff:ff:ff:ff:ff:ff")/IP(src="0.0.0.0",dst="255.255.255.255")/UDP(sport=68,dport=67)/BOOTP()/DHCP(options=[("message-type","discover"),"end"]),**kargs) |
def __make_table(yfmtfunc, fmtfunc, endline, list, fx, fy, fz, sortx=None, sorty=None): | def __make_table(yfmtfunc, fmtfunc, endline, list, fxyz, sortx=None, sorty=None): | def __make_table(yfmtfunc, fmtfunc, endline, list, fx, fy, fz, sortx=None, sorty=None): vx = {} vy = {} vz = {} l = 0 for e in list: xx = str(fx(e)) yy = str(fy(e)) zz = str(fz(e)) l = max(len(yy),l) vx[xx] = max(vx.get(xx,0), len(xx), len(zz)) vy[yy] = None vz[(xx,yy)] = zz vxk = vx.keys() vyk = vy.keys() if sortx: v... |
xx = str(fx(e)) yy = str(fy(e)) zz = str(fz(e)) | xx,yy,zz = map(str, fxyz(e)) | def __make_table(yfmtfunc, fmtfunc, endline, list, fx, fy, fz, sortx=None, sorty=None): vx = {} vy = {} vz = {} l = 0 for e in list: xx = str(fx(e)) yy = str(fy(e)) zz = str(fz(e)) l = max(len(yy),l) vx[xx] = max(vx.get(xx,0), len(xx), len(zz)) vy[yy] = None vz[(xx,yy)] = zz vxk = vx.keys() vyk = vy.keys() if sortx: v... |
for i in __builtins__: obj = __builtins__[i] if not type(obj) is types.ClassType: continue if issubclass(obj, Packet): print "%-10s : %s" %(i,obj.name) | objlst = filter(lambda (n,o): type(o) is types.ClassType and issubclass(o,Packet), __builtins__.items()) objlst.sort(lambda x,y:cmp(x[0],y[0])) for n,o in objlst: print "%-10s : %s" %(n,o.name) | def ls(obj=None): """List available layers, or infos on a given layer""" if obj is None: for i in __builtins__: obj = __builtins__[i] if not type(obj) is types.ClassType: continue if issubclass(obj, Packet): print "%-10s : %s" %(i,obj.name) else: if type(obj) is types.ClassType and issubclass(obj, Packet): for f in ob... |
ac = pickle.load(rdpipe) arp_cache.update(ac) os.waitpid(pid,0) | try: ac = pickle.load(rdpipe) except EOFError: warning("Child died unexpectedly. Packets may have not been sent") else: arp_cache.update(ac) os.waitpid(pid,0) | def sndrcv(pks, pkt, timeout = 2, inter = 0, verbose=None): if not isinstance(pkt, Gen): pkt = SetGen(pkt) if verbose is None: verbose = conf.verb recv = [] ans = [] # do it here to fix random fields, so that parent and child have the same sent = [p for p in pkt] notans = len(sent) hsent={} for i in sent: h = i.hash... |
def srp(x,iface=None,filter=None,type=None, *args,**kargs): | def srp(x,iface=None,filter=None,type=ETH_P_ALL, *args,**kargs): | def srp(x,iface=None,filter=None,type=None, *args,**kargs): """Send and receive packets at layer 2""" if not kargs.has_key("timeout"): kargs["timeout"] = -1 a,b,c=sndrcv(conf.L2socket(iface=iface, filter=filter, type=type),x,*args,**kargs) return a,b |
def srp1(x,iface=None,filter=None,type=None, *args,**kargs): | def srp1(x,iface=None,filter=None,type=ETH_P_ALL, *args,**kargs): | def srp1(x,iface=None,filter=None,type=None, *args,**kargs): """Send and receive packets at layer 2 and return only the first answer""" if not kargs.has_key("timeout"): kargs["timeout"] = -1 a,b,c=sndrcv(conf.L2socket(iface=iface, filter=filter, type=type),x,*args,**kargs) if len(a) > 0: return a[0][1] else: return Non... |
f = os.popen("tcpdump -i s -ddd -s 1600 '%s'" % (conf.iface,filter)) | f = os.popen("tcpdump -i %s -ddd -s 1600 '%s'" % (conf.iface,filter)) | def attach_filter(s, filter): # XXX We generate the filter on the interface conf.iface # because tcpdump open the "any" interface and ppp interfaces # in cooked mode. As we use them in raw mode, the filter will not # work... one solution could be to use "any" interface and translate # the filter from cooked mode to raw... |
print "%-10s : %s (%s)" % (f.name, f.__class__.__name__, repr(f.default)) | print "%-10s : %-20s = (%s)" % (f.name, f.__class__.__name__, repr(f.default)) elif isinstance(obj, Packet): for f in obj.fields_desc: print "%-10s : %-20s = %-15s (%s)" % (f.name, f.__class__.__name__, repr(getattr(obj,f.name)), repr(f.default)) if not isinstance(obj.payload, NoPayload): print "--" ls(obj.payload) | def ls(obj=None): """List available layers, or infos on a given layer""" if obj is None: for i in __builtins__: obj = __builtins__[i] if not type(obj) is types.ClassType: continue if issubclass(obj, Packet): print "%-10s : %s" %(i,obj.name) else: if type(obj) is types.ClassType and issubclass(obj, Packet): for f in ob... |
def dispatch(self, callback): """call the specified callback routine for each packet read This is just a convienience function for the main loop that allows for easy launching of packet processing in a thread. """ p = self.read_packet() while p != None: callback(p) p = self.read_packet() def read_all(self): """return... | def dispatch(self, callback): """call the specified callback routine for each packet read | def dispatch(self, callback): """call the specified callback routine for each packet read |
"""A pcap writer with more control than wrpcap() This routine is based entirely on scapy.wrpcap(), but adds capability of writing one packet at a time in a streaming manner. | def __init__(self, filename, linktype=1): self.f = open(filename,"w") self.f.write(struct.pack("IHHIIII", 0xa1b2c3d4L, 2, 4, 0, 0, MTU, linktype)) def write(self, packets): """accepts a either a single packet or a list of packets to be written to the dumpfile | def recv(self, size): """ Emulate a socket """ return self.read_packet() |
def __init__(self, filename, linktype=1): self.f = open(filename,"w") self.f.write(struct.pack("IHHIIII", 0xa1b2c3d4L, 2, 4, 0, 0, MTU, linktype)) def write(self, packets): """accepts a either a single packet or a list of packets to be written to the dumpfile """ if type(packets) == type(list): for p in packets: self.... | if type(packets) == type(list): for p in packets: self.write_packet(p) else: self.write_packet(packets) def write_packet(self, packet): """writes a single packet to the pcap file """ s = str(packet) l = len(s) sec = int(packet.time) usec = int((packet.time-sec)*1000000) self.f.write(struct.pack("IIII", sec, usec, l, l... | def __init__(self, filename, linktype=1): self.f = open(filename,"w") self.f.write(struct.pack("IHHIIII", 0xa1b2c3d4L, 2, 4, 0, 0, MTU, linktype)) # XXX Find the link type |
self.__getattr__(f).show(indent=indent, label_lvl=label_lvl+lvl+(" "*indent)+"|") | self.__getattr__(f).show(indent=indent, label_lvl=label_lvl+lvl+" |") | def show(self, indent=3, lvl="", label_lvl=""): """Prints a hierarchical view of the packet. "indent" gives the size of indentation for each layer.""" ct = conf.color_theme print "%s%s %s %s" % (label_lvl, ct.punct("###["), ct.layer_name(self.name), ct.punct("]###")) for f in self.fields_desc: if isinstance(f, Emph): n... |
x = len(getattr(pkt, self.fld))-self.shift | f = pkt.fields_desc[pkt.fields_desc.index(self.fld)] v = f.i2m(pkt,getattr(pkt, self.fld)) x = len(v)-self.shift | def i2m(self, pkt, x): if x is None: x = len(getattr(pkt, self.fld))-self.shift return x |
def i2h(self, pkt, x): if x is None: x = len(getattr(pkt, self.fld))+self.shift return x | def i2h(self, pkt, x): if x is None: x = len(getattr(pkt, self.fld))+self.shift return x | |
def remove_underlayer(self, underlayer): | def remove_underlayer(self,other): | def remove_underlayer(self, underlayer): self.underlayer = None |
def remove_underlayer(self): | def remove_underlayer(self,other): | def remove_underlayer(self): pass |
warning("Dest mac not calculated if more than 1 dest IP (%s)"%repr(dstip)) return None x = "ff:ff:ff:ff:ff:ff" | dstip = dstip.__iter__().next() | def i2h(self, pkt, x): if x is None: dstip = None if isinstance(pkt.payload, IP): dstip = pkt.payload.dst elif isinstance(pkt.payload, ARP): dstip = pkt.payload.pdst if isinstance(dstip, Gen): warning("Dest mac not calculated if more than 1 dest IP (%s)"%repr(dstip)) return None x = "ff:ff:ff:ff:ff:ff" if dstip is not ... |
m=getmacbyip(dstip) if m: x = m else: warning("Mac address for %s not found\n"%dstip) | x=getmacbyip(dstip) if x is None: x = "ff:ff:ff:ff:ff:ff" warning("Mac address to reach %s not found\n"%dstip) | def i2h(self, pkt, x): if x is None: dstip = None if isinstance(pkt.payload, IP): dstip = pkt.payload.dst elif isinstance(pkt.payload, ARP): dstip = pkt.payload.pdst if isinstance(dstip, Gen): warning("Dest mac not calculated if more than 1 dest IP (%s)"%repr(dstip)) return None x = "ff:ff:ff:ff:ff:ff" if dstip is not ... |
warning("Source mac not calculated if more than 1 dest IP (%s)"%repr(dstip)) return None x = "00:00:00:00:00:00" | dstip = dstip.__iter__().next() | def i2h(self, pkt, x): if x is None: dstip = None if isinstance(pkt.payload, IP): dstip = pkt.payload.dst elif isinstance(pkt.payload, ARP): dstip = pkt.payload.pdst if isinstance(dstip, Gen): warning("Source mac not calculated if more than 1 dest IP (%s)"%repr(dstip)) return None x = "00:00:00:00:00:00" if dstip is no... |
m = get_if_hwaddr(iff) if m: x = m | x = get_if_hwaddr(iff) if x is None: x = "00:00:00:00:00:00" | def i2h(self, pkt, x): if x is None: dstip = None if isinstance(pkt.payload, IP): dstip = pkt.payload.dst elif isinstance(pkt.payload, ARP): dstip = pkt.payload.pdst if isinstance(dstip, Gen): warning("Source mac not calculated if more than 1 dest IP (%s)"%repr(dstip)) return None x = "00:00:00:00:00:00" if dstip is no... |
warning("Source mac not calculated if more than 1 dest IP (%s)"%repr(dstip)) return None x = "00:00:00:00:00:00" | dstip = dstip.__iter__().next() | def i2h(self, pkt, x): if x is None: dstip = pkt.pdst if isinstance(dstip, Gen): warning("Source mac not calculated if more than 1 dest IP (%s)"%repr(dstip)) return None x = "00:00:00:00:00:00" if dstip is not None: iff,a,gw = conf.route.route(dstip) m = get_if_hwaddr(iff) if m: x = m return MACField.i2h(self, pkt, x) |
m = get_if_hwaddr(iff) if m: x = m | x = get_if_hwaddr(iff) if x is None: x = "00:00:00:00:00:00" | def i2h(self, pkt, x): if x is None: dstip = pkt.pdst if isinstance(dstip, Gen): warning("Source mac not calculated if more than 1 dest IP (%s)"%repr(dstip)) return None x = "00:00:00:00:00:00" if dstip is not None: iff,a,gw = conf.route.route(dstip) m = get_if_hwaddr(iff) if m: x = m return MACField.i2h(self, pkt, x) |
mtu = False | mtu_present = False | def read_routes(): if SOLARIS: f=os.popen("netstat -rvn") # -f inet else: f=os.popen("netstat -rn") # -f inet ok = 0 mtu = False routes = [] for l in f.readlines(): if not l: break l = l.strip() if l.find("----") >= 0: # a separation line continue if l.find("Destination") >= 0: ok = 1 if l.find("Mtu") >= 0: mtu_present... |
return self.i2s.get(x, x) | return self.i2s.get(x, repr(x)) | def i2repr(self, pkt, x): return self.i2s.get(x, x) |
def sum(self): return self.sprintf("Info %Dot11Elt.ID%") | def mysummary(self): if self.ID == 0: return self.sprintf("SSID=%s"%self.info),[Dot11] else: return "" | def sum(self): return self.sprintf("Info %Dot11Elt.ID%") |
l = map(f,self.res) | l = self.res | def plot(self, f, lfilter=None,**kargs): """Applies a function to each packet to get a value that will be plotted with GnuPlot. A gnuplot object is returned lfilter: a truth function that decides whether a packet must be ploted""" g=Gnuplot.Gnuplot() l = map(f,self.res) if lfilter is not None: l = filter(lfilter, l) g.... |
x = get_if_hwaddr(iff) | try: x = get_if_hwaddr(iff) except: pass | def i2h(self, pkt, x): if x is None: dstip = None if isinstance(pkt.payload, IPv6): dstip = pkt.payload.dst elif isinstance(pkt.payload, IP): dstip = pkt.payload.dst elif isinstance(pkt.payload, ARP): dstip = pkt.payload.pdst if isinstance(dstip, Gen): dstip = dstip.__iter__().next() if dstip is not None: if isinstance... |
x = get_if_hwaddr(iff) | try: x = get_if_hwaddr(iff) except: pass | def i2h(self, pkt, x): if x is None: dstip = pkt.pdst if isinstance(dstip, Gen): dstip = dstip.__iter__().next() if dstip is not None: iff,a,gw = conf.route.route(dstip) x = get_if_hwaddr(iff) if x is None: x = "00:00:00:00:00:00" return MACField.i2h(self, pkt, x) |
p0f_base = [] p0f_ttl_range=[255] def init_p0f(base=None,reset=1): global p0f_base global p0f_ttl_range if reset: p0f_base=[] p0f_ttl_range=[255] if base is None: base = conf.p0f_base try: f=open(base) except IOError: return for l in f: if l[0] in [" continue l = tuple(l.split(":")) if len(l) < 9: continue li = map(in... | class p0fKnowledgeBase(KnowledgeBase): def __init__(self, filename): KnowledgeBase.__init__(self, filename) self.ttl_range=[255] def lazy_init(self): try: f=open(self.filename) except IOError: warning("Can't open base %s" % self.filename) return try: self.base = [] for l in f: if l[0] in [" continue l = tuple(l.split("... | def attach_filter(s, filter): # XXX We generate the filter on the interface conf.iface # because tcpdump open the "any" interface and ppp interfaces # in cooked mode. As we use them in raw mode, the filter will not # work... one solution could be to use "any" interface and translate # the filter from cooked mode to raw... |
if not isinstance(pkt, Packet): | while pkt.haslayer(IP) and pkt.haslayer(TCP): pkt = pkt.getlayer(IP) if isinstance(pkt.payload, TCP): break pkt = pkt.payload if not isinstance(pkt, IP) or not isinstance(pkt.payload, TCP): | def packet2p0f(pkt): if not isinstance(pkt, Packet): raise TypeError("Not a TCP/IP packet") if not isinstance(pkt, IP): return packet2p0f(pkt.payload) if not isinstance(pkt.payload, TCP): raise TypeError("Not a TCP packet") if pkt.payload.flags & 0x13 != 0x02: #S,!A,!F raise TypeError("Not a syn packet") if "MSS" in p... |
if not isinstance(pkt, IP): return packet2p0f(pkt.payload) if not isinstance(pkt.payload, TCP): raise TypeError("Not a TCP packet") | def packet2p0f(pkt): if not isinstance(pkt, Packet): raise TypeError("Not a TCP/IP packet") if not isinstance(pkt, IP): return packet2p0f(pkt.payload) if not isinstance(pkt.payload, TCP): raise TypeError("Not a TCP packet") if pkt.payload.flags & 0x13 != 0x02: #S,!A,!F raise TypeError("Not a syn packet") if "MSS" in p... | |
t = p0f_ttl_range[:] | t = p0f_kdb.ttl_range[:] | def packet2p0f(pkt): if not isinstance(pkt, Packet): raise TypeError("Not a TCP/IP packet") if not isinstance(pkt, IP): return packet2p0f(pkt.payload) if not isinstance(pkt.payload, TCP): raise TypeError("Not a TCP packet") if pkt.payload.flags & 0x13 != 0x02: #S,!A,!F raise TypeError("Not a syn packet") if "MSS" in p... |
if len(p0f_base) == 0: | pb = p0f_kdb.get_base() if not pb: | def p0f(pkt): """Passive OS fingerprinting: which OS emitted this TCP SYN ? |
s = len(p0f_base[0][0]) | s = len(pb[0][0]) | def p0f(pkt): """Passive OS fingerprinting: which OS emitted this TCP SYN ? |
for b,name in p0f_base: | for b,name in pb: | def p0f(pkt): """Passive OS fingerprinting: which OS emitted this TCP SYN ? |
queso_base={} | def pkt2uptime(pkt, HZ=100): """Calculate the date the machine which emitted the packet booted using TCP timestamp | |
def init_queso(base=None, reset=1): global queso_base if reset: queso_base = {} if base is None: base = conf.queso_base try: f = open(base) except IOError: return p = None for l in f: l = l.strip() if not l or l[0] == ';': continue if l[0] == '*': | class QuesoKnowledgeBase(KnowledgeBase): def lazy_init(self): try: f = open(self.filename) except IOError: return self.base = {} p = None try: for l in f: l = l.strip() if not l or l[0] == ';': continue if l[0] == '*': if p is not None: p[""] = name name = l[1:].strip() p = self.base continue if l[0] not in list("01234... | def init_queso(base=None, reset=1): global queso_base if reset: queso_base = {} if base is None: base = conf.queso_base try: f = open(base) except IOError: return p = None for l in f: l = l.strip() if not l or l[0] == ';': continue if l[0] == '*': if p is not None: p[""] = name name = l[1:].strip() p = queso_base conti... |
name = l[1:].strip() p = queso_base continue if l[0] not in list("0123456"): continue res = l[2:].split() res[-1] = quesoTCPflags(res[-1]) res = " ".join(res) if not p.has_key(res): p[res] = {} p = p[res] if p is not None: p[""] = name f.close() | except: self.base = None warning("Can't load queso base [%s]", self.filename) f.close() | def init_queso(base=None, reset=1): global queso_base if reset: queso_base = {} if base is None: base = conf.queso_base try: f = open(base) except IOError: return p = None for l in f: l = l.strip() if not l or l[0] == ';': continue if l[0] == '*': if p is not None: p[""] = name name = l[1:].strip() p = queso_base conti... |
global queso_base p = queso_base | p = queso_kdb.get_base() | def queso_sig(target, dport=80, timeout=3): global queso_base p = queso_base ret = [] for flags in ["S", "SA", "F", "FA", "SF", "P", "SEC"]: ans, unans = sr(IP(dst=target)/TCP(dport=dport,flags=flags,seq=RandInt()), timeout=timeout, verbose=0) if len(ans) == 0: rs = "- - - -" else: s,r = ans[0] rs = "%i" % (r.seq != 0)... |
p = queso_base | p = queso_kdb.get_base() | def queso_search(sig): p = queso_base sig.reverse() ret = [] try: while sig: s = sig.pop() p = p[s] if p.has_key(""): ret.append(p[""]) except KeyError: pass return ret |
nmap_base = [] def init_nmap(base=None, reset=1): global nmap_base if reset: nmap_base=[] if base is None: base = conf.nmap_base try: f=open(base) except IOError: return name = None for l in f: l = l.strip() if not l or l[0] == " continue if l[:12] == "Fingerprint ": | class NmapKnowledgeBase(KnowledgeBase): def lazy_init(self): try: f=open(self.filename) except IOError: return self.base = [] name = None try: for l in f: l = l.strip() if not l or l[0] == " continue if l[:12] == "Fingerprint ": if name is not None: self.base.append((name,sig)) name = l[12:].strip() sig={} p = self.ba... | def queso(*args,**kargs): """Queso OS fingerprinting |
nmap_base.append((name,sig)) name = l[12:].strip() sig={} p = nmap_base continue op = l.find("(") cl = l.find(")") if op < 0 or cl < 0: warning("error reading nmap os fp base file") continue test = l[:op] s = map(lambda x: x.split("="), l[op+1:cl].split("%")) si = {} for n,v in s: si[n] = v sig[test]=si if name is not ... | self.base.append((name,sig)) except: self.base = None warning("Can't read nmap database [%s](new nmap version ?)" % base.filename) f.close() | def init_nmap(base=None, reset=1): global nmap_base if reset: nmap_base=[] if base is None: base = conf.nmap_base try: f=open(base) except IOError: return name = None for l in f: l = l.strip() if not l or l[0] == "#": continue if l[:12] == "Fingerprint ": if name is not None: nmap_base.append((name,sig)) name = l[12:]... |
for os,fp in nmap_base: | for os,fp in nmap_kdb.get_base(): | def nmap_search(sigs): guess = 0,[] for os,fp in nmap_base: c = 0.0 for t in sigs.keys(): if t in fp: c += nmap_match_one_sig(sigs[t], fp[t]) c /= len(sigs.keys()) if c > guess[0]: guess = c,[ os ] elif c == guess[0]: guess[1].append(os) return guess |
init_p0f() init_queso() init_nmap() | p0f_kdb = p0fKnowledgeBase(conf.p0f_base) queso_kdb = QuesoKnowledgeBase(conf.queso_base) nmap_kdb = NmapKnowledgeBase(conf.nmap_base) | def reset(self): self.__dict__ = {} |
readline.read_history_file(scapy.conf.histfile) | try: readline.read_history_file(scapy.conf.histfile) except IOError: pass | def usage(): print "Usage: scapy.py [-s sessionfile]" sys.exit(0) |
def __init__(self, set): | def __init__(self, set, _iterpacket=1): self._iterpacket=_iterpacket | def __init__(self, set): if type(set) is list: self.set = set elif isinstance(set, PacketList): self.set = list(set) else: self.set = [set] |
elif isinstance(i, Gen): | elif isinstance(i, Gen) and (self._iterpacket or not isinstance(i,Packet)): | def __iter__(self): for i in self.set: if (type(i) is tuple) and (len(i) == 2) and type(i[0]) is int and type(i[1]) is int: if (i[0] <= i[1]): j=i[0] while j <= i[1]: yield j j += 1 elif isinstance(i, Gen): for j in i: yield j else: yield i |
fvalue_gen = SetGen(self.__getattr__(f)) | fvalue_gen = SetGen(self.__getattr__(f),_iterpacket=0) | def haslayer(self, cls): """true if self has a layer that is an instance of cls. Superseded by "cls in self" syntax.""" if self.__class__ == cls or self.__class__.__name__ == cls: return 1 for f in self.fields_desc: fvalue_gen = SetGen(self.__getattr__(f)) for fvalue in fvalue_gen: if isinstance(fvalue, Packet): ret = ... |
fvalue_gen = SetGen(self.__getattr__(f)) | fvalue_gen = SetGen(self.__getattr__(f),_iterpacket=0) | def getlayer(self, cls, nb=1, _track=None): """Return the nb^th layer that is an instance of cls.""" if type(cls) is str and "." in cls: ccls,fld = cls.split(".",1) else: ccls,fld = cls,None if self.__class__ == cls or self.__class__.name == ccls: if nb == 1: if fld is None: return self else: return getattr(self, fld) ... |
fvalue_gen = SetGen(self.__getattr__(f)) | fvalue_gen = SetGen(self.__getattr__(f),_iterpacket=0) | def show(self, indent=3, lvl="", label_lvl=""): """Prints a hierarchical view of the packet. "indent" gives the size of indentation for each layer.""" ct = conf.color_theme print "%s%s %s %s" % (label_lvl, ct.punct("###["), ct.layer_name(self.name), ct.punct("]###")) for f in self.fields_desc: if isinstance(f, Emph): n... |
l = len(s) p = max(1,int(l*8*p)) | l = len(s)*8 p = max(1,int(l*p)) | def corrupt_bits(s, p=0.01): s = array.array("B",str(s)) l = len(s) p = max(1,int(l*8*p)) for i in random.sample(xrange(l), p): s[i/8] ^= 1 << (i%8) return s.tostring() |
DNET=PCAP=0 | DNET=PCAP=1 | def attr_matches(self, text): m = re.match(r"(\w+(\.\w+)*)\.(\w*)", text) if not m: return expr, attr = m.group(1, 3) try: object = eval(expr) except: object = eval(expr, session) if isinstance(object, scapy.Packet): words = filter(lambda x: x[0]!="_",dir(object)) words += map(str, object.fields_desc) else: words = dir... |
l = dnet.intf().get(iff) l = l["link_addr"] | try: l = dnet.intf().get(iff) l = l["link_addr"] except: raise Exception("Error in attempting to get hw address for interface [%s]" % iff) | def get_if_raw_hwaddr(iff): if iff[:2] == "lo": return (772, '\x00'*6) l = dnet.intf().get(iff) l = l["link_addr"] return l.type,l.data |
dest,gw,fl,ref,use,netif = l.split()[:6] | if OPENBSD: dest,gw,fl,ref,use,mtu,netif = l.split()[:7] else: dest,gw,fl,ref,use,netif = l.split()[:6] | def read_routes(): f=os.popen("netstat -rn") # -f inet ok = 0 routes = [] for l in f.readlines(): if not l: break l = l.strip() if l.find("Destination") >= 0: ok = 1 continue if ok == 0: continue if not l: break dest,gw,fl,ref,use,netif = l.split()[:6] if dest == "default": dest = 0L netmask = 0L else: if "/" in dest: ... |
ByteField("key", 0), | ByteField("keyid", 0), | def sum(self): return self.sprintf("Info %Dot11Elt.ID%") |
f=open(session_name) session=cPickle.load(f) f.close() print "Using session [%s]" % session_name except IOError: | os.stat(session_name) except OSError: | def attr_matches(self, text): m = re.match(r"(\w+(\.\w+)*)\.(\w*)", text) if not m: return expr, attr = m.group(1, 3) try: object = eval(expr) except: object = eval(expr, session) if isinstance(object, scapy.Packet): words = filter(lambda x: x[0]!="_",dir(object)) words += map(str, object.fields_desc) else: words = dir... |
except EOFError: print "Error opening session [%s]" % session_name except AttributeError: print "Error opening session [%s]. Attribute missing" % session_name | else: try: try: session = cPickle.load(gzip.open(session_name)) except IOError: session = cPickle.load(open(session_name)) print "Using session [%s]" % session_name except EOFError: print "Error opening session [%s]" % session_name except AttributeError: print "Error opening session [%s]. Attribute missing" % session_... | def attr_matches(self, text): m = re.match(r"(\w+(\.\w+)*)\.(\w*)", text) if not m: return expr, attr = m.group(1, 3) try: object = eval(expr) except: object = eval(expr, session) if isinstance(object, scapy.Packet): words = filter(lambda x: x[0]!="_",dir(object)) words += map(str, object.fields_desc) else: words = dir... |
saved = {} if session.has_key("__builtins__"): saved["__builtins__"] = session["__builtins__"] del(session["__builtins__"]) for k in session.keys(): if type(session[k]) in [types.ClassType, types.ModuleType]: print "[%s] (%s) can't be saved. Deleted." % (k, type(session[k])) saved[k] = session[k] del(session[k]) | to_be_saved = session.copy() if to_be_saved.has_key("__builtins__"): del(to_be_saved["__builtins__"]) for k in to_be_saved.keys(): if type(to_be_saved[k]) in [types.ClassType, types.ModuleType]: print "[%s] (%s) can't be saved. Deleted." % (k, type(to_be_saved[k])) del(to_be_saved[k]) | def save_session(fname, session=None, pickleProto=-1): if session is None: session = scapy_session saved = {} if session.has_key("__builtins__"): saved["__builtins__"] = session["__builtins__"] del(session["__builtins__"]) for k in session.keys(): if type(session[k]) in [types.ClassType, types.ModuleType]: print "[%... |
cPickle.dump(session, f, pickleProto) | cPickle.dump(to_be_saved, f, pickleProto) | def save_session(fname, session=None, pickleProto=-1): if session is None: session = scapy_session saved = {} if session.has_key("__builtins__"): saved["__builtins__"] = session["__builtins__"] del(session["__builtins__"]) for k in session.keys(): if type(session[k]) in [types.ClassType, types.ModuleType]: print "[%... |
session.update(saved) | def save_session(fname, session=None, pickleProto=-1): if session is None: session = scapy_session saved = {} if session.has_key("__builtins__"): saved["__builtins__"] = session["__builtins__"] del(session["__builtins__"]) for k in session.keys(): if type(session[k]) in [types.ClassType, types.ModuleType]: print "[%... | |
send(reply, **self.optsend) | self.send_function(reply, **self.optsend) | def send_reply(self, reply): send(reply, **self.optsend) |
def send_reply(self, reply): sendp(reply, **self.optsend) | def send_reply(self, reply): sendp(reply, **self.optsend) | |
def send_reply(self, reply): sendp(reply, **self.optsend) | def make_reply(self, req): ether = req.getlayer(Ether) arp = req.getlayer(ARP) iff,a,gw = conf.route.route(arp.psrc) if self.iface != None: iff = iface ARP_addr = self.ARP_addr IP_addr = arp.pdst resp = Ether(dst=ether.src, src=ARP_addr)/ARP(op="is-at", hwsrc=ARP_addr, psrc=IP_addr, hwdst=arp.hwsrc, pdst=arp.pdst) retu... | |
while 1: l = f.readline() if not l: break | for l in f: | def init_queso(base=None, reset=1): global queso_base if reset: queso_base = {} if base is None: base = conf.queso_base try: f = open(base) except IOError: return p = None while 1: l = f.readline() if not l: break l = l.strip() if not l: continue if l[0] == ';': continue if l[0] == '*': if p is not None: p[""] = name n... |
if not l: continue if l[0] == ';': | if not l or l[0] == ';': | def init_queso(base=None, reset=1): global queso_base if reset: queso_base = {} if base is None: base = conf.queso_base try: f = open(base) except IOError: return p = None while 1: l = f.readline() if not l: break l = l.strip() if not l: continue if l[0] == ';': continue if l[0] == '*': if p is not None: p[""] = name n... |
if l[0] not in ["0","1","2","3","4","5","6"]: | if l[0] not in list("0123456"): | def init_queso(base=None, reset=1): global queso_base if reset: queso_base = {} if base is None: base = conf.queso_base try: f = open(base) except IOError: return p = None while 1: l = f.readline() if not l: break l = l.strip() if not l: continue if l[0] == ';': continue if l[0] == '*': if p is not None: p[""] = name n... |
return queso_base | if p is not None: p[""] = name f.close() | def init_queso(base=None, reset=1): global queso_base if reset: queso_base = {} if base is None: base = conf.queso_base try: f = open(base) except IOError: return p = None while 1: l = f.readline() if not l: break l = l.strip() if not l: continue if l[0] == ';': continue if l[0] == '*': if p is not None: p[""] = name n... |
import code,sys,pickle,types,os | import code,sys,cPickle,types,os | def usage(): print "Usage: scapy.py [-s sessionfile]" sys.exit(0) |
session=pickle.load(f) | session=cPickle.load(f) | def usage(): print "Usage: scapy.py [-s sessionfile]" sys.exit(0) |
pickle.dump(session, f) | cPickle.dump(session, f) | def usage(): print "Usage: scapy.py [-s sessionfile]" sys.exit(0) |
class param: iface="eth0" | def usage(): print "Usage: scapy.py [-s sessionfile]" sys.exit(0) | |
def send(x, iface=None, slp=-1): if iface is None: iface = param.iface s=socket.socket(socket.AF_PACKET, socket.SOCK_RAW, 0) s.bind((iface, 0)) if slp >= 0: try: while 1: s.send(str(x)) time.sleep(slp) except KeyboardInterrupt: pass else: s.send(str(x)) s.close() | def send(x, iface=None, slp=-1): if iface is None: iface = param.iface s=socket.socket(socket.AF_PACKET, socket.SOCK_RAW, 0) s.bind((iface, 0)) if slp >= 0: try: while 1: s.send(str(x)) time.sleep(slp) except KeyboardInterrupt: pass else: s.send(str(x)) s.close() | |
def send(x, *args, **kargs): | def send(x, inter=0, *args, **kargs): | def send(x, *args, **kargs): """Send packets at layer 3""" s=L3PacketSocket() s.send(x) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.