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) else: warning(('no random class for [%s] (fmt=%s).' % (self.name, self.fmt)))
'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() del q[fnb].payload del q[fnb].chksum del q[fnb].len if (i == (nb - 1)): q[IP].flags &= (~ 1) else: q[IP].flags |= 1 q[IP].frag = ((i * fragsize) / 8) r = Raw(load=s[(i * fragsize):((i + 1) * fragsize)]) r.overload_fields = p[IP].payload.overload_fields.copy() q.add_payload(r) lst.append(q) return lst
'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): if (self.label is not None): if (visible is None): visible = self.label.visible self.label.visible = 0 elif (visible is None): visible = 0 self.label = visual.label(text=txt, pos=self.pos, space=self.radius, xoffset=10, yoffset=20, visible=visible) def action(self): self.label.visible ^= 1 visual.scene = visual.display() visual.scene.exit_on_close(0) start = visual.box() rings = {} tr3d = {} for i in trace: tr = trace[i] tr3d[i] = [] ttl = tr.keys() for t in range(1, (max(ttl) + 1)): if (t not in rings): rings[t] = [] if (t in tr): if (tr[t] not in rings[t]): rings[t].append(tr[t]) tr3d[i].append(rings[t].index(tr[t])) else: rings[t].append(('unk', (-1))) tr3d[i].append((len(rings[t]) - 1)) for t in rings: r = rings[t] l = len(r) for i in range(l): if (r[i][1] == (-1)): col = (0.75, 0.75, 0.75) elif r[i][1]: col = visual.color.green else: col = visual.color.blue s = IPsphere(pos=(((l - 1) * visual.cos((((2 * i) * visual.pi) / l))), ((l - 1) * visual.sin((((2 * i) * visual.pi) / l))), (2 * t)), ip=r[i][0], color=col) for trlst in tr3d.values(): if (t <= len(trlst)): if (trlst[(t - 1)] == i): trlst[(t - 1)] = s forecol = colgen(0.625, 0.4375, 0.25, 0.125) for trlst in tr3d.values(): col = forecol.next() start = (0, 0, 0) for ip in trlst: visual.cylinder(pos=start, axis=(ip.pos - start), color=col, radius=0.2) start = ip.pos movcenter = None while 1: if visual.scene.kb.keys: k = visual.scene.kb.getkey() if ((k == 'esc') or (k == 'q')): break if visual.scene.mouse.events: ev = visual.scene.mouse.getevent() if (ev.press == 'left'): o = ev.pick if o: if ev.ctrl: if (o.ip == 'unk'): continue savcolor = o.color o.color = (1, 0, 0) (a, b) = sr((IP(dst=o.ip) / TCP(dport=[21, 22, 23, 25, 80, 443])), timeout=2) o.color = savcolor if (len(a) == 0): txt = ('%s:\nno results' % o.ip) else: txt = ('%s:\n' % o.ip) for (s, r) in a: txt += r.sprintf('{TCP:%IP.src%:%TCP.sport% %TCP.flags%}{TCPerror:%IPerror.dst%:%TCPerror.dport% %IP.src% %ir,ICMP.type%}\n') o.setlabel(txt, visible=1) elif hasattr(o, 'action'): o.action() elif (ev.drag == 'left'): movcenter = ev.pos elif (ev.drop == 'left'): movcenter = None if movcenter: visual.scene.center -= (visual.scene.mouse.pos - movcenter) movcenter = visual.scene.mouse.pos
'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.), passed to dot\'s "-T" option target: filename or redirect. Defaults pipe to Imagemagick\'s display program prog: which graphviz program to use'
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 required padding length.'
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 key modulus. Output: ciphertext representative, a long between 0 and n-1 Not intended to be used directly. Please, see encrypt() method.'
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 = pkcs_os2ip(EM) c = self._rsaep(m) C = pkcs_i2osp(c, k) return C
'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 hLen the length in octets of the hash function output) h : hash function name (in \'md2\', \'md4\', \'md5\', \'sha1\', \'tls\', \'sha256\', \'sha384\'). hLen denotes the length in octets of the hash function output. \'sha1\' is used by default if not provided. mgf: the mask generation function f : seed, maskLen -> mask L : optional label to be associated with the message; the default value for L, if not provided is the empty string Output: ciphertext, an octet string of length k On error, None is returned.'
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 - (2 * hLen)) - 2)): warning('Key._rsaes_oaep_encrypt(): message too long.') return None if (L is None): L = '' lHash = hFun(L) PS = ('\x00' * (((k - mLen) - (2 * hLen)) - 2)) DB = (((lHash + PS) + '\x01') + M) seed = randstring(hLen) if (mgf is None): mgf = (lambda x, y: pkcs_mgf1(x, y, h)) dbMask = mgf(seed, ((k - hLen) - 1)) maskedDB = strxor(DB, dbMask) seedMask = mgf(maskedDB, hLen) maskedSeed = strxor(seed, seedMask) EM = (('\x00' + maskedSeed) + maskedDB) m = pkcs_os2ip(EM) c = self._rsaep(m) C = pkcs_i2osp(c, k) return C
'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 just ignored. - \'pkcs\': the message \'m\' is applied RSAES-PKCS1-V1_5-ENCRYPT encryption scheme as described in section 7.2.1 of RFC 3447. In that context, other parameters (\'h\', \'mgf\', \'l\') are not used. - \'oaep\': the message \'m\' is applied the RSAES-OAEP-ENCRYPT encryption scheme, as described in PKCS#1 v2.1, i.e. RFC 3447 Sect 7.1.1. In that context, o \'h\' parameter provides the name of the hash method to use. Possible values are "md2", "md4", "md5", "sha1", "tls", "sha224", "sha256", "sha384" and "sha512". if none is provided, sha1 is used. o \'mgf\' is the mask generation function. By default, mgf is derived from the provided hash function using the generic MGF1 (see pkcs_mgf1() for details). o \'L\' is the optional label to be associated with the message. If not provided, the default value is used, i.e the empty string. No check is done on the input limitation of the hash function regarding the size of \'L\' (for instance, 2^61 - 1 for SHA-1). You have been warned.'
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(): Unknown encryption type (%s) provided' % t)) return None
'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 and n-1, where n is the key modulus. Output: message representative, an integer between 0 and n-1 Not intended to be used directly. Please, see verify() method.'
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 = _hashFuncParams[h][0] sLen = hLen modBits = self.modulusLen k = (modBits / 8) if (len(S) != k): return False s = pkcs_os2ip(S) m = self._rsavp1(s) emLen = math.ceil(((modBits - 1) / 8.0)) EM = pkcs_i2osp(m, emLen) Result = pkcs_emsa_pss_verify(M, EM, (modBits - 1), h, mgf, sLen) return Result
'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\', \'sha1\', \'tls\', \'sha256\', \'sha384\'). Output: True if the signature is valid. False otherwise.'
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_v1_5_verify(): unable to encode.') return False return (EM == EMPrime)
'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 exponentiation using the public key. Then, a comparison of the result is done against \'M\'. On match, True is returned. Additionnal method parameters are just ignored. - \'pkcs\': the alleged signature \'S\' and message \'M\' are applied RSASSA-PKCS1-v1_5-VERIFY signature verification scheme as described in Sect. 8.2.2 of RFC 3447. In that context, the hash function name is passed using \'h\'. Possible values are "md2", "md4", "md5", "sha1", "tls", "sha224", "sha256", "sha384" and "sha512". If none is provided, sha1 is used. Other additionnal parameters are ignored. - \'pss\': the alleged signature \'S\' and message \'M\' are applied RSASSA-PSS-VERIFY signature scheme as described in Sect. 8.1.2. of RFC 3447. In that context, o \'h\' parameter provides the name of the hash method to use. Possible values are "md2", "md4", "md5", "sha1", "tls", "sha224", "sha256", "sha384" and "sha512". if none is provided, sha1 is used. o \'mgf\' is the mask generation function. By default, mgf is derived from the provided hash function using the generic MGF1 (see pkcs_mgf1() for details). o \'sLen\' is the length in octet of the salt. You can overload the default value (the octet length of the hash value for provided algorithm) by providing another one with that parameter.'
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(math.ceil((math.log(m, 2) / 8.0))) m = pkcs_i2osp(m, l) return (M == m) elif (t == 'pkcs'): if (h is None): h = 'sha1' return self._rsassa_pkcs1_v1_5_verify(M, S, h) elif (t == 'pss'): return self._rsassa_pss_verify(M, S, h, mgf, sLen) else: warning(('Key.verify(): Unknown signature type (%s) provided' % t)) return None
'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 the key modulus. Output: ciphertext representative, a long between 0 and n-1 Not intended to be used directly. Please, see encrypt() method.'
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'): warning('Key._rsaes_pkcs1_v1_5_decrypt(): decryption error (first byte is not 0x00)') return None if (EM[1] != '\x02'): warning('Key._rsaes_pkcs1_v1_5_decrypt(): decryption error (second byte is not 0x02)') return None tmp = EM[2:].split('\x00', 1) if (len(tmp) != 2): warning('Key._rsaes_pkcs1_v1_5_decrypt(): decryption error (no 0x00 to separate PS from M)') return None (PS, M) = tmp if (len(PS) < 8): warning('Key._rsaes_pkcs1_v1_5_decrypt(): decryption error (PS is less than 8 byte long)') return None return M
'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 length in octets of the hash function output) h : hash function name (in \'md2\', \'md4\', \'md5\', \'sha1\', \'tls\', \'sha256\', \'sha384\'). \'sha1\' is used if none is provided. mgf: the mask generation function f : seed, maskLen -> mask L : optional label whose association with the message is to be verified; the default value for L, if not provided is the empty string. Output: message, an octet string of length k mLen, where mLen <= k - 2*hLen - 2 On error, None is returned.'
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): warning('Key._rsaes_oaep_decrypt(): decryption error. (cLen != k)') return None if (k < ((2 * hLen) + 2)): warning('Key._rsaes_oaep_decrypt(): decryption error. (k < 2*hLen + 2)') return None c = pkcs_os2ip(C) m = self._rsadp(c) EM = pkcs_i2osp(m, k) if (L is None): L = '' lHash = hFun(L) Y = EM[:1] if (Y != '\x00'): warning('Key._rsaes_oaep_decrypt(): decryption error. (Y is not zero)') return None maskedSeed = EM[1:(1 + hLen)] maskedDB = EM[(1 + hLen):] if (mgf is None): mgf = (lambda x, y: pkcs_mgf1(x, y, h)) seedMask = mgf(maskedDB, hLen) seed = strxor(maskedSeed, seedMask) dbMask = mgf(seed, ((k - hLen) - 1)) DB = strxor(maskedDB, dbMask) lHashPrime = DB[:hLen] tmp = DB[hLen:].split('\x01', 1) if (len(tmp) != 2): warning('Key._rsaes_oaep_decrypt(): decryption error. (0x01 separator not found)') return None (PS, M) = tmp if (PS != ('\x00' * len(PS))): warning('Key._rsaes_oaep_decrypt(): decryption error. (invalid padding string)') return None if (lHash != lHashPrime): warning('Key._rsaes_oaep_decrypt(): decryption error. (invalid hash)') return None return M
'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 parameters are just ignored. - \'pkcs\': the ciphertext \'C\' is applied RSAES-PKCS1-V1_5-DECRYPT decryption scheme as described in section 7.2.2 of RFC 3447. In that context, other parameters (\'h\', \'mgf\', \'l\') are not used. - \'oaep\': the ciphertext \'C\' is applied the RSAES-OAEP-DECRYPT decryption scheme, as described in PKCS#1 v2.1, i.e. RFC 3447 Sect 7.1.2. In that context, o \'h\' parameter provides the name of the hash method to use. Possible values are "md2", "md4", "md5", "sha1", "tls", "sha224", "sha256", "sha384" and "sha512". if none is provided, sha1 is used by default. o \'mgf\' is the mask generation function. By default, mgf is derived from the provided hash function using the generic MGF1 (see pkcs_mgf1() for details). o \'L\' is the optional label to be associated with the message. If not provided, the default value is used, i.e the empty string. No check is done on the input limitation of the hash function regarding the size of \'L\' (for instance, 2^61 - 1 for SHA-1). You have been warned.'
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: warning(('Key.decrypt(): Unknown decryption type (%s) provided' % t)) return None
'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 the key modulus. Output: signature representative, an integer between 0 and n-1 Not intended to be used directly. Please, see sign() method.'
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 = _hashFuncParams[h][0] sLen = hLen modBits = self.modulusLen k = (modBits / 8) EM = pkcs_emsa_pss_encode(M, (modBits - 1), h, mgf, sLen) if (EM is None): warning('Key._rsassa_pss_sign(): unable to encode') return None m = pkcs_os2ip(EM) s = self._rsasp1(m) S = pkcs_i2osp(s, k) return S
'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 ignored. - \'pkcs\': the message \'M\' is applied RSASSA-PKCS1-v1_5-SIGN signature scheme as described in Sect. 8.2.1 of RFC 3447. In that context, the hash function name is passed using \'h\'. Possible values are "md2", "md4", "md5", "sha1", "tls", "sha224", "sha256", "sha384" and "sha512". If none is provided, sha1 is used. Other additionnal parameters are ignored. - \'pss\' : the message \'M\' is applied RSASSA-PSS-SIGN signature scheme as described in Sect. 8.1.1. of RFC 3447. In that context, o \'h\' parameter provides the name of the hash method to use. Possible values are "md2", "md4", "md5", "sha1", "tls", "sha224", "sha256", "sha384" and "sha512". if none is provided, sha1 is used. o \'mgf\' is the mask generation function. By default, mgf is derived from the provided hash function using the generic MGF1 (see pkcs_mgf1() for details). o \'sLen\' is the length in octet of the salt. You can overload the default value (the octet length of the hash value for provided algorithm) by providing another one with that parameter.'
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_i2osp(s, (self.modulusLen / 8)) elif (t == 'pkcs'): if (h is None): h = 'sha1' return self._rsassa_pkcs1_v1_5_sign(M, h) elif (t == 'pss'): return self._rsassa_pss_sign(M, h, mgf, sLen) else: warning(('Key.sign(): Unknown signature type (%s) provided' % t)) return None
'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 + 1):] found = None for k in _hashFuncParams.keys(): if self.sigAlg.startswith(k): found = k break if (not found): return False (hlen, hfunc, digestInfo) = _hashFuncParams[k] if (len(unenc) != (hlen + len(digestInfo))): return False if (not unenc.startswith(digestInfo)): return False h = unenc[(- hlen):] myh = hfunc(self.tbsCertificate) return (h == myh)
'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 certificate of the returned chain is self signed (if c is the result, c[-1].isSelfSigned())'
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 = possible_issuer else: break return res
'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 representing the date. Accepted format for the string version are: - \'%b %d %H:%M:%S %Y %Z\' e.g. \'Jan 30 07:38:59 2008 GMT\' - \'%m/%d/%y\' e.g. \'01/30/08\' (less precise) If the certificate is no more valid at the date considered, then, a negative value is returned representing the number of days since it has expired. The number of days is returned as a float to deal with the unlikely case of certificates that are still just valid.'
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 time string provided '%s'. Using current time" % now)) now = time.localtime() now = time.mktime(now) nft = time.mktime(self.notAfter) diff = ((nft - now) / (24.0 * 3600)) return diff
'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. If you have a lot of certificates to verify against the same list of anchor, consider constructing this list as a cafile and use .verifychain_from_cafile() instead.'
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(cafile, untrusted_file=untrusted_file) os.unlink(cafile) if untrusted_file: os.unlink(untrusted_file) return res
'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 a file, this time)'
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.endswith('\nOK\n') or cmdres.endswith(': OK\n'))
'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 file (concatenation of the certificates in PEM format)'
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.endswith('\nOK\n') or cmdres.endswith(': OK\n'))
'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 considered revoked: this is because _all_ CRLs are checked (not only the freshest) and revocation status is not handled. Also note that the check on the issuer is performed on the Authority Key Identifier if available in _both_ the CRL and the Cert. Otherwise, the issuers are simply compared.'
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 x: x[0]), c.revoked_cert_serials)) return False
'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) return ('verify OK' in cmdres)
'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_candidate_set(prefix, plen, devaddrs, LOOPBACK_NAME) return (prefix, plen, gw, dev, ifaddr)
'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): warning('No matching route found') elif (len(l) > 1): warning('Found more than one match. Aborting.') else: i = self.routes.index(l[0]) self.invalidate_cache() del self.routes[i]
'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. In that case, a value of 128 will be used.'
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 performed and result is used. if optional \'dev\' parameter is provided a specific interface, filtering is performed to limit search to route associated to that interface.'
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.getaddrinfo(savedst, None, socket.AF_INET6)[0][(-1)][0] k = dst if (dev is not None): k = ((dst + '%%') + dev) if (k in self.cache): return self.cache[k] pathes = [] for (p, plen, gw, iface, cset) in self.routes: if ((dev is not None) and (iface != dev)): continue if in6_isincluded(dst, p, plen): pathes.append((plen, (iface, cset, gw))) elif (in6_ismlladdr(dst) and in6_islladdr(p) and in6_islladdr(cset[0])): pathes.append((plen, (iface, cset, gw))) if (not pathes): warning(('No route found for IPv6 destination %s (no default route?)' % dst)) return (LOOPBACK_NAME, '::', '::') pathes.sort(reverse=True) best_plen = pathes[0][0] pathes = filter((lambda x: (x[0] == best_plen)), pathes) res = [] for p in pathes: tmp = p[1] srcaddr = get_source_addr_from_candidate_set(dst, p[1][1]) if (srcaddr is not None): res.append((p[0], (tmp[0], srcaddr, tmp[2]))) if (len(res) > 1): tmp = [] if (in6_isgladdr(dst) and in6_isaddr6to4(dst)): tmp = filter((lambda x: in6_isaddr6to4(x[1][1])), res) elif (in6_ismaddr(dst) or in6_islladdr(dst)): tmp = filter((lambda x: (x[1][0] == conf.iface6)), res) if tmp: res = tmp k = dst if (dev is not None): k = ((dst + '%%') + dev) self.cache[k] = res[0][1] return res[0][1]
'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\\Interfaces\\%s' % uuid) try: key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, keyname) except WindowsError: log_loading.debug(("Couldn't open 'HKEY_LOCAL_MACHINE\\%s' (for guessed pcap iface name '%s')." % (keyname, guess))) continue try: fixed_ip = _winreg.QueryValueEx(key, 'IPAddress')[0][0].encode('utf-8') except (WindowsError, UnicodeDecodeError, IndexError): fixed_ip = None try: dhcp_ip = _winreg.QueryValueEx(key, 'DhcpIPAddress')[0].encode('utf-8') except (WindowsError, UnicodeDecodeError, IndexError): dhcp_ip = None if ((fixed_ip is not None) and (fixed_ip != '0.0.0.0')): ip = fixed_ip elif ((dhcp_ip is not None) and (dhcp_ip != '0.0.0.0')): ip = dhcp_ip else: continue except IOError: continue else: if (ip == self.ip): self.pcap_name = guess self.win_name = win_name self.uuid = uuid break else: raise PcapNameNotFoundError
'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 your pcap and dnet network interfaces found. You probably won't be able to send packets. Deactivating unneeded interfaces and restarting Scapy might help.")
'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).ljust(5), str(dev.ip).ljust(15), mac))
'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_fields.copy() clone.underlayer = self.underlayer clone.explicit = self.explicit clone.post_transforms = self.post_transforms[:] clone.__dict__['payload'] = self.payload.copy() clone.payload.add_underlayer(clone) return clone
'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 self.default_payload_class(payload)
'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 fvalue in fvalue_gen: if isinstance(fvalue, Packet): ret = fvalue.haslayer(cls) if ret: return ret return self.payload.haslayer(cls)
'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 (fld is None): return self else: return self.getfieldval(fld) else: nb -= 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 fvalue in fvalue_gen: if isinstance(fvalue, Packet): track = [] ret = fvalue.getlayer(cls, nb, _track=track) if (ret is not None): return ret nb = track[0] return self.payload.getlayer(cls, nb, _track=_track)
'"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)): ncol = ct.emph_field_name vcol = ct.emph_field_value else: ncol = ct.field_name vcol = ct.field_value fvalue = self.getfieldval(f.name) if (isinstance(fvalue, Packet) or (f.islist and f.holds_packets and (type(fvalue) is list))): print ('%s \\%-10s\\' % ((label_lvl + lvl), ncol(f.name))) fvalue_gen = SetGen(fvalue, _iterpacket=0) for fvalue in fvalue_gen: fvalue.show(indent=indent, label_lvl=((label_lvl + lvl) + ' |')) else: print ('%s %-10s%s %s' % ((label_lvl + lvl), ncol(f.name), ct.punct('='), vcol(f.i2repr(self, fvalue)))) self.payload.show(indent=indent, lvl=(lvl + ((' ' * indent) * self.show_indent)), label_lvl=label_lvl)
'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 we want (ex: for IP/IP packets, IP:2.src is the src of the upper IP layer). Special case : "%.time%" is the creation time. Ex : p.sprintf("%.time% %-15s,IP.src% -> %-15s,IP.dst% %IP.chksum% " "%03xr,IP.proto% %r,TCP.flags%") Moreover, the format string can include conditionnal statements. A conditionnal statement looks like : {layer:string} where layer is a layer name, and string is the string to insert in place of the condition if it is true, i.e. if layer is present. If layer is preceded by a "!", the result si inverted. Conditions can be imbricated. A valid statement can be : p.sprintf("This is a{TCP: TCP}{UDP: UDP}{ICMP:n ICMP} packet") p.sprintf("{IP:%IP.dst% {ICMP:%ICMP.type%}{TCP:%TCP.dport%}}") A side effect is that, to obtain "{" and "}" characters, you must use "%(" and "%)".'
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 sprintf doc!)' % cond)) (cond, format) = (cond[:k], cond[(k + 1):]) res = False if (cond[0] == '!'): res = True cond = cond[1:] if self.haslayer(cond): res = (not res) if (not res): format = '' fmt = ((fmt[:i] + format) + fmt[((i + j) + 2):]) s = '' while ('%' in fmt): i = fmt.index('%') s += fmt[:i] fmt = fmt[(i + 1):] if (fmt and (fmt[0] in escape)): s += escape[fmt[0]] fmt = fmt[1:] continue try: i = fmt.index('%') sfclsfld = fmt[:i] fclsfld = sfclsfld.split(',') if (len(fclsfld) == 1): f = 's' clsfld = fclsfld[0] elif (len(fclsfld) == 2): (f, clsfld) = fclsfld else: raise Scapy_Exception if ('.' in clsfld): (cls, fld) = clsfld.split('.') else: cls = self.__class__.__name__ fld = clsfld num = 1 if (':' in cls): (cls, num) = cls.split(':') num = int(num) fmt = fmt[(i + 1):] except: raise Scapy_Exception(('Bad format string [%%%s%s]' % (fmt[:25], (fmt[25:] and '...')))) else: if (fld == 'time'): val = (time.strftime('%H:%M:%S.%%06i', time.localtime(self.time)) % int(((self.time - int(self.time)) * 1000000))) elif ((cls == self.__class__.__name__) and hasattr(self, fld)): if (num > 1): val = self.payload.sprintf(('%%%s,%s:%s.%s%%' % (f, cls, (num - 1), fld)), relax) f = 's' elif (f[(-1)] == 'r'): val = getattr(self, fld) f = f[:(-1)] if (not f): f = 's' else: val = getattr(self, fld) if (fld in self.fieldtype): val = self.fieldtype[fld].i2repr(self, val) else: val = self.payload.sprintf(('%%%s%%' % sfclsfld), relax) f = 's' s += (('%' + f) % val) s += fmt return s
'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(val)) print (' DCTB %s, DCTB DCTB /* %s */' % (val, f.name)) print ');'
'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(fv) f.append(('%s=%s' % (fn, fv))) c = ('%s(%s)' % (self.__class__.__name__, ', '.join(f))) pc = self.payload.command() if pc: c += ('/' + pc) return c
'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 [email protected]\') child = pexpect.spawn (\'ls -latr /tmp\') You may also construct it with a list of arguments like so:: child = pexpect.spawn (\'/usr/bin/ftp\', []) child = pexpect.spawn (\'/usr/bin/ssh\', [\'[email protected]\']) child = pexpect.spawn (\'ls\', [\'-latr\', \'/tmp\']) After this the child application will be created and will be ready to talk to. For normal use, see expect() and send() and sendline(). Remember that Pexpect does NOT interpret shell meta characters such as redirect, pipe, or wild cards (>, |, or *). This is a common mistake. If you want to run a command and pipe it through another command then you must also start a shell. For example:: child = pexpect.spawn(\'/bin/bash -c "ls -l | grep LOG > log_list.txt"\') child.expect(pexpect.EOF) The second form of spawn (where you pass a list of arguments) is useful in situations where you wish to spawn a command and pass it its own argument list. This can make syntax more clear. For example, the following is equivalent to the previous example:: shell_cmd = \'ls -l | grep LOG > log_list.txt\' child = pexpect.spawn(\'/bin/bash\', [\'-c\', shell_cmd]) child.expect(pexpect.EOF) The maxread attribute sets the read buffer size. This is maximum number of bytes that Pexpect will try to read from a TTY at one time. Setting the maxread size to 1 will turn off buffering. Setting the maxread value higher may help performance in cases where large amounts of output are read back from the child. This feature is useful in conjunction with searchwindowsize. The searchwindowsize attribute sets the how far back in the incomming seach buffer Pexpect will search for pattern matches. Every time Pexpect reads some data from the child it will append the data to the incomming buffer. The default is to search from the beginning of the imcomming buffer each time new data is read from the child. But this is very inefficient if you are running a command that generates a large amount of data where you want to match The searchwindowsize does not effect the size of the incomming data buffer. You will still have access to the full buffer after expect() returns. The logfile member turns on or off logging. All input and output will be copied to the given file object. Set logfile to None to stop logging. This is the default. Set logfile to sys.stdout to echo everything to standard output. The logfile is flushed after each write. Example log input and output to a file:: child = pexpect.spawn(\'some_command\') fout = file(\'mylog.txt\',\'w\') child.logfile = fout Example log to stdout:: child = pexpect.spawn(\'some_command\') child.logfile = sys.stdout The logfile_read and logfile_send members can be used to separately log the input from the child and output sent to the child. Sometimes you don\'t want to see everything you write to the child. You only want to log what the child sends back. For example:: child = pexpect.spawn(\'some_command\') child.logfile_read = sys.stdout To separately log output sent to the child use logfile_send:: self.logfile_send = fout The delaybeforesend helps overcome a weird behavior that many users were experiencing. The typical problem was that a user would expect() a "Password:" prompt and then immediately call sendline() to send the password. The user would then see that their password was echoed back to them. Passwords don\'t normally echo. The problem is caused by the fact that most applications print out the "Password" prompt and then turn off stdin echo, but if you send your password before the application turned off echo, then you get your password echoed. Normally this wouldn\'t be a problem when interacting with a human at a real keyboard. If you introduce a slight delay just before writing then this seems to clear up the problem. This was such a common problem for many users that I decided that the default pexpect behavior should be to sleep just before writing to the child application. 1/20th of a second (50 ms) seems to be enough to clear up the problem. You can set delaybeforesend to 0 to return to the old behavior. Most Linux machines don\'t like this to be below 0.03. I don\'t know why. Note that spawn is clever about finding commands on your path. It uses the same logic that "which" uses to find executables. If you wish to get the exit status of the child you must call the close() method. The exit or signal status of the child will be stored in self.exitstatus or self.signalstatus. If the child exited normally then exitstatus will store the exit return code and signalstatus will be None. If the child was terminated abnormally with a signal then signalstatus will store the signal value and exitstatus will be None. If you need more detail you can also read the self.status member which stores the status returned by os.waitpid. You can interpret this using os.WIFEXITED/os.WEXITSTATUS or os.WIFSIGNALED/os.TERMSIG.'
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.match = None self.match_index = None self.terminated = True self.exitstatus = None self.signalstatus = None self.status = None self.flag_eof = False self.pid = None self.child_fd = (-1) self.timeout = timeout self.delimiter = EOF self.logfile = logfile self.logfile_read = None self.logfile_send = None self.maxread = maxread self.buffer = '' self.searchwindowsize = searchwindowsize self.delaybeforesend = 0.05 self.delayafterclose = 0.1 self.delayafterterminate = 0.1 self.softspace = False self.name = (('<' + repr(self)) + '>') self.encoding = None self.closed = True self.cwd = cwd self.env = env self.__irix_hack = (sys.platform.lower().find('irix') >= 0) if ((sys.platform.lower().find('solaris') >= 0) or (sys.platform.lower().find('sunos5') >= 0)): self.use_native_pty_fork = False else: self.use_native_pty_fork = True if (command is None): self.command = None self.args = None self.name = '<pexpect factory incomplete>' else: self._spawn(command, args)
'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): ' + str(self.buffer)[(-100):])) s.append(('before (last 100 chars): ' + str(self.before)[(-100):])) s.append(('after: ' + str(self.after))) s.append(('match: ' + str(self.match))) s.append(('match_index: ' + str(self.match_index))) s.append(('exitstatus: ' + str(self.exitstatus))) s.append(('flag_eof: ' + str(self.flag_eof))) s.append(('pid: ' + str(self.pid))) s.append(('child_fd: ' + str(self.child_fd))) s.append(('closed: ' + str(self.closed))) s.append(('timeout: ' + str(self.timeout))) s.append(('delimiter: ' + str(self.delimiter))) s.append(('logfile: ' + str(self.logfile))) s.append(('logfile_read: ' + str(self.logfile_read))) s.append(('logfile_send: ' + str(self.logfile_send))) s.append(('maxread: ' + str(self.maxread))) s.append(('ignorecase: ' + str(self.ignorecase))) s.append(('searchwindowsize: ' + str(self.searchwindowsize))) s.append(('delaybeforesend: ' + str(self.delaybeforesend))) s.append(('delayafterclose: ' + str(self.delayafterclose))) s.append(('delayafterterminate: ' + str(self.delayafterterminate))) return '\n'.join(s)
'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.') if (type(args) != type([])): raise TypeError('The argument, args, must be a list.') if (args == []): self.args = split_command_line(command) self.command = self.args[0] else: self.args = args[:] self.args.insert(0, command) self.command = command command_with_path = which(self.command) if (command_with_path is None): raise ExceptionPexpect(('The command was not found or was not executable: %s.' % self.command)) self.command = command_with_path self.args[0] = self.command self.name = (('<' + ' '.join(self.args)) + '>') assert (self.pid is None), 'The pid member should be None.' assert (self.command is not None), 'The command member should not be None.' if self.use_native_pty_fork: try: (self.pid, self.child_fd) = pty.fork() except OSError as e: raise ExceptionPexpect(('Error! pty.fork() failed: ' + str(e))) else: (self.pid, self.child_fd) = self.__fork_pty() if (self.pid == 0): try: self.child_fd = sys.stdout.fileno() self.setwinsize(24, 80) except: pass max_fd = resource.getrlimit(resource.RLIMIT_NOFILE)[0] for i in range(3, max_fd): try: os.close(i) except OSError: pass signal.signal(signal.SIGHUP, signal.SIG_IGN) if (self.cwd is not None): os.chdir(self.cwd) if (self.env is None): os.execv(self.command, self.args) else: os.execvpe(self.command, self.args, self.env) self.terminated = False self.closed = False
'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. Based on patch to posixmodule.c authored by Noah Spurrier:: http://mail.python.org/pipermail/python-dev/2003-May/035281.html'
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.close(parent_fd) self.__pty_make_controlling_tty(child_fd) os.dup2(child_fd, 0) os.dup2(child_fd, 1) os.dup2(child_fd, 2) if (child_fd > 2): os.close(child_fd) else: os.close(child_fd) return (pid, parent_fd)
'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 not disconnected from a controlling tty.' except: pass fd = os.open(child_name, os.O_RDWR) if (fd < 0): raise ExceptionPexpect, ('Error! Could not open child pty, ' + child_name) else: os.close(fd) fd = os.open('/dev/tty', os.O_WRONLY) if (fd < 0): raise ExceptionPexpect, 'Error! Could not open controlling tty, /dev/tty' else: os.close(fd)
'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()') self.child_fd = (-1) self.closed = True
'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 user to enter a password. For example, instead of expecting the "password:" prompt you can wait for the child to set ECHO off:: p = pexpect.spawn (\'ssh [email protected]\') p.waitnoecho() p.sendline(mypassword) If timeout is None then this method to block forever until ECHO flag is False.'
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): timeout = (end_time - time.time()) time.sleep(0.1)
'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 from tty echo and again from cat). p.expect ([\'1234\']) p.expect ([\'1234\']) p.setecho(False) # Turn off tty echo p.sendline (\'abcd\') # We will set this only once (echoed by cat). p.sendline (\'wxyz\') # We will set this only once (echoed by cat) p.expect ([\'abcd\']) p.expect ([\'wxyz\']) The following WILL NOT WORK because the lines sent before the setecho will be lost:: p = pexpect.spawn(\'cat\') p.sendline (\'1234\') # We will see this twice (once from tty echo and again from cat). p.setecho(False) # Turn off tty echo p.sendline (\'abcd\') # We will set this only once (echoed by cat). p.sendline (\'wxyz\') # We will set this only once (echoed by cat) p.expect ([\'1234\']) p.expect ([\'1234\']) p.expect ([\'abcd\']) p.expect ([\'wxyz\'])'
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 the log file. If timeout is None then the read may block indefinitely. If timeout is -1 then the self.timeout value is used. If timeout is 0 then the child is polled and if there was no data immediately ready then this will raise a TIMEOUT exception. The timeout refers only to the amount of time to read at least one character. This is not effected by the \'size\' parameter, so if you call read_nonblocking(size=100, timeout=30) and only one character is available right away then one character will be returned immediately. It will not wait for 30 seconds for another 99 characters to come in. This is a wrapper around os.read(). It uses select.select() to implement the timeout.'
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 raise EOF('End Of File (EOF) in read_nonblocking(). Braindead platform.') elif self.__irix_hack: (r, w, e) = self.__select([self.child_fd], [], [], 2) if ((not r) and (not self.isalive())): self.flag_eof = True raise EOF('End Of File (EOF) in read_nonblocking(). Pokey platform.') (r, w, e) = self.__select([self.child_fd], [], [], timeout) if (not r): if (not self.isalive()): self.flag_eof = True raise EOF('End of File (EOF) in read_nonblocking(). Very pokey platform.') else: raise TIMEOUT('Timeout exceeded in read_nonblocking().') if (self.child_fd in r): try: s = os.read(self.child_fd, size) except OSError as e: self.flag_eof = True raise EOF('End Of File (EOF) in read_nonblocking(). Exception style platform.') if (s == ''): self.flag_eof = True raise EOF('End Of File (EOF) in read_nonblocking(). Empty string style platform.') if (self.logfile is not None): self.logfile.write(s) self.logfile.flush() if (self.logfile_read is not None): self.logfile_read.write(s) self.logfile_read.flush() return s raise ExceptionPexpect('Reached an unexpected state in read_nonblocking().')
'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 \r\n. An empty string is returned when EOF is hit immediately. Currently, the size argument is mostly ignored, so this behavior is not standard for a file-like object. If size is 0 then an empty string is returned.'
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)