Skip to content

Commit ec8f20b

Browse files
Avoid out-of-bound pointers and integer overflows in size comparisons
This changes pointer calculations in size comparions to a form that ensures that no out-of-bound pointers are computed, because even their computation yields undefined behavior. Also, this changes size comparions to a form that ensures that neither the left-hand side nor the right-hand side can overflow.
1 parent 01ee1b3 commit ec8f20b

File tree

3 files changed

+7
-10
lines changed

3 files changed

+7
-10
lines changed

contrib/lax_der_parsing.c

+3-3
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ int ecdsa_signature_parse_der_lax(const secp256k1_context* ctx, secp256k1_ecdsa_
3232
lenbyte = input[pos++];
3333
if (lenbyte & 0x80) {
3434
lenbyte -= 0x80;
35-
if (pos + lenbyte > inputlen) {
35+
if (lenbyte > inputlen - pos) {
3636
return 0;
3737
}
3838
pos += lenbyte;
@@ -51,7 +51,7 @@ int ecdsa_signature_parse_der_lax(const secp256k1_context* ctx, secp256k1_ecdsa_
5151
lenbyte = input[pos++];
5252
if (lenbyte & 0x80) {
5353
lenbyte -= 0x80;
54-
if (pos + lenbyte > inputlen) {
54+
if (lenbyte > inputlen - pos) {
5555
return 0;
5656
}
5757
while (lenbyte > 0 && input[pos] == 0) {
@@ -89,7 +89,7 @@ int ecdsa_signature_parse_der_lax(const secp256k1_context* ctx, secp256k1_ecdsa_
8989
lenbyte = input[pos++];
9090
if (lenbyte & 0x80) {
9191
lenbyte -= 0x80;
92-
if (pos + lenbyte > inputlen) {
92+
if (lenbyte > inputlen - pos) {
9393
return 0;
9494
}
9595
while (lenbyte > 0 && input[pos] == 0) {

src/ecdsa_impl.h

+2-6
Original file line numberDiff line numberDiff line change
@@ -157,12 +157,8 @@ static int secp256k1_ecdsa_sig_parse(secp256k1_scalar *rr, secp256k1_scalar *rs,
157157
if (secp256k1_der_read_len(&rlen, &sig, sigend) == 0) {
158158
return 0;
159159
}
160-
if (sig + rlen > sigend) {
161-
/* Tuple exceeds bounds */
162-
return 0;
163-
}
164-
if (sig + rlen != sigend) {
165-
/* Garbage after tuple. */
160+
if (rlen != (size_t)(sigend - sig)) {
161+
/* Tuple exceeds bounds or garage after tuple. */
166162
return 0;
167163
}
168164

src/hash_impl.h

+2-1
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,8 @@ static void secp256k1_sha256_transform(uint32_t* s, const uint32_t* chunk) {
131131
static void secp256k1_sha256_write(secp256k1_sha256 *hash, const unsigned char *data, size_t len) {
132132
size_t bufsize = hash->bytes & 0x3F;
133133
hash->bytes += len;
134-
while (bufsize + len >= 64) {
134+
VERIFY_CHECK(hash->bytes >= len);
135+
while (len >= 64 - bufsize) {
135136
/* Fill the buffer, and process it. */
136137
size_t chunk_len = 64 - bufsize;
137138
memcpy(((unsigned char*)hash->buf) + bufsize, data, chunk_len);

0 commit comments

Comments
 (0)