Skip to content

bech32: add BIP-173 padding validation #8419

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 25 additions & 2 deletions common/bech32_util.c
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ static u8 get_u5_bit(const u5 *src, size_t bitoff)
return ((src[bitoff / 5] >> (4 - (bitoff % 5))) & 1);
}

void bech32_pull_bits(u8 **data, const u5 *src, size_t nbits)
bool bech32_pull_bits(u8 **data, const u5 *src, size_t nbits)
{
size_t i;
size_t data_len = tal_count(*data);
Expand All @@ -46,6 +46,27 @@ void bech32_pull_bits(u8 **data, const u5 *src, size_t nbits)
}
data_len++;
}

/* BIP-173:
*
* Decoding...
* - Any incomplete group at the end MUST be 4 bits or less, MUST be all zeroes, and is discarded
*/
size_t remaining_bits = nbits - i;

if (remaining_bits > 0) {
if (remaining_bits > 4) {
return false;
}

for (size_t b = 0; b < remaining_bits; b++) {
if (get_u5_bit(src, i + b) != 0) {
return false;
}
}
}

return true;
}

/* Returns a char, tracks case. */
Expand Down Expand Up @@ -95,7 +116,9 @@ bool from_bech32_charset(const tal_t *ctx,
goto fail;

*data = tal_arr(ctx, u8, 0);
bech32_pull_bits(data, u5data, tal_bytelen(u5data) * 5);
if (!bech32_pull_bits(data, u5data, tal_bytelen(u5data) * 5)) {
goto fail;
}
tal_free(u5data);
return true;

Expand Down
2 changes: 1 addition & 1 deletion common/bech32_util.h
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ void bech32_push_bits(u5 **data, const void *src, size_t nbits);
/**
* Push the bytes in src in 8 bit format onto the end of data.
*/
void bech32_pull_bits(u8 **data, const u5 *src, size_t nbits);
bool bech32_pull_bits(u8 **data, const u5 *src, size_t nbits);

/**
* Checksumless bech32 routines.
Expand Down
4 changes: 3 additions & 1 deletion plugins/offers.c
Original file line number Diff line number Diff line change
Expand Up @@ -477,7 +477,9 @@ static u8 *encrypted_decode(const tal_t *ctx, const char *str, char **fail) {
goto fail;
}
u8 *data8bit = tal_arr(data, u8, 0);
bech32_pull_bits(&data8bit, data, datalen*5);
if (!bech32_pull_bits(&data8bit, data, datalen*5)) {
goto fail;
}

return data8bit;
fail:
Expand Down
Loading