text_prompt
stringlengths 100
17.7k
⌀ | code_prompt
stringlengths 7
9.86k
⌀ |
---|---|
<SYSTEM_TASK:>
Initialize each fields of the fields_desc dict, or use the cached
<END_TASK>
<USER_TASK:>
Description:
def do_init_cached_fields(self):
"""
Initialize each fields of the fields_desc dict, or use the cached
fields information
""" |
cls_name = self.__class__
# Build the fields information
if Packet.class_default_fields.get(cls_name, None) is None:
self.prepare_cached_fields(self.fields_desc)
# Use fields information from cache
if not Packet.class_default_fields.get(cls_name, None) is None:
self.default_fields = Packet.class_default_fields[cls_name]
self.fieldtype = Packet.class_fieldtype[cls_name]
self.packetfields = Packet.class_packetfields[cls_name]
# Deepcopy default references
for fname in Packet.class_default_fields_ref[cls_name]:
value = copy.deepcopy(self.default_fields[fname])
setattr(self, fname, value) |
<SYSTEM_TASK:>
Prepare the cached fields of the fields_desc dict
<END_TASK>
<USER_TASK:>
Description:
def prepare_cached_fields(self, flist):
"""
Prepare the cached fields of the fields_desc dict
""" |
cls_name = self.__class__
# Fields cache initialization
if flist:
Packet.class_default_fields[cls_name] = dict()
Packet.class_default_fields_ref[cls_name] = list()
Packet.class_fieldtype[cls_name] = dict()
Packet.class_packetfields[cls_name] = list()
# Fields initialization
for f in flist:
if isinstance(f, MultipleTypeField):
del Packet.class_default_fields[cls_name]
del Packet.class_default_fields_ref[cls_name]
del Packet.class_fieldtype[cls_name]
del Packet.class_packetfields[cls_name]
self.class_dont_cache[cls_name] = True
self.do_init_fields(self.fields_desc)
break
tmp_copy = copy.deepcopy(f.default)
Packet.class_default_fields[cls_name][f.name] = tmp_copy
Packet.class_fieldtype[cls_name][f.name] = f
if f.holds_packets:
Packet.class_packetfields[cls_name].append(f)
# Remember references
if isinstance(f.default, (list, dict, set, RandField, Packet)):
Packet.class_default_fields_ref[cls_name].append(f.name) |
<SYSTEM_TASK:>
Return a list of slots and methods, including those from subclasses.
<END_TASK>
<USER_TASK:>
Description:
def _superdir(self):
"""
Return a list of slots and methods, including those from subclasses.
""" |
attrs = set()
cls = self.__class__
if hasattr(cls, '__all_slots__'):
attrs.update(cls.__all_slots__)
for bcls in cls.__mro__:
if hasattr(bcls, '__dict__'):
attrs.update(bcls.__dict__)
return attrs |
<SYSTEM_TASK:>
Clear the raw packet cache for the field and all its subfields
<END_TASK>
<USER_TASK:>
Description:
def clear_cache(self):
"""Clear the raw packet cache for the field and all its subfields""" |
self.raw_packet_cache = None
for _, fval in six.iteritems(self.fields):
if isinstance(fval, Packet):
fval.clear_cache()
self.payload.clear_cache() |
<SYSTEM_TASK:>
Create the default layer regarding fields_desc dict
<END_TASK>
<USER_TASK:>
Description:
def self_build(self, field_pos_list=None):
"""
Create the default layer regarding fields_desc dict
:param field_pos_list:
""" |
if self.raw_packet_cache is not None:
for fname, fval in six.iteritems(self.raw_packet_cache_fields):
if self.getfieldval(fname) != fval:
self.raw_packet_cache = None
self.raw_packet_cache_fields = None
self.wirelen = None
break
if self.raw_packet_cache is not None:
return self.raw_packet_cache
p = b""
for f in self.fields_desc:
val = self.getfieldval(f.name)
if isinstance(val, RawVal):
sval = raw(val)
p += sval
if field_pos_list is not None:
field_pos_list.append((f.name, sval.encode("string_escape"), len(p), len(sval))) # noqa: E501
else:
p = f.addfield(self, p, val)
return p |
<SYSTEM_TASK:>
Create the default version of the layer
<END_TASK>
<USER_TASK:>
Description:
def do_build(self):
"""
Create the default version of the layer
:return: a string of the packet with the payload
""" |
if not self.explicit:
self = next(iter(self))
pkt = self.self_build()
for t in self.post_transforms:
pkt = t(pkt)
pay = self.do_build_payload()
if self.raw_packet_cache is None:
return self.post_build(pkt, pay)
else:
return pkt + pay |
<SYSTEM_TASK:>
Create the current layer
<END_TASK>
<USER_TASK:>
Description:
def build(self):
"""
Create the current layer
:return: string of the packet with the payload
""" |
p = self.do_build()
p += self.build_padding()
p = self.build_done(p)
return p |
<SYSTEM_TASK:>
Perform the dissection of the layer's payload
<END_TASK>
<USER_TASK:>
Description:
def do_dissect_payload(self, s):
"""
Perform the dissection of the layer's payload
:param str s: the raw layer
""" |
if s:
cls = self.guess_payload_class(s)
try:
p = cls(s, _internal=1, _underlayer=self)
except KeyboardInterrupt:
raise
except Exception:
if conf.debug_dissector:
if issubtype(cls, Packet):
log_runtime.error("%s dissector failed" % cls.__name__)
else:
log_runtime.error("%s.guess_payload_class() returned [%s]" % (self.__class__.__name__, repr(cls))) # noqa: E501
if cls is not None:
raise
p = conf.raw_layer(s, _internal=1, _underlayer=self)
self.add_payload(p) |
<SYSTEM_TASK:>
Return the nb^th layer that is an instance of cls, matching flt
<END_TASK>
<USER_TASK:>
Description:
def getlayer(self, cls, nb=1, _track=None, _subclass=None, **flt):
"""Return the nb^th layer that is an instance of cls, matching flt
values.
""" |
if _subclass is None:
_subclass = self.match_subclass or None
if _subclass:
match = lambda cls1, cls2: issubclass(cls1, cls2)
else:
match = lambda cls1, cls2: cls1 == cls2
if isinstance(cls, int):
nb = cls + 1
cls = None
if isinstance(cls, str) and "." in cls:
ccls, fld = cls.split(".", 1)
else:
ccls, fld = cls, None
if cls is None or match(self.__class__, cls) \
or ccls in [self.__class__.__name__, self._name]:
if all(self.getfieldval(fldname) == fldvalue
for fldname, fldvalue in six.iteritems(flt)):
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=nb, _track=track,
_subclass=_subclass, **flt)
if ret is not None:
return ret
nb = track[0]
return self.payload.getlayer(cls, nb=nb, _track=_track,
_subclass=_subclass, **flt) |
<SYSTEM_TASK:>
Internal method that shows or dumps a hierarchical view of a packet.
<END_TASK>
<USER_TASK:>
Description:
def _show_or_dump(self, dump=False, indent=3, lvl="", label_lvl="", first_call=True): # noqa: E501
"""
Internal method that shows or dumps a hierarchical view of a packet.
Called by show.
:param dump: determine if it prints or returns the string value
:param int indent: the size of indentation for each layer
:param str lvl: additional information about the layer lvl
:param str label_lvl: additional information about the layer fields
:param first_call: determine if the current function is the first
:return: return a hierarchical view if dump, else print it
""" |
if dump:
from scapy.themes import AnsiColorTheme
ct = AnsiColorTheme() # No color for dump output
else:
ct = conf.color_theme
s = "%s%s %s %s \n" % (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 isinstance(fvalue, list)): # noqa: E501
s += "%s \\%-10s\\\n" % (label_lvl + lvl, ncol(f.name))
fvalue_gen = SetGen(fvalue, _iterpacket=0)
for fvalue in fvalue_gen:
s += fvalue._show_or_dump(dump=dump, indent=indent, label_lvl=label_lvl + lvl + " |", first_call=False) # noqa: E501
else:
begn = "%s %-10s%s " % (label_lvl + lvl,
ncol(f.name),
ct.punct("="),)
reprval = f.i2repr(self, fvalue)
if isinstance(reprval, str):
reprval = reprval.replace("\n", "\n" + " " * (len(label_lvl) + # noqa: E501
len(lvl) +
len(f.name) +
4))
s += "%s%s\n" % (begn, vcol(reprval))
if self.payload:
s += self.payload._show_or_dump(dump=dump, indent=indent, lvl=lvl + (" " * indent * self.show_indent), label_lvl=label_lvl, first_call=False) # noqa: E501
if first_call and not dump:
print(s)
else:
return s |
<SYSTEM_TASK:>
XXX We should offer the right key according to the client's suites. For
<END_TASK>
<USER_TASK:>
Description:
def INIT_TLS_SESSION(self):
"""
XXX We should offer the right key according to the client's suites. For
now server_rsa_key is only used for RSAkx, but we should try to replace
every server_key with both server_rsa_key and server_ecdsa_key.
""" |
self.cur_session = tlsSession(connection_end="server")
self.cur_session.server_certs = [self.mycert]
self.cur_session.server_key = self.mykey
if isinstance(self.mykey, PrivKeyRSA):
self.cur_session.server_rsa_key = self.mykey
# elif isinstance(self.mykey, PrivKeyECDSA):
# self.cur_session.server_ecdsa_key = self.mykey
raise self.WAITING_CLIENTFLIGHT1() |
<SYSTEM_TASK:>
We extract cipher suites candidates from the client's proposition.
<END_TASK>
<USER_TASK:>
Description:
def should_check_ciphersuites(self):
"""
We extract cipher suites candidates from the client's proposition.
""" |
if isinstance(self.mykey, PrivKeyRSA):
kx = "RSA"
elif isinstance(self.mykey, PrivKeyECDSA):
kx = "ECDSA"
if get_usable_ciphersuites(self.cur_pkt.ciphers, kx):
return
raise self.NO_USABLE_CIPHERSUITE() |
<SYSTEM_TASK:>
Selecting a cipher suite should be no trouble as we already caught
<END_TASK>
<USER_TASK:>
Description:
def should_add_ServerHello(self):
"""
Selecting a cipher suite should be no trouble as we already caught
the None case previously.
Also, we do not manage extensions at all.
""" |
if isinstance(self.mykey, PrivKeyRSA):
kx = "RSA"
elif isinstance(self.mykey, PrivKeyECDSA):
kx = "ECDSA"
usable_suites = get_usable_ciphersuites(self.cur_pkt.ciphers, kx)
c = usable_suites[0]
if self.preferred_ciphersuite in usable_suites:
c = self.preferred_ciphersuite
self.add_msg(TLSServerHello(cipher=c))
raise self.ADDED_SERVERHELLO() |
<SYSTEM_TASK:>
Compute and install the PMK
<END_TASK>
<USER_TASK:>
Description:
def install_PMK(self):
"""Compute and install the PMK""" |
self.pmk = PBKDF2HMAC(
algorithm=hashes.SHA1(),
length=32,
salt=self.ssid.encode(),
iterations=4096,
backend=default_backend(),
).derive(self.passphrase.encode()) |
<SYSTEM_TASK:>
Use the client nonce @client_nonce to compute and install
<END_TASK>
<USER_TASK:>
Description:
def install_unicast_keys(self, client_nonce):
"""Use the client nonce @client_nonce to compute and install
PTK, KCK, KEK, TK, MIC (AP -> STA), MIC (STA -> AP)
""" |
pmk = self.pmk
anonce = self.anonce
snonce = client_nonce
amac = mac2str(self.mac)
smac = mac2str(self.client)
# Compute PTK
self.ptk = customPRF512(pmk, amac, smac, anonce, snonce)
# Extract derivated keys
self.kck = self.ptk[:16]
self.kek = self.ptk[16:32]
self.tk = self.ptk[32:48]
self.mic_ap_to_sta = self.ptk[48:56]
self.mic_sta_to_ap = self.ptk[56:64]
# Reset IV
self.client_iv = count() |
<SYSTEM_TASK:>
Send an encrypted packet with content @data, using IV @iv,
<END_TASK>
<USER_TASK:>
Description:
def send_wpa_enc(self, data, iv, seqnum, dest, mic_key,
key_idx=0, additionnal_flag=["from-DS"],
encrypt_key=None):
"""Send an encrypted packet with content @data, using IV @iv,
sequence number @seqnum, MIC key @mic_key
""" |
if encrypt_key is None:
encrypt_key = self.tk
rep = RadioTap()
rep /= Dot11(
addr1=dest,
addr2=self.mac,
addr3=self.mac,
FCfield="+".join(['protected'] + additionnal_flag),
SC=(next(self.seq_num) << 4),
subtype=0,
type="Data",
)
# Assume packet is send by our AP -> use self.mac as source
# Encapsule in TKIP with MIC Michael and ICV
data_to_enc = build_MIC_ICV(raw(data), mic_key, self.mac, dest)
# Header TKIP + payload
rep /= Raw(build_TKIP_payload(data_to_enc, iv, self.mac, encrypt_key))
self.send(rep)
return rep |
<SYSTEM_TASK:>
Send an Ethernet packet using the WPA channel
<END_TASK>
<USER_TASK:>
Description:
def send_ether_over_wpa(self, pkt, **kwargs):
"""Send an Ethernet packet using the WPA channel
Extra arguments will be ignored, and are just left for compatibility
""" |
payload = LLC() / SNAP() / pkt[Ether].payload
dest = pkt.dst
if dest == "ff:ff:ff:ff:ff:ff":
self.send_wpa_to_group(payload, dest)
else:
assert dest == self.client
self.send_wpa_to_client(payload) |
<SYSTEM_TASK:>
If the next message to be processed has type 'pkt_cls', raise 'state'.
<END_TASK>
<USER_TASK:>
Description:
def raise_on_packet(self, pkt_cls, state, get_next_msg=True):
"""
If the next message to be processed has type 'pkt_cls', raise 'state'.
If there is no message waiting to be processed, we try to get one with
the default 'get_next_msg' parameters.
""" |
# Maybe we already parsed the expected packet, maybe not.
if get_next_msg:
self.get_next_msg()
if (not self.buffer_in or
not isinstance(self.buffer_in[0], pkt_cls)):
return
self.cur_pkt = self.buffer_in[0]
self.buffer_in = self.buffer_in[1:]
raise state() |
<SYSTEM_TASK:>
Add a new TLS or SSLv2 or TLS 1.3 record to the packets buffered out.
<END_TASK>
<USER_TASK:>
Description:
def add_record(self, is_sslv2=None, is_tls13=None):
"""
Add a new TLS or SSLv2 or TLS 1.3 record to the packets buffered out.
""" |
if is_sslv2 is None and is_tls13 is None:
v = (self.cur_session.tls_version or
self.cur_session.advertised_tls_version)
if v in [0x0200, 0x0002]:
is_sslv2 = True
elif v >= 0x0304:
is_tls13 = True
if is_sslv2:
self.buffer_out.append(SSLv2(tls_session=self.cur_session))
elif is_tls13:
self.buffer_out.append(TLS13(tls_session=self.cur_session))
else:
self.buffer_out.append(TLS(tls_session=self.cur_session)) |
<SYSTEM_TASK:>
Send all buffered records and update the session accordingly.
<END_TASK>
<USER_TASK:>
Description:
def flush_records(self):
"""
Send all buffered records and update the session accordingly.
""" |
s = b"".join(p.raw_stateful() for p in self.buffer_out)
self.socket.send(s)
self.buffer_out = [] |
<SYSTEM_TASK:>
Return the 48-byte master_secret, computed from pre_master_secret,
<END_TASK>
<USER_TASK:>
Description:
def compute_master_secret(self, pre_master_secret,
client_random, server_random):
"""
Return the 48-byte master_secret, computed from pre_master_secret,
client_random and server_random. See RFC 5246, section 6.3.
""" |
seed = client_random + server_random
if self.tls_version < 0x0300:
return None
elif self.tls_version == 0x0300:
return self.prf(pre_master_secret, seed, 48)
else:
return self.prf(pre_master_secret, b"master secret", seed, 48) |
<SYSTEM_TASK:>
Perform the derivation of master_secret into a key_block of req_len
<END_TASK>
<USER_TASK:>
Description:
def derive_key_block(self, master_secret, server_random,
client_random, req_len):
"""
Perform the derivation of master_secret into a key_block of req_len
requested length. See RFC 5246, section 6.3.
""" |
seed = server_random + client_random
if self.tls_version <= 0x0300:
return self.prf(master_secret, seed, req_len)
else:
return self.prf(master_secret, b"key expansion", seed, req_len) |
<SYSTEM_TASK:>
Return verify_data based on handshake messages, connection end,
<END_TASK>
<USER_TASK:>
Description:
def compute_verify_data(self, con_end, read_or_write,
handshake_msg, master_secret):
"""
Return verify_data based on handshake messages, connection end,
master secret, and read_or_write position. See RFC 5246, section 7.4.9.
Every TLS 1.2 cipher suite has a verify_data of length 12. Note also:
"This PRF with the SHA-256 hash function is used for all cipher
suites defined in this document and in TLS documents published
prior to this document when TLS 1.2 is negotiated."
Cipher suites using SHA-384 were defined later on.
""" |
if self.tls_version < 0x0300:
return None
elif self.tls_version == 0x0300:
if read_or_write == "write":
d = {"client": b"CLNT", "server": b"SRVR"}
else:
d = {"client": b"SRVR", "server": b"CLNT"}
label = d[con_end]
sslv3_md5_pad1 = b"\x36" * 48
sslv3_md5_pad2 = b"\x5c" * 48
sslv3_sha1_pad1 = b"\x36" * 40
sslv3_sha1_pad2 = b"\x5c" * 40
md5 = _tls_hash_algs["MD5"]()
sha1 = _tls_hash_algs["SHA"]()
md5_hash = md5.digest(master_secret + sslv3_md5_pad2 +
md5.digest(handshake_msg + label +
master_secret + sslv3_md5_pad1))
sha1_hash = sha1.digest(master_secret + sslv3_sha1_pad2 +
sha1.digest(handshake_msg + label +
master_secret + sslv3_sha1_pad1)) # noqa: E501
verify_data = md5_hash + sha1_hash
else:
if read_or_write == "write":
d = {"client": "client", "server": "server"}
else:
d = {"client": "server", "server": "client"}
label = ("%s finished" % d[con_end]).encode()
if self.tls_version <= 0x0302:
s1 = _tls_hash_algs["MD5"]().digest(handshake_msg)
s2 = _tls_hash_algs["SHA"]().digest(handshake_msg)
verify_data = self.prf(master_secret, label, s1 + s2, 12)
else:
if self.hash_name in ["MD5", "SHA"]:
h = _tls_hash_algs["SHA256"]()
else:
h = _tls_hash_algs[self.hash_name]()
s = h.digest(handshake_msg)
verify_data = self.prf(master_secret, label, s, 12)
return verify_data |
<SYSTEM_TASK:>
Postprocess cipher key for EXPORT ciphersuite, i.e. weakens it.
<END_TASK>
<USER_TASK:>
Description:
def postprocess_key_for_export(self, key, client_random, server_random,
con_end, read_or_write, req_len):
"""
Postprocess cipher key for EXPORT ciphersuite, i.e. weakens it.
An export key generation example is given in section 6.3.1 of RFC 2246.
See also page 86 of EKR's book.
""" |
s = con_end + read_or_write
s = (s == "clientwrite" or s == "serverread")
if self.tls_version < 0x0300:
return None
elif self.tls_version == 0x0300:
if s:
tbh = key + client_random + server_random
else:
tbh = key + server_random + client_random
export_key = _tls_hash_algs["MD5"]().digest(tbh)[:req_len]
else:
if s:
tag = b"client write key"
else:
tag = b"server write key"
export_key = self.prf(key,
tag,
client_random + server_random,
req_len)
return export_key |