Skip to content
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
17 changes: 10 additions & 7 deletions src/handler/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ use crate::metrics::METRICS;
use crate::{lru_time_cache::LruTimeCache, socket::ListenConfig};
use active_requests::ActiveRequests;
use request_call::RequestCall;
use session::Session;
use session::{ChallengeError, Session};

// The time interval to check banned peer timeouts and unban peers when the timeout has elapsed (in
// seconds).
Expand Down Expand Up @@ -852,7 +852,7 @@ impl Handler {
"Received an Authentication header message",
);

if let Some(challenge) = self.active_challenges.remove(&node_address) {
if let Some(challenge) = self.active_challenges.get(&node_address) {
match Session::establish_from_challenge(
self.key.clone(),
&self.node_id,
Expand All @@ -863,7 +863,8 @@ impl Handler {
enr_record,
) {
Ok((session, enr)) => {
// Remove the expected response for the challenge.
// Remove the active challenge and its expected response entry.
self.active_challenges.remove(&node_address);
self.remove_expected_response(node_address.socket_addr);
// Receiving an AuthResponse must give us an up-to-date view of the node ENR.
// Verify the ENR is valid
Expand Down Expand Up @@ -916,19 +917,21 @@ impl Handler {
)
.await;
}
Err(Error::InvalidChallengeSignature(challenge)) => {
Err(ChallengeError::InvalidSignature) => {
warn!(
%node_address,
"Authentication header contained invalid signature. Ignoring packet from node",
);
// insert back the challenge
self.active_challenges.insert(node_address, *challenge);
// Keep the existing challenge in place without resetting its expiry timer.
}
Err(e) => {
Err(ChallengeError::Other(e)) => {
warn!(
error = ?e,
"Invalid Authentication header. Dropping session",
);
// Remove the dropped challenge and its expected response entry.
self.active_challenges.remove(&node_address);
self.remove_expected_response(node_address.socket_addr);
self.fail_session(&node_address, RequestError::InvalidRemotePacket, true)
.await;
}
Expand Down
33 changes: 23 additions & 10 deletions src/handler/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,21 @@ pub(crate) struct Session {
counter: u32,
}

/// Error returned when establishing a session from an active challenge.
pub(crate) enum ChallengeError {
/// The challenge signature did not verify; the caller should keep the existing challenge
/// without resetting its expiry timer.
InvalidSignature,
/// Any other failure; the caller should drop the challenge and fail the session.
Other(Error),
}

impl From<Error> for ChallengeError {
fn from(err: Error) -> Self {
ChallengeError::Other(err)
}
}

impl Session {
pub fn new(keys: Keys) -> Self {
Session {
Expand Down Expand Up @@ -137,14 +152,14 @@ impl Session {
local_key: Arc<RwLock<CombinedKey>>,
local_id: &NodeId,
remote_id: &NodeId,
challenge: Challenge,
challenge: &Challenge,
id_nonce_sig: &[u8],
ephem_pubkey: &[u8],
enr_record: Option<Enr>,
) -> Result<(Session, Enr), Error> {
) -> Result<(Session, Enr), ChallengeError> {
// check and verify a potential ENR update

// Duplicate code here to avoid cloning an ENR
// Duplicate code here to avoid cloning an ENR before signature verification
let remote_public_key = {
let enr = match (enr_record.as_ref(), challenge.remote_enr.as_ref()) {
(Some(new_enr), Some(known_enr)) => {
Expand All @@ -161,7 +176,7 @@ impl Session {
node = %remote_id,
"Peer did not respond with their ENR. Session could not be established",
);
return Err(Error::SessionNotEstablished);
return Err(ChallengeError::Other(Error::SessionNotEstablished));
}
};
enr.public_key()
Expand All @@ -175,7 +190,7 @@ impl Session {
local_id,
id_nonce_sig,
) {
return Err(Error::InvalidChallengeSignature(Box::new(challenge)));
return Err(ChallengeError::InvalidSignature);
}

// The keys are derived after the message has been verified to prevent potential extra work
Expand All @@ -195,18 +210,16 @@ impl Session {
decryption_key,
};

// Takes ownership of the provided ENRs - Slightly annoying code duplication, but avoids
// cloning ENRs
let session_enr = match (enr_record, challenge.remote_enr) {
let session_enr = match (enr_record, challenge.remote_enr.as_ref()) {
(Some(new_enr), Some(known_enr)) => {
if new_enr.seq() > known_enr.seq() {
new_enr
} else {
known_enr
known_enr.clone()
}
}
(Some(new_enr), None) => new_enr,
(None, Some(known_enr)) => known_enr,
(None, Some(known_enr)) => known_enr.clone(),
(None, None) => unreachable!("Checked in the first match above"),
};

Expand Down
116 changes: 116 additions & 0 deletions src/handler/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1087,3 +1087,119 @@ async fn test_send_pending_request() {
}
}
}

#[tokio::test]
async fn test_failed_handshake_removes_expected_response() {
init();

let ip = Ipv4Addr::LOCALHOST;
let key = CombinedKey::generate_secp256k1();
let local_enr = Enr::builder().ip4(ip).udp4(0).build(&key).unwrap();
let config = ConfigBuilder::new(ListenConfig::Ipv4 { ip, port: 0 })
.enable_packet_filter()
.build();
let (_exit, _send, _recv, mut handler) = build_handler(local_enr, key, config).await;

let remote_key = CombinedKey::generate_secp256k1();
let remote_enr = Enr::builder()
.ip4(ip)
.udp4(5010)
.build(&remote_key)
.unwrap();
let node_address = NodeAddress {
socket_addr: (ip, 5010).into(),
node_id: remote_enr.node_id(),
};

handler
.send_challenge(WhoAreYouRef(node_address.clone(), [0u8; 12]), None)
.await;
assert_eq!(handler.active_challenges.len(), 1);
assert_eq!(
handler
.filter_expected_responses
.read()
.get(&node_address.socket_addr),
Some(&1)
);

// Handshake with no ENR on either side fails with SessionNotEstablished.
handler
.handle_auth_message(node_address.clone(), [0u8; 12], &[], &[], None, &[], &[])
.await;

assert!(handler.active_challenges.is_empty());
assert!(handler.filter_expected_responses.read().is_empty());
}

#[tokio::test]
async fn test_invalid_challenge_signature_does_not_reset_expiry() {
init();

let ip = Ipv4Addr::LOCALHOST;
let key = CombinedKey::generate_secp256k1();
let local_enr = Enr::builder().ip4(ip).udp4(0).build(&key).unwrap();
let config = ConfigBuilder::new(ListenConfig::Ipv4 { ip, port: 0 })
.request_timeout(Duration::from_millis(200))
.enable_packet_filter()
.build();
let (_exit, _send, _recv, mut handler) = build_handler(local_enr, key, config).await;

let remote_key = CombinedKey::generate_secp256k1();
let remote_enr = Enr::builder()
.ip4(ip)
.udp4(5011)
.build(&remote_key)
.unwrap();
let node_address = NodeAddress {
socket_addr: (ip, 5011).into(),
node_id: remote_enr.node_id(),
};

handler
.send_challenge(WhoAreYouRef(node_address.clone(), [0u8; 12]), None)
.await;
assert_eq!(handler.active_challenges.len(), 1);
assert_eq!(
handler
.filter_expected_responses
.read()
.get(&node_address.socket_addr),
Some(&1)
);

// Repeated invalid-signature handshakes must not reset the challenge timeout.
let mut tick = tokio::time::interval(Duration::from_millis(50));
tick.tick().await;
let deadline = sleep(Duration::from_millis(600));
tokio::pin!(deadline);

let expired = loop {
tokio::select! {
Some(Ok((expired_addr, _))) = handler.active_challenges.next() => {
handler.remove_expected_response(expired_addr.socket_addr);
break true;
}
_ = tick.tick() => {
handler
.handle_auth_message(
node_address.clone(),
[0u8; 12],
&[0u8; 64],
&[0u8; 33],
Some(remote_enr.clone()),
&[],
&[],
)
.await;
}
_ = &mut deadline => {
break false;
}
}
};

assert!(expired, "challenge expiry was reset by invalid signatures");
assert!(handler.active_challenges.is_empty());
assert!(handler.filter_expected_responses.read().is_empty());
}