Skip to content

Commit

Permalink
core: better support of Buf with fixed size but invalid content
Browse files Browse the repository at this point in the history
  • Loading branch information
p1-bmu committed Mar 17, 2021
1 parent a20d9eb commit 80aaf07
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
2 changes: 2 additions & 0 deletions pycrate_core/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,8 @@ def get_bl(self):
__call__ = get_val


# Null terminated string
# only different from Buf when consuming a buffer at parsing
class NullTermStr(Buf):

def _from_char(self, char):
Expand Down
25 changes: 22 additions & 3 deletions pycrate_core/elt.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@
'Element', 'Atom', 'Envelope', 'Array', 'Sequence', 'Alt']


from binascii import hexlify

try:
from json import JSONEncoder, JSONDecoder
except ImportError:
Expand Down Expand Up @@ -660,7 +662,13 @@ def to_uint(self):
Returns:
uint (int) : unsigned integer
"""
return bytes_to_uint(self.to_bytes(), self.get_bl())
try:
return bytes_to_uint(self.to_bytes(), self.get_bl())
except PycrateErr:
# an invalid value has been set, _SAFE_STAT / DYN is probably disabled
# for e.g. fuzzing purpose, but there is still need to not break here
b = self.to_bytes()
return bytes_to_uint(b, len(b)<<3)

def from_int(self, integ, bl=None):
"""Consume a signed integer or charpy instance `integ' and sets the
Expand Down Expand Up @@ -698,7 +706,13 @@ def to_int(self):
Returns:
integ (int) : signed integer
"""
return bytes_to_int(self.to_bytes(), self.get_bl())
try:
return bytes_to_int(self.to_bytes(), self.get_bl())
except PycrateErr:
# an invalid value has been set, _SAFE_STAT / DYN is probably disabled
# for e.g. fuzzing purpose, but there is still need to not break here
b = self.to_bytes()
return bytes_to_int(b, len(b)<<3)

if python_version < 3:
__str__ = to_bytes
Expand All @@ -725,7 +739,12 @@ def hex(self):
if bl == 0:
return ''
else:
return uint_to_hex(bytes_to_uint(self.to_bytes(), bl), bl)
try:
return uint_to_hex(bytes_to_uint(self.to_bytes(), bl), bl)
except PycrateErr:
# an invalid value has been set, _SAFE_STAT / DYN is probably disabled
# for e.g. fuzzing purpose, but there is still need to not break here
return hexlify(self.to_bytes()).decode('ascii')

__bin__ = bin
__hex__ = hex
Expand Down

0 comments on commit 80aaf07

Please sign in to comment.