Skip to content

Commit 50e6d9f

Browse files
committed
strict error checking in DER decoding of integers and sequences
1 parent 72621b1 commit 50e6d9f

File tree

1 file changed

+21
-6
lines changed

1 file changed

+21
-6
lines changed

src/ecdsa/der.py

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -75,10 +75,15 @@ def remove_constructed(string):
7575

7676

7777
def remove_sequence(string):
78+
if not string:
79+
raise UnexpectedDER("Empty string does not encode a sequence")
7880
if not string.startswith(b("\x30")):
79-
n = string[0] if isinstance(string[0], integer_types) else ord(string[0])
80-
raise UnexpectedDER("wanted sequence (0x30), got 0x%02x" % n)
81+
n = string[0] if isinstance(string[0], integer_types) else \
82+
ord(string[0])
83+
raise UnexpectedDER("wanted type 'sequence' (0x30), got 0x%02x" % n)
8184
length, lengthlength = read_length(string[1:])
85+
if length > len(string) - 1 - lengthlength:
86+
raise UnexpectedDER("Length longer than the provided buffer")
8287
endseq = 1+lengthlength+length
8388
return string[1+lengthlength:endseq], string[endseq:]
8489

@@ -114,14 +119,24 @@ def remove_object(string):
114119

115120

116121
def remove_integer(string):
122+
if not string:
123+
raise UnexpectedDER("Empty string is an invalid encoding of an "
124+
"integer")
117125
if not string.startswith(b("\x02")):
118-
n = string[0] if isinstance(string[0], integer_types) else ord(string[0])
119-
raise UnexpectedDER("wanted integer (0x02), got 0x%02x" % n)
126+
n = string[0] if isinstance(string[0], integer_types) \
127+
else ord(string[0])
128+
raise UnexpectedDER("wanted type 'integer' (0x02), got 0x%02x" % n)
120129
length, llen = read_length(string[1:])
130+
if length > len(string) - 1 - llen:
131+
raise UnexpectedDER("Length longer than provided buffer")
132+
if length == 0:
133+
raise UnexpectedDER("0-byte long encoding of integer")
121134
numberbytes = string[1+llen:1+llen+length]
122135
rest = string[1+llen+length:]
123-
nbytes = numberbytes[0] if isinstance(numberbytes[0], integer_types) else ord(numberbytes[0])
124-
assert nbytes < 0x80 # can't support negative numbers yet
136+
nbytes = numberbytes[0] if isinstance(numberbytes[0], integer_types) \
137+
else ord(numberbytes[0])
138+
if not nbytes < 0x80:
139+
raise UnexpectedDER("Negative integers are not supported")
125140
return int(binascii.hexlify(numberbytes), 16), rest
126141

127142

0 commit comments

Comments
 (0)