Skip to content

Commit

Permalink
network-libp2p: Verify also peer contacts received
Browse files Browse the repository at this point in the history
Add verification of peer contacts received from the different
messages that can transmit a list of peer contacts in the discovery
protocol. The verification includes checks for appropriate lengths,
signatures and number of addresses.
  • Loading branch information
jsdanielh committed May 27, 2024
1 parent 9d3a23c commit 2377895
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 3 deletions.
41 changes: 40 additions & 1 deletion network-libp2p/src/discovery/handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -528,6 +528,32 @@ impl ConnectionHandler for Handler {
);
}

// Check and verify the peer contacts received
if peer_contacts.len() > self.config.update_limit as usize {
return Poll::Ready(
ConnectionHandlerEvent::NotifyBehaviour(
HandlerOutEvent::Error(
Error::UpdateLimitExceeded {
num_peer_contacts: peer_contacts.len(),
},
),
),
);
}
for peer_contact in &peer_contacts {
if !peer_contact.verify() {
return Poll::Ready(
ConnectionHandlerEvent::NotifyBehaviour(
HandlerOutEvent::Error(
Error::InvalidPeerContactSignature {
peer_contact: peer_contact.clone(),
},
),
),
);
}
}

let mut peer_contact_book = self.peer_contact_book.write();

// Insert the peer into the peer contact book.
Expand Down Expand Up @@ -614,7 +640,7 @@ impl ConnectionHandler for Handler {
}
self.last_update_time = Some(now);

// Check if the update is not too large.
// Check if the update is not too large and if the peer contacts verify
if peer_contacts.len() > self.config.update_limit as usize {
return Poll::Ready(
ConnectionHandlerEvent::NotifyBehaviour(
Expand All @@ -626,6 +652,19 @@ impl ConnectionHandler for Handler {
),
);
}
for peer_contact in &peer_contacts {
if !peer_contact.verify() {
return Poll::Ready(
ConnectionHandlerEvent::NotifyBehaviour(
HandlerOutEvent::Error(
Error::InvalidPeerContactSignature {
peer_contact: peer_contact.clone(),
},
),
),
);
}
}

// Insert the new peer contacts into the peer contact book.
self.peer_contact_book.write().insert_all_filtered(
Expand Down
4 changes: 2 additions & 2 deletions network-libp2p/tests/network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -352,9 +352,9 @@ async fn create_network_with_n_peers(n_peers: usize) -> Vec<Network> {
networks
}

#[test(tokio::test)]
#[test(tokio::test(flavor = "multi_thread", worker_threads = 10))]
async fn connections_stress_and_reconnect() {
let peers: usize = 15;
let peers: usize = 10;
let networks = create_network_with_n_peers(peers).await;

assert_eq!(peers, networks.len());
Expand Down

0 comments on commit 2377895

Please sign in to comment.