Skip to content

Commit 01e163e

Browse files
committed
f Upper-bound read channels/nodes, avoid u64/usize overflows
1 parent a6a70dc commit 01e163e

File tree

1 file changed

+14
-2
lines changed

1 file changed

+14
-2
lines changed

lightning/src/routing/gossip.rs

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1682,10 +1682,18 @@ where
16821682
fn read<R: io::Read>(reader: &mut R, logger: L) -> Result<NetworkGraph<L>, DecodeError> {
16831683
let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
16841684

1685+
const MAX_CHAN_COUNT_LIMIT: usize = 100_000_000;
1686+
const MAX_NODE_COUNT_LIMIT: usize = 10_000_000;
1687+
16851688
let chain_hash: ChainHash = Readable::read(reader)?;
16861689
let channels_count: u64 = Readable::read(reader)?;
16871690
// Pre-allocate 115% of the known channel count to avoid unnecessary reallocations.
1688-
let channels_map_capacity = (channels_count * 115 / 100) as usize;
1691+
let channels_map_capacity = (channels_count as u128 * 115 / 100)
1692+
.try_into()
1693+
.map_err(|_| DecodeError::InvalidValue)?;
1694+
if channels_map_capacity > MAX_CHAN_COUNT_LIMIT {
1695+
return Err(DecodeError::InvalidValue);
1696+
}
16891697
let mut channels = IndexedMap::with_capacity(channels_map_capacity);
16901698
for _ in 0..channels_count {
16911699
let chan_id: u64 = Readable::read(reader)?;
@@ -1699,7 +1707,11 @@ where
16991707
return Err(DecodeError::InvalidValue);
17001708
}
17011709
// Pre-allocate 115% of the known channel count to avoid unnecessary reallocations.
1702-
let nodes_map_capacity = (nodes_count * 115 / 100) as usize;
1710+
let nodes_map_capacity: usize =
1711+
(nodes_count as u128 * 115 / 100).try_into().map_err(|_| DecodeError::InvalidValue)?;
1712+
if nodes_map_capacity > MAX_NODE_COUNT_LIMIT {
1713+
return Err(DecodeError::InvalidValue);
1714+
}
17031715
let mut nodes = IndexedMap::with_capacity(nodes_map_capacity);
17041716
for i in 0..nodes_count {
17051717
let node_id = Readable::read(reader)?;

0 commit comments

Comments
 (0)