desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Return a volatile object whose value is both random and suitable for this field'
def randval(self):
fmtt = self.fmt[(-1)] if (fmtt in 'BHIQ'): return {'B': RandByte, 'H': RandShort, 'I': RandInt, 'Q': RandLong}[fmtt]() elif (fmtt == 's'): if (self.fmt[0] in '0123456789'): l = int(self.fmt[:(-1)]) else: l = int(self.fmt[1:(-1)]) return RandBin(l) ...
'Fragment IP datagrams'
def fragment(self, fragsize=1480):
fragsize = (((fragsize + 7) / 8) * 8) lst = [] fnb = 0 fl = self while (fl.underlayer is not None): fnb += 1 fl = fl.underlayer for p in fl: s = str(p[fnb].payload) nb = (((len(s) + fragsize) - 1) / fragsize) for i in range(nb): q = p.copy() ...
'Give a 3D representation of the traceroute. right button: rotate the scene middle button: zoom left button: move the scene left button on a ball: toggle IP displaying ctrl-left button on a ball: scan ports 21,22,23,25,80 and 443 and display the result'
def trace3D(self):
trace = self.get_trace() import visual class IPsphere(visual.sphere, ): def __init__(self, ip, **kargs): visual.sphere.__init__(self, **kargs) self.ip = ip self.label = None self.setlabel(self.ip) def setlabel(self, txt, visible=None): ...
'x.graph(ASres=conf.AS_resolver, other args): ASres=None : no AS resolver => no clustering ASres=AS_resolver() : default whois AS resolver (riswhois.ripe.net) ASres=AS_resolver_cymru(): use whois.cymru.com whois database ASres=AS_resolver(server="whois.ra.net") type: output type (svg, ps, gif, jpg, etc.), pass...
def graph(self, ASres=None, padding=0, **kargs):
if (ASres is None): ASres = conf.AS_resolver if ((self.graphdef is None) or (self.graphASres != ASres) or (self.graphpadding != padding)): self.make_graph(ASres, padding) return do_graph(self.graphdef, **kargs)
'As specified in section 4.2 of RFC 2460, every options has an alignment requirement ususally expressed xn+y, meaning the Option Type must appear at an integer multiple of x octest from the start of the header, plus y octet. That function is provided the current position from the start of the header and returns require...
def alignment_delta(self, curpos):
return 0
'overloaded version to provide a Whois resolution on the embedded IPv4 address if the address is 6to4 or Teredo. Otherwise, the native IPv6 address is passed.'
def _resolve_one(self, ip):
if in6_isaddr6to4(ip): tmp = inet_pton(socket.AF_INET6, ip) addr = inet_ntop(socket.AF_INET, tmp[2:6]) elif in6_isaddrTeredo(ip): addr = teredoAddrExtractInfo(ip)[2] else: addr = ip (_, asn, desc) = AS_resolver_riswhois._resolve_one(self, addr) return (ip, asn, desc)
'Internal method providing raw RSA encryption, i.e. simple modular exponentiation of the given message representative \'m\', a long between 0 and n-1. This is the encryption primitive RSAEP described in PKCS#1 v2.1, i.e. RFC 3447 Sect. 5.1.1. Input: m: message representative, a long between 0 and n-1, where n is the ke...
def _rsaep(self, m):
n = self.modulus if (type(m) is int): m = long(m) if ((type(m) is not long) or (m > (n - 1))): warning('Key._rsaep() expects a long between 0 and n-1') return None return self.key.encrypt(m, '')[0]
'Implements RSAES-PKCS1-V1_5-ENCRYPT() function described in section 7.2.1 of RFC 3447. Input: M: message to be encrypted, an octet string of length mLen, where mLen <= k - 11 (k denotes the length in octets of the key modulus) Output: ciphertext, an octet string of length k On error, None is returned.'
def _rsaes_pkcs1_v1_5_encrypt(self, M):
mLen = len(M) k = (self.modulusLen / 8) if (mLen > (k - 11)): warning(('Key._rsaes_pkcs1_v1_5_encrypt(): message too long (%d > %d - 11)' % (mLen, k))) return None PS = zerofree_randstring(((k - mLen) - 3)) EM = (((('\x00' + '\x02') + PS) + '\x00') + M) m ...
'Internal method providing RSAES-OAEP-ENCRYPT as defined in Sect. 7.1.1 of RFC 3447. Not intended to be used directly. Please, see encrypt() method for type "OAEP". Input: M : message to be encrypted, an octet string of length mLen where mLen <= k - 2*hLen - 2 (k denotes the length in octets of the RSA modulus and hLe...
def _rsaes_oaep_encrypt(self, M, h=None, mgf=None, L=None):
mLen = len(M) if (h is None): h = 'sha1' if (not _hashFuncParams.has_key(h)): warning('Key._rsaes_oaep_encrypt(): unknown hash function %s.', h) return None hLen = _hashFuncParams[h][0] hFun = _hashFuncParams[h][1] k = (self.modulusLen / 8) if (mLen > ((k ...
'Encrypt message \'m\' using \'t\' encryption scheme where \'t\' can be: - None: the message \'m\' is directly applied the RSAEP encryption primitive, as described in PKCS#1 v2.1, i.e. RFC 3447 Sect 5.1.1. Simply put, the message undergo a modular exponentiation using the public key. Additionnal method parameters are j...
def encrypt(self, m, t=None, h=None, mgf=None, L=None):
if (t is None): m = pkcs_os2ip(m) c = self._rsaep(m) return pkcs_i2osp(c, (self.modulusLen / 8)) elif (t == 'pkcs'): return self._rsaes_pkcs1_v1_5_encrypt(m) elif (t == 'oaep'): return self._rsaes_oaep_encrypt(m, h, mgf, L) else: warning(('Key.encrypt(): ...
'Internal method providing raw RSA verification, i.e. simple modular exponentiation of the given signature representative \'c\', an integer between 0 and n-1. This is the signature verification primitive RSAVP1 described in PKCS#1 v2.1, i.e. RFC 3447 Sect. 5.2.2. Input: s: signature representative, an integer between 0...
def _rsavp1(self, s):
return self._rsaep(s)
'Implements RSASSA-PSS-VERIFY() function described in Sect 8.1.2 of RFC 3447 Input: M: message whose signature is to be verified S: signature to be verified, an octet string of length k, where k is the length in octets of the RSA modulus n. Output: True is the signature is valid. False otherwise.'
def _rsassa_pss_verify(self, M, S, h=None, mgf=None, sLen=None):
if (h is None): h = 'sha1' if (not _hashFuncParams.has_key(h)): warning(('Key._rsassa_pss_verify(): unknown hash function provided (%s)' % h)) return False if (mgf is None): mgf = (lambda x, y: pkcs_mgf1(x, y, h)) if (sLen is None): hLen = _hashFunc...
'Implements RSASSA-PKCS1-v1_5-VERIFY() function as described in Sect. 8.2.2 of RFC 3447. Input: M: message whose signature is to be verified, an octet string S: signature to be verified, an octet string of length k, where k is the length in octets of the RSA modulus n h: hash function name (in \'md2\', \'md4\', \'md5\'...
def _rsassa_pkcs1_v1_5_verify(self, M, S, h):
k = (self.modulusLen / 8) if (len(S) != k): warning('invalid signature (len(S) != k)') return False s = pkcs_os2ip(S) m = self._rsavp1(s) EM = pkcs_i2osp(m, k) EMPrime = pkcs_emsa_pkcs1_v1_5_encode(M, k, h) if (EMPrime is None): warning('Key._rsassa_pkcs1_...
'Verify alleged signature \'S\' is indeed the signature of message \'M\' using \'t\' signature scheme where \'t\' can be: - None: the alleged signature \'S\' is directly applied the RSAVP1 signature primitive, as described in PKCS#1 v2.1, i.e. RFC 3447 Sect 5.2.1. Simply put, the provided signature is applied a moular ...
def verify(self, M, S, t=None, h=None, mgf=None, sLen=None):
if (t is None): S = pkcs_os2ip(S) n = self.modulus if (S > (n - 1)): warning('Signature to be verified is too long for key modulus') return False m = self._rsavp1(S) if (m is None): return False l = int(ma...
'Internal method providing raw RSA decryption, i.e. simple modular exponentiation of the given ciphertext representative \'c\', a long between 0 and n-1. This is the decryption primitive RSADP described in PKCS#1 v2.1, i.e. RFC 3447 Sect. 5.1.2. Input: c: ciphertest representative, a long between 0 and n-1, where n is ...
def _rsadp(self, c):
n = self.modulus if (type(c) is int): c = long(c) if ((type(c) is not long) or (c > (n - 1))): warning('Key._rsaep() expects a long between 0 and n-1') return None return self.key.decrypt(c)
'Implements RSAES-PKCS1-V1_5-DECRYPT() function described in section 7.2.2 of RFC 3447. Input: C: ciphertext to be decrypted, an octet string of length k, where k is the length in octets of the RSA modulus n. Output: an octet string of length k at most k - 11 on error, None is returned.'
def _rsaes_pkcs1_v1_5_decrypt(self, C):
cLen = len(C) k = (self.modulusLen / 8) if ((cLen != k) or (k < 11)): warning('Key._rsaes_pkcs1_v1_5_decrypt() decryption error (cLen != k or k < 11)') return None c = pkcs_os2ip(C) m = self._rsadp(c) EM = pkcs_i2osp(m, k) if (EM[0] != '\x00'): ...
'Internal method providing RSAES-OAEP-DECRYPT as defined in Sect. 7.1.2 of RFC 3447. Not intended to be used directly. Please, see encrypt() method for type "OAEP". Input: C : ciphertext to be decrypted, an octet string of length k, where k = 2*hLen + 2 (k denotes the length in octets of the RSA modulus and hLen the l...
def _rsaes_oaep_decrypt(self, C, h=None, mgf=None, L=None):
if (h is None): h = 'sha1' if (not _hashFuncParams.has_key(h)): warning('Key._rsaes_oaep_decrypt(): unknown hash function %s.', h) return None hLen = _hashFuncParams[h][0] hFun = _hashFuncParams[h][1] k = (self.modulusLen / 8) cLen = len(C) if (cLen != k):...
'Decrypt ciphertext \'C\' using \'t\' decryption scheme where \'t\' can be: - None: the ciphertext \'C\' is directly applied the RSADP decryption primitive, as described in PKCS#1 v2.1, i.e. RFC 3447 Sect 5.1.2. Simply, put the message undergo a modular exponentiation using the private key. Additionnal method parameter...
def decrypt(self, C, t=None, h=None, mgf=None, L=None):
if (t is None): C = pkcs_os2ip(C) c = self._rsadp(C) l = int(math.ceil((math.log(c, 2) / 8.0))) return pkcs_i2osp(c, l) elif (t == 'pkcs'): return self._rsaes_pkcs1_v1_5_decrypt(C) elif (t == 'oaep'): return self._rsaes_oaep_decrypt(C, h, mgf, L) else: ...
'Internal method providing raw RSA signature, i.e. simple modular exponentiation of the given message representative \'m\', an integer between 0 and n-1. This is the signature primitive RSASP1 described in PKCS#1 v2.1, i.e. RFC 3447 Sect. 5.2.1. Input: m: message representative, an integer between 0 and n-1, where n is...
def _rsasp1(self, m):
return self._rsadp(m)
'Implements RSASSA-PSS-SIGN() function described in Sect. 8.1.1 of RFC 3447. Input: M: message to be signed, an octet string Output: signature, an octet string of length k, where k is the length in octets of the RSA modulus n. On error, None is returned.'
def _rsassa_pss_sign(self, M, h=None, mgf=None, sLen=None):
if (h is None): h = 'sha1' if (not _hashFuncParams.has_key(h)): warning(('Key._rsassa_pss_sign(): unknown hash function provided (%s)' % h)) return None if (mgf is None): mgf = (lambda x, y: pkcs_mgf1(x, y, h)) if (sLen is None): hLen = _hashFuncPar...
'Implements RSASSA-PKCS1-v1_5-SIGN() function as described in Sect. 8.2.1 of RFC 3447. Input: M: message to be signed, an octet string h: hash function name (in \'md2\', \'md4\', \'md5\', \'sha1\', \'tls\' \'sha256\', \'sha384\'). Output: the signature, an octet string.'
def _rsassa_pkcs1_v1_5_sign(self, M, h):
k = (self.modulusLen / 8) EM = pkcs_emsa_pkcs1_v1_5_encode(M, k, h) if (EM is None): warning('Key._rsassa_pkcs1_v1_5_sign(): unable to encode') return None m = pkcs_os2ip(EM) s = self._rsasp1(m) S = pkcs_i2osp(s, k) return S
'Sign message \'M\' using \'t\' signature scheme where \'t\' can be: - None: the message \'M\' is directly applied the RSASP1 signature primitive, as described in PKCS#1 v2.1, i.e. RFC 3447 Sect 5.2.1. Simply put, the message undergo a modular exponentiation using the private key. Additionnal method parameters are just...
def sign(self, M, t=None, h=None, mgf=None, sLen=None):
if (t is None): M = pkcs_os2ip(M) n = self.modulus if (M > (n - 1)): warning('Message to be signed is too long for key modulus') return None s = self._rsasp1(M) if (s is None): return None return pkcs_i2os...
'True if \'other\' issued \'self\', i.e.: - self.issuer == other.subject - self is signed by other'
def isIssuerCert(self, other):
if (self.issuer != other.subject): return False keyLen = ((other.modulusLen + 7) / 8) if (keyLen != self.sigLen): return False unenc = other.encrypt(self.sig) unenc = unenc[1:] if (not ('\x00' in unenc)): return False pos = unenc.index('\x00') unenc = unenc[(pos +...
'Construct the chain of certificates leading from \'self\' to the self signed root using the certificates in \'certlist\'. If the list does not provide all the required certs to go to the root the function returns a incomplete chain starting with the certificate. This fact can be tested by tchecking if the last certifi...
def chain(self, certlist):
d = {} for c in certlist: d[c.subject] = c res = [self] cur = self while (not cur.isSelfSigned()): if d.has_key(cur.issuer): possible_issuer = d[cur.issuer] if cur.isIssuerCert(possible_issuer): res.append(possible_issuer) cur =...
'Based on the value of notBefore field, returns the number of days the certificate will still be valid. The date used for the comparison is the current and local date, as returned by time.localtime(), except if \'now\' argument is provided another one. \'now\' argument can be given as either a time tuple or a string re...
def remainingDays(self, now=None):
if (now is None): now = time.localtime() elif (type(now) is str): try: if ('/' in now): now = time.strptime(now, '%m/%d/%y') else: now = time.strptime(now, '%b %d %H:%M:%S %Y %Z') except: warning(("Bad tim...
'Export certificate in \'fmt\' format (PEM, DER or TXT) to file \'filename\''
def export(self, filename, fmt='DER'):
f = open(filename, 'wb') f.write(self.output(fmt)) f.close()
'Return True if the certificate is self signed: - issuer and subject are the same - the signature of the certificate is valid.'
def isSelfSigned(self):
if (self.issuer == self.subject): return self.isIssuerCert(self) return False
'Perform verification of certificate chains for that certificate. The behavior of verifychain method is mapped (and also based) on openssl verify userland tool (man 1 verify). A list of anchors is required. untrusted parameter can be provided a list of untrusted certificates that can be used to reconstruct the chain. I...
def verifychain(self, anchors, untrusted=None):
cafile = create_temporary_ca_file(anchors) if (not cafile): return False untrusted_file = None if untrusted: untrusted_file = create_temporary_ca_file(untrusted) if (not untrusted_file): os.unlink(cafile) return False res = self.verifychain_from_cafile...
'Does the same job as .verifychain() but using the list of anchors from the cafile. This is useful (because more efficient) if you have a lot of certificates to verify do it that way: it avoids the creation of a cafile from anchors at each call. As for .verifychain(), a list of untrusted certificates can be passed (as ...
def verifychain_from_cafile(self, cafile, untrusted_file=None):
u = '' if untrusted_file: u = ('-untrusted %s' % untrusted_file) try: cmd = ('openssl verify -CAfile %s %s ' % (cafile, u)) pemcert = self.output(fmt='PEM') cmdres = self._apply_ossl_cmd(cmd, pemcert) except: return False return (cmdres.endsw...
'Does the same job as .verifychain_from_cafile() but using the list of anchors in capath directory. The directory should contain certificates files in PEM format with associated links as created using c_rehash utility (man c_rehash). As for .verifychain_from_cafile(), a list of untrusted certificates can be passed as a...
def verifychain_from_capath(self, capath, untrusted_file=None):
u = '' if untrusted_file: u = ('-untrusted %s' % untrusted_file) try: cmd = ('openssl verify -CApath %s %s ' % (capath, u)) pemcert = self.output(fmt='PEM') cmdres = self._apply_ossl_cmd(cmd, pemcert) except: return False return (cmdres.endsw...
'Given a list of trusted CRL (their signature has already been verified with trusted anchors), this function returns True if the certificate is marked as revoked by one of those CRL. Note that if the Certificate was on hold in a previous CRL and is now valid again in a new CRL and bot are in the list, it will be consid...
def is_revoked(self, crl_list):
for c in crl_list: if ((self.authorityKeyID is not None) and (c.authorityKeyID is not None) and (self.authorityKeyID == c.authorityKeyID)): return (self.serial in map((lambda x: x[0]), c.revoked_cert_serials)) elif (self.issuer == c.issuer): return (self.serial in map((lambda...
'Return True if the CRL is signed by one of the provided anchors. False on error (invalid signature, missing anchorand, ...)'
def verify(self, anchors):
cafile = create_temporary_ca_file(anchors) if (cafile is None): return False try: cmd = (self.osslcmdbase + ('-noout -CAfile %s 2>&1' % cafile)) cmdres = self._apply_ossl_cmd(cmd, self.rawcrl) except: os.unlink(cafile) return False os.unlink(cafile) ...
'Ex: add(net="192.168.1.0/24",gw="1.2.3.4")'
def add(self, *args, **kargs):
self.invalidate_cache() self.routes.append(self.make_route(*args, **kargs))
'delt(host|net, gw|dev)'
def delt(self, *args, **kargs):
self.invalidate_cache() route = self.make_route(*args, **kargs) try: i = self.routes.index(route) del self.routes[i] except ValueError: warning('no matching route found')
'Internal function : create a route for \'dst\' via \'gw\'.'
def make_route(self, dst, gw=None, dev=None):
(prefix, plen) = (dst.split('/') + ['128'])[:2] plen = int(plen) if (gw is None): gw = '::' if (dev is None): (dev, ifaddr, x) = self.route(gw) else: lifaddr = in6_getifaddr() devaddrs = filter((lambda x: (x[2] == dev)), lifaddr) ifaddr = construct_source_cand...
'Ex: add(dst="2001:db8:cafe:f000::/56") add(dst="2001:db8:cafe:f000::/56", gw="2001:db8:cafe::1") add(dst="2001:db8:cafe:f000::/64", gw="2001:db8:cafe::1", dev="eth0")'
def add(self, *args, **kargs):
self.invalidate_cache() self.routes.append(self.make_route(*args, **kargs))
'Ex: delt(dst="::/0") delt(dst="2001:db8:cafe:f000::/56") delt(dst="2001:db8:cafe:f000::/56", gw="2001:db8:deca::1")'
def delt(self, dst, gw=None):
tmp = (dst + '/128') (dst, plen) = tmp.split('/')[:2] dst = in6_ptop(dst) plen = int(plen) l = filter((lambda x: ((in6_ptop(x[0]) == dst) and (x[1] == plen))), self.routes) if gw: gw = in6_ptop(gw) l = filter((lambda x: (in6_ptop(x[0]) == gw)), self.routes) if (len(l) == 0): ...
'removes all route entries that uses \'iff\' interface.'
def ifdel(self, iff):
new_routes = [] for rt in self.routes: if (rt[3] != iff): new_routes.append(rt) self.invalidate_cache() self.routes = new_routes
'Add an interface \'iff\' with provided address into routing table. Ex: ifadd(\'eth0\', \'2001:bd8:cafe:1::1/64\') will add following entry into Scapy6 internal routing table: Destination Next Hop iface Def src @ 2001:bd8:cafe:1::/64 :: eth0 2001:bd8:cafe:1::1 prefix length value can be omitted. I...
def ifadd(self, iff, addr):
(addr, plen) = (addr.split('/') + ['128'])[:2] addr = in6_ptop(addr) plen = int(plen) naddr = inet_pton(socket.AF_INET6, addr) nmask = in6_cidr2mask(plen) prefix = inet_ntop(socket.AF_INET6, in6_and(nmask, naddr)) self.invalidate_cache() self.routes.append((prefix, plen, '::', iff, [addr...
'Provide best route to IPv6 destination address, based on Scapy6 internal routing table content. When a set of address is passed (e.g. 2001:db8:cafe:*::1-5) an address of the set is used. Be aware of that behavior when using wildcards in upper parts of addresses ! If \'dst\' parameter is a FQDN, name resolution is perf...
def route(self, dst, dev=None):
dst = dst.split('/')[0] savedst = dst dst = dst.replace('*', '0') l = dst.find('-') while (l >= 0): m = (dst[l:] + ':').find(':') dst = (dst[:l] + dst[(l + m):]) l = dst.find('-') try: inet_pton(socket.AF_INET6, dst) except socket.error: dst = socket.g...
'Each parameter is a volatile object or a couple (volatile object, weight)'
def __init__(self, *args):
pool = [] for p in args: w = 1 if (type(p) is tuple): (p, w) = p pool += ([p] * w) self._pool = pool
'Update info about network interface according to given dnet dictionary'
def update(self, dnetdict):
self.name = dnetdict['name'] try: self.ip = socket.inet_ntoa(dnetdict['addr'].ip) except (KeyError, AttributeError, NameError): pass try: self.mac = dnetdict['link_addr'] except KeyError: pass self._update_pcapdata()
'Supplement more info from pypcap and the Windows registry'
def _update_pcapdata(self):
for n in range(30): guess = ('eth%s' % n) win_name = pcapdnet.pcap.ex_name(guess) if win_name.endswith('}'): try: uuid = win_name[win_name.index('{'):(win_name.index('}') + 1)] keyname = ('SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters\\Int...
'Populate interface table via dnet'
def load_from_dnet(self):
for i in pcapdnet.dnet.intf(): try: if (i['name'].startswith('eth') and ('addr' in i)): self.data[i['name']] = NetworkInterface(i) except (KeyError, PcapNameNotFoundError): pass if (len(self.data) == 0): log_loading.warning("No match between ...
'Return pypcap device name for given libdnet/Scapy device name This mapping is necessary because pypcap numbers the devices differently.'
def pcap_name(self, devname):
try: pcap_name = self.data[devname].pcap_name except KeyError: raise ValueError(('Unknown network interface %r' % devname)) else: return pcap_name
'Return libdnet/Scapy device name for given pypcap device name This mapping is necessary because pypcap numbers the devices differently.'
def devname(self, pcap_name):
for (devname, iface) in self.items(): if (iface.pcap_name == pcap_name): return iface.name raise ValueError(('Unknown pypcap network interface %r' % pcap_name))
'Print list of available network interfaces in human readable form'
def show(self, resolve_mac=True):
print ('%s %s %s' % ('IFACE'.ljust(5), 'IP'.ljust(15), 'MAC')) for iface_name in sorted(self.data.keys()): dev = self.data[iface_name] mac = str(dev.mac) if resolve_mac: mac = conf.manufdb._resolve_MAC(mac) print ('%s %s %s' % (str(dev.name...
'DEV: will be called after a dissection is completed'
def dissection_done(self, pkt):
self.post_dissection(pkt) self.payload.dissection_done(pkt)
'DEV: is called after the dissection of the whole packet'
def post_dissection(self, pkt):
pass
'DEV: returns the field instance from the name of the field'
def get_field(self, fld):
return self.fieldtype[fld]
'Returns a deep copy of the instance.'
def copy(self):
clone = self.__class__() clone.fields = self.fields.copy() for k in clone.fields: clone.fields[k] = self.get_field(k).do_copy(clone.fields[k]) clone.default_fields = self.default_fields.copy() clone.overloaded_fields = self.overloaded_fields.copy() clone.overload_fields = self.overload_f...
'DEV: called right after the current layer is build.'
def post_build(self, pkt, pay):
return (pkt + pay)
'psdump(filename=None, layer_shift=0, rebuild=1) Creates an EPS file describing a packet. If filename is not provided a temporary file is created and gs is called.'
def psdump(self, filename=None, **kargs):
canvas = self.canvas_dump(**kargs) if (filename is None): fname = get_temp_file(autoext='.eps') canvas.writeEPSfile(fname) subprocess.Popen([conf.prog.psreader, (fname + '.eps')]) else: canvas.writeEPSfile(filename)
'pdfdump(filename=None, layer_shift=0, rebuild=1) Creates a PDF file describing a packet. If filename is not provided a temporary file is created and xpdf is called.'
def pdfdump(self, filename=None, **kargs):
canvas = self.canvas_dump(**kargs) if (filename is None): fname = get_temp_file(autoext='.pdf') canvas.writePDFfile(fname) subprocess.Popen([conf.prog.pdfreader, (fname + '.pdf')]) else: canvas.writePDFfile(filename)
'DEV: to be overloaded to extract current layer\'s padding. Return a couple of strings (actual layer, padding)'
def extract_padding(self, s):
return (s, None)
'DEV: is called right after the current layer has been dissected'
def post_dissect(self, s):
return s
'DEV: is called right before the current layer is dissected'
def pre_dissect(self, s):
return s
'DEV: Guesses the next payload class from layer bonds. Can be overloaded to use a different mechanism.'
def guess_payload_class(self, payload):
for t in self.aliastypes: for (fval, cls) in t.payload_guess: ok = 1 for k in fval.keys(): if ((not hasattr(self, k)) or (fval[k] != self.getfieldval(k))): ok = 0 break if ok: return cls return se...
'DEV: Returns the default payload class if nothing has been found by the guess_payload_class() method.'
def default_payload_class(self, payload):
return conf.raw_layer
'Removes fields\' values that are the same as default values.'
def hide_defaults(self):
for k in self.fields.keys(): if self.default_fields.has_key(k): if (self.default_fields[k] == self.fields[k]): del self.fields[k] self.payload.hide_defaults()
'True if other is an answer from self (self ==> other).'
def __gt__(self, other):
if isinstance(other, Packet): return (other < self) elif (type(other) is str): return 1 else: raise TypeError((self, other))
'True if self is an answer from other (other ==> self).'
def __lt__(self, other):
if isinstance(other, Packet): return self.answers(other) elif (type(other) is str): return 1 else: raise TypeError((self, other))
'DEV: returns a string that has the same value for a request and its answer.'
def hashret(self):
return self.payload.hashret()
'DEV: true if self is an answer from other'
def answers(self, other):
if (other.__class__ == self.__class__): return self.payload.answers(other.payload) return 0
'true if self has a layer that is an instance of cls. Superseded by "cls in self" syntax.'
def haslayer(self, cls):
if ((self.__class__ == cls) or (self.__class__.__name__ == cls)): return 1 for f in self.packetfields: fvalue_gen = self.getfieldval(f.name) if (fvalue_gen is None): continue if (not f.islist): fvalue_gen = SetGen(fvalue_gen, _iterpacket=0) for fva...
'Return the nb^th layer that is an instance of cls.'
def getlayer(self, cls, nb=1, _track=None):
if (type(cls) is int): nb = (cls + 1) cls = None if ((type(cls) is str) and ('.' in cls)): (ccls, fld) = cls.split('.', 1) else: (ccls, fld) = (cls, None) if ((cls is None) or (self.__class__ == cls) or (self.__class__.name == ccls)): if (nb == 1): if ...
'"cls in self" returns true if self has a layer which is an instance of cls.'
def __contains__(self, cls):
return self.haslayer(cls)
'Deprecated. Use show() method.'
def display(self, *args, **kargs):
self.show(*args, **kargs)
'Prints a hierarchical view of the packet. "indent" gives the size of indentation for each layer.'
def show(self, indent=3, lvl='', label_lvl=''):
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, ConditionalField) and (not f._evalcond(self))): continue if (isinstance(f, Emph) or (f in conf.emph)): ...
'Prints a hierarchical view of an assembled version of the packet, so that automatic fields are calculated (checksums, etc.)'
def show2(self):
self.__class__(str(self)).show()
'sprintf(format, [relax=1]) -> str where format is a string that can include directives. A directive begins and ends by % and has the following format %[fmt[r],][cls[:nb].]field%. fmt is a classic printf directive, "r" can be appended for raw substitution (ex: IP.flags=0x18 instead of SA), nb is the number of the layer...
def sprintf(self, fmt, relax=1):
escape = {'%': '%', '(': '{', ')': '}'} while ('{' in fmt): i = fmt.rindex('{') j = fmt[(i + 1):].index('}') cond = fmt[(i + 1):((i + j) + 1)] k = cond.find(':') if (k < 0): raise Scapy_Exception(('Bad condition in format string: [%s] (read ...
'DEV: can be overloaded to return a string that summarizes the layer. Only one mysummary() is used in a whole packet summary: the one of the upper layer, except if a mysummary() also returns (as a couple) a list of layers whose mysummary() must be called if they are present.'
def mysummary(self):
return ''
'Prints a one line summary of a packet.'
def summary(self, intern=0):
(found, s, needed) = self._do_summary() return s
'Returns the uppest layer of the packet'
def lastlayer(self, layer=None):
return self.payload.lastlayer(self)
'Reassembles the payload and decode it using another packet class'
def decode_payload_as(self, cls):
s = str(self.payload) self.payload = cls(s, _internal=1, _underlayer=self) pp = self while (pp.underlayer is not None): pp = pp.underlayer self.payload.dissection_done(pp)
'Not ready yet. Should give the necessary C code that interfaces with libnet to recreate the packet'
def libnet(self):
print ('libnet_build_%s(' % self.__class__.name.lower()) det = self.__class__(str(self)) for f in self.fields_desc: val = det.getfieldval(f.name) if (val is None): val = 0 elif (type(val) is int): val = str(val) else: val = ('"%s"' % str(va...
'Returns a string representing the command you have to type to obtain the same packet'
def command(self):
f = [] for (fn, fv) in self.fields.items(): fld = self.get_field(fn) if isinstance(fv, Packet): fv = fv.command() elif (fld.islist and fld.holds_packets and (type(fv) is list)): fv = ('[%s]' % ','.join(map(Packet.command, fv))) else: fv = repr(...
'This returns an abbreviated stack trace with lines that only concern the caller. In other words, the stack trace inside the Pexpect module is not included.'
def get_trace(self):
tblist = traceback.extract_tb(sys.exc_info()[2]) tblist = [item for item in tblist if self.__filter_not_pexpect(item)] tblist = traceback.format_list(tblist) return ''.join(tblist)
'This returns True if list item 0 the string \'pexpect.py\' in it.'
def __filter_not_pexpect(self, trace_list_item):
if (trace_list_item[0].find('pexpect.py') == (-1)): return True else: return False
'This is the constructor. The command parameter may be a string that includes a command and any arguments to the command. For example:: child = pexpect.spawn (\'/usr/bin/ftp\') child = pexpect.spawn (\'/usr/bin/ssh user@example.com\') child = pexpect.spawn (\'ls -latr /tmp\') You may also construct it with a list of ar...
def __init__(self, command, args=[], timeout=30, maxread=2000, searchwindowsize=None, logfile=None, cwd=None, env=None):
self.STDIN_FILENO = pty.STDIN_FILENO self.STDOUT_FILENO = pty.STDOUT_FILENO self.STDERR_FILENO = pty.STDERR_FILENO self.stdin = sys.stdin self.stdout = sys.stdout self.stderr = sys.stderr self.searcher = None self.ignorecase = False self.before = None self.after = None self.m...
'This makes sure that no system resources are left open. Python only garbage collects Python objects. OS file descriptors are not Python objects, so they must be handled explicitly. If the child file descriptor was opened outside of this class (passed to the constructor) then this does not close it.'
def __del__(self):
if (not self.closed): try: self.close() except AttributeError: pass
'This returns a human-readable string that represents the state of the object.'
def __str__(self):
s = [] s.append(repr(self)) s.append((((('version: ' + __version__) + ' (') + __revision__) + ')')) s.append(('command: ' + str(self.command))) s.append(('args: ' + str(self.args))) s.append(('searcher: ' + str(self.searcher))) s.append(('buffer (last 100 chars): '...
'This starts the given command in a child process. This does all the fork/exec type of stuff for a pty. This is called by __init__. If args is empty then command will be parsed (split on spaces) and args will be set to parsed arguments.'
def _spawn(self, command, args=[]):
if (type(command) == type(0)): raise ExceptionPexpect('Command is an int type. If this is a file descriptor then maybe you want to use fdpexpect.fdspawn which takes an existing file descriptor instead of a command string.') ...
'This implements a substitute for the forkpty system call. This should be more portable than the pty.fork() function. Specifically, this should work on Solaris. Modified 10.06.05 by Geoff Marshall: Implemented __fork_pty() method to resolve the issue with Python\'s pty.fork() not supporting Solaris, particularly ssh. B...
def __fork_pty(self):
(parent_fd, child_fd) = os.openpty() if ((parent_fd < 0) or (child_fd < 0)): raise ExceptionPexpect, 'Error! Could not open pty with os.openpty().' pid = os.fork() if (pid < 0): raise ExceptionPexpect, 'Error! Failed os.fork().' elif (pid == 0): os.clo...
'This makes the pseudo-terminal the controlling tty. This should be more portable than the pty.fork() function. Specifically, this should work on Solaris.'
def __pty_make_controlling_tty(self, tty_fd):
child_name = os.ttyname(tty_fd) fd = os.open('/dev/tty', (os.O_RDWR | os.O_NOCTTY)) if (fd >= 0): os.close(fd) os.setsid() try: fd = os.open('/dev/tty', (os.O_RDWR | os.O_NOCTTY)) if (fd >= 0): os.close(fd) raise ExceptionPexpect, 'Error! We are ...
'This returns the file descriptor of the pty for the child.'
def fileno(self):
return self.child_fd
'This closes the connection with the child application. Note that calling close() more than once is valid. This emulates standard Python behavior with files. Set force to True if you want to make sure that the child is terminated (SIGKILL is sent if the child ignores SIGHUP and SIGINT).'
def close(self, force=True):
if (not self.closed): self.flush() os.close(self.child_fd) time.sleep(self.delayafterclose) if self.isalive(): if (not self.terminate(force)): raise ExceptionPexpect('close() could not terminate the child using terminate()') se...
'This does nothing. It is here to support the interface for a File-like object.'
def flush(self):
pass
'This returns True if the file descriptor is open and connected to a tty(-like) device, else False.'
def isatty(self):
return os.isatty(self.child_fd)
'This waits until the terminal ECHO flag is set False. This returns True if the echo mode is off. This returns False if the ECHO flag was not set False before the timeout. This can be used to detect when the child is waiting for a password. Usually a child application will turn off echo mode when it is waiting for the ...
def waitnoecho(self, timeout=(-1)):
if (timeout == (-1)): timeout = self.timeout if (timeout is not None): end_time = (time.time() + timeout) while True: if (not self.getecho()): return True if ((timeout < 0) and (timeout is not None)): return False if (timeout is not None): ...
'This returns the terminal echo mode. This returns True if echo is on or False if echo is off. Child applications that are expecting you to enter a password often set ECHO False. See waitnoecho().'
def getecho(self):
attr = termios.tcgetattr(self.child_fd) if (attr[3] & termios.ECHO): return True return False
'This sets the terminal echo mode on or off. Note that anything the child sent before the echo will be lost, so you should be sure that your input buffer is empty before you call setecho(). For example, the following will work as expected:: p = pexpect.spawn(\'cat\') p.sendline (\'1234\') # We will see this twice (once...
def setecho(self, state):
self.child_fd attr = termios.tcgetattr(self.child_fd) if state: attr[3] = (attr[3] | termios.ECHO) else: attr[3] = (attr[3] & (~ termios.ECHO)) termios.tcsetattr(self.child_fd, termios.TCSANOW, attr)
'This reads at most size characters from the child application. It includes a timeout. If the read does not complete within the timeout period then a TIMEOUT exception is raised. If the end of file is read then an EOF exception will be raised. If a log file was set using setlog() then all data will also be written to t...
def read_nonblocking(self, size=1, timeout=(-1)):
if self.closed: raise ValueError('I/O operation on closed file in read_nonblocking().') if (timeout == (-1)): timeout = self.timeout if (not self.isalive()): (r, w, e) = self.__select([self.child_fd], [], [], 0) if (not r): self.flag_eof = True ...
'This reads at most "size" bytes from the file (less if the read hits EOF before obtaining size bytes). If the size argument is negative or omitted, read all data until EOF is reached. The bytes are returned as a string object. An empty string is returned when EOF is encountered immediately.'
def read(self, size=(-1)):
if (size == 0): return '' if (size < 0): self.expect(self.delimiter) return self.before cre = re.compile(('.{%d}' % size), re.DOTALL) index = self.expect([cre, self.delimiter]) if (index == 0): return self.after return self.before
'This reads and returns one entire line. A trailing newline is kept in the string, but may be absent when a file ends with an incomplete line. Note: This readline() looks for a \r\n pair even on UNIX because this is what the pseudo tty device returns. So contrary to what you may expect you will receive the newline as \...
def readline(self, size=(-1)):
if (size == 0): return '' index = self.expect(['\r\n', self.delimiter]) if (index == 0): return (self.before + '\r\n') else: return self.before
'This is to support iterators over a file-like object.'
def __iter__(self):
return self
'This is to support iterators over a file-like object.'
def next(self):
result = self.readline() if (result == ''): raise StopIteration return result
'This reads until EOF using readline() and returns a list containing the lines thus read. The optional "sizehint" argument is ignored.'
def readlines(self, sizehint=(-1)):
lines = [] while True: line = self.readline() if (not line): break lines.append(line) return lines
'This is similar to send() except that there is no return value.'
def write(self, s):
self.send(s)
'This calls write() for each element in the sequence. The sequence can be any iterable object producing strings, typically a list of strings. This does not add line separators There is no return value.'
def writelines(self, sequence):
for s in sequence: self.write(s)