fix(iroh-dns): validate the response question against the query

The response parser only checked the transaction ID, the QR bit, the
presence of a question, and the RCODE. It then took the queried name
from the response's own question section, so a forged reply that guessed
the 16-bit ID and supplied its own question could have its answers
accepted for an arbitrary name. CNAME-following decisions were taken on
a packet whose ID was never verified, since only the final hop was
checked.

Validate every hop in send_query_following_cnames: check_response now
takes the queried name and type and rejects any response whose single
question does not echo them, alongside the existing ID, QR, and RCODE
checks. The parse_* functions become pure extractors that run on an
already-validated response, anchoring CNAME resolution on the verified
question.
This commit is contained in:
Frando
2026-06-22 15:34:35 +02:00
parent 900468d118
commit b831f4f5bf
3 changed files with 106 additions and 71 deletions
+12 -5
View File
@@ -407,26 +407,33 @@ impl SimpleDnsResolver {
&self,
host: String,
qtype: TYPE,
) -> Result<(Vec<u8>, u16), DnsError> {
) -> Result<Vec<u8>, DnsError> {
let mut current_host = host;
for _ in 0..MAX_CNAME_DEPTH {
let name = simple_dns::Name::new(&current_host)
.map_err(|e| e!(DnsError::InvalidQuery, AnyError::from_std(e)))?;
let (id, query_bytes) = query::build_query(&current_host, qtype)?;
let response = self.send_query(&query_bytes).await?;
let packet =
simple_dns::Packet::parse(&response).map_err(|_| e!(DnsError::InvalidResponse))?;
// Validate the id, QR bit, question, and RCODE before trusting the
// packet to decide the answer or the next CNAME target. This is the
// only check of the response against the name we actually asked for.
query::check_response(&packet, id, &name, qtype)?;
let has_answer = packet
.answers
.iter()
.any(|rr| rr.rdata.type_code() == qtype);
if has_answer {
return Ok((response, id));
return Ok(response);
}
// No records of the requested type -- follow CNAME if present.
let Some(target) = query::cname_target(&packet, &current_host) else {
return Ok((response, id));
return Ok(response);
};
debug!(from = %current_host, to = %target, "following CNAME");
current_host = target;
@@ -442,7 +449,7 @@ impl SimpleDnsResolver {
qtype: QueryType,
dns_type: TYPE,
from_cache: fn(CachedRecord) -> Option<Vec<T>>,
parse: fn(&[u8], u16) -> Result<(Vec<T>, u32), QueryError>,
parse: fn(&[u8]) -> Result<(Vec<T>, u32), QueryError>,
to_cache: fn(Vec<T>) -> CachedRecord,
) -> Result<Vec<T>, DnsError> {
if let Some(cached) = self.cache.get(host, qtype).and_then(from_cache) {
@@ -459,7 +466,7 @@ impl SimpleDnsResolver {
.send_query_following_cnames(name.clone(), dns_type)
.await
{
Ok((response, id)) => parse(&response, id).map_err(DnsError::from),
Ok(response) => parse(&response).map_err(DnsError::from),
Err(e) => Err(e),
};
match res {
+82 -48
View File
@@ -98,23 +98,34 @@ pub(super) fn cname_target(packet: &Packet<'_>, qname: &str) -> Option<String> {
(canonical != name).then(|| canonical.to_string())
}
/// Check response packet for errors (QR bit, ID mismatch, question section, RCODE).
/// Validate a response against the query that produced it, then surface its RCODE.
///
/// Validates per RFC 5452: transaction ID, QR flag, and question section must match
/// the original query to prevent spoofed responses.
fn check_response(packet: &Packet, expected_id: u16) -> Result<(), QueryError> {
/// Per RFC 5452 a response is only trustworthy if it echoes the query: the QR
/// flag must be set, the transaction ID must match, and the response must carry
/// exactly the one question we asked, by name, type, and class. Without the
/// question check an off-path attacker who guesses the 16-bit ID could supply
/// its own question and have its answers accepted for an arbitrary name. A
/// `NameError` RCODE maps to [`QueryError::NxDomain`] and any other non-`NoError`
/// RCODE to [`QueryError::ServerFailure`].
pub(super) fn check_response(
packet: &Packet,
expected_id: u16,
expected_name: &Name<'_>,
expected_type: TYPE,
) -> Result<(), QueryError> {
if !packet.has_flags(PacketFlag::RESPONSE) {
return Err(e!(QueryError::Unexpected));
}
if packet.id() != expected_id {
return Err(e!(QueryError::Unexpected));
}
// A well-formed response echoes the query's question section (RFC 1035
// Section 4.1.2). Reject a question-less response: without a question,
// `name_matches` would accept answers for any name, so a spoofed reply that
// guessed the transaction ID could inject records for an arbitrary host.
if packet.questions.is_empty() {
return Err(e!(QueryError::Unexpected));
// The response must echo exactly the question we sent (RFC 1035 4.1.2).
match packet.questions.as_slice() {
[question]
if &question.qname == expected_name
&& question.qtype == QTYPE::TYPE(expected_type)
&& question.qclass == QCLASS::CLASS(CLASS::IN) => {}
_ => return Err(e!(QueryError::Unexpected)),
}
match packet.rcode() {
RCODE::NoError => Ok(()),
@@ -142,18 +153,18 @@ fn name_matches(
}
}
/// Parse matching records from a DNS response, following CNAME chains.
/// Extract matching records from a validated DNS response, following CNAME chains.
///
/// Validates the response, resolves CNAME chains, then extracts records using
/// the provided closure. Returns the extracted records and the minimum TTL.
/// The caller must already have validated the response with [`check_response`];
/// this resolves the CNAME chain anchored on the question and extracts records
/// of the requested type using `extract`. Returns the records and the minimum
/// TTL across them.
fn parse_response<T>(
data: &[u8],
expected_id: u16,
extract: impl Fn(&RData<'_>) -> Option<T>,
) -> Result<(Vec<T>, u32), QueryError> {
let packet =
Packet::parse(data).map_err(|e| e!(QueryError::Malformed, AnyError::from_std(e)))?;
check_response(&packet, expected_id)?;
let qname = packet.questions.first().map(|q| q.qname.clone());
let canonical = qname.as_ref().map(|q| resolve_cname_chain(&packet, q));
@@ -175,33 +186,24 @@ fn parse_response<T>(
}
/// Parse A (IPv4) records from a DNS response, following CNAME chains.
pub(super) fn parse_a_response(
data: &[u8],
expected_id: u16,
) -> Result<(Vec<Ipv4Addr>, u32), QueryError> {
parse_response(data, expected_id, |rdata| match rdata {
pub(super) fn parse_a_response(data: &[u8]) -> Result<(Vec<Ipv4Addr>, u32), QueryError> {
parse_response(data, |rdata| match rdata {
RData::A(A { address }) => Some(Ipv4Addr::from(*address)),
_ => None,
})
}
/// Parse AAAA (IPv6) records from a DNS response, following CNAME chains.
pub(super) fn parse_aaaa_response(
data: &[u8],
expected_id: u16,
) -> Result<(Vec<Ipv6Addr>, u32), QueryError> {
parse_response(data, expected_id, |rdata| match rdata {
pub(super) fn parse_aaaa_response(data: &[u8]) -> Result<(Vec<Ipv6Addr>, u32), QueryError> {
parse_response(data, |rdata| match rdata {
RData::AAAA(AAAA { address }) => Some(Ipv6Addr::from(*address)),
_ => None,
})
}
/// Parse TXT records from a DNS response, following CNAME chains.
pub(super) fn parse_txt_response(
data: &[u8],
expected_id: u16,
) -> Result<(Vec<TxtRecordData>, u32), QueryError> {
parse_response(data, expected_id, |rdata| match rdata {
pub(super) fn parse_txt_response(data: &[u8]) -> Result<(Vec<TxtRecordData>, u32), QueryError> {
parse_response(data, |rdata| match rdata {
RData::TXT(txt) => Some(extract_txt_record_data(txt)),
_ => None,
})
@@ -338,7 +340,7 @@ mod tests {
fn parse_a_no_cname() {
let (id, _) = make_query("example.com");
let resp = a_response(id, "example.com", &[Ipv4Addr::new(1, 2, 3, 4)]);
let (addrs, ttl) = parse_a_response(&resp, id).unwrap();
let (addrs, ttl) = parse_a_response(&resp).unwrap();
assert_eq!(addrs, [Ipv4Addr::new(1, 2, 3, 4)]);
assert_eq!(ttl, 300);
}
@@ -352,7 +354,7 @@ mod tests {
"real.example.com",
&[Ipv4Addr::new(10, 0, 0, 1), Ipv4Addr::new(10, 0, 0, 2)],
);
let (addrs, _) = parse_a_response(&resp, id).unwrap();
let (addrs, _) = parse_a_response(&resp).unwrap();
assert_eq!(
addrs,
[Ipv4Addr::new(10, 0, 0, 1), Ipv4Addr::new(10, 0, 0, 2)]
@@ -392,7 +394,7 @@ mod tests {
}),
));
let resp = packet.build_bytes_vec().unwrap();
let (addrs, _) = parse_a_response(&resp, id).unwrap();
let (addrs, _) = parse_a_response(&resp).unwrap();
assert_eq!(addrs, [Ipv4Addr::new(5, 6, 7, 8)]);
}
@@ -405,25 +407,57 @@ mod tests {
assert_eq!(target.as_deref(), Some("real.example.com"));
}
#[test]
fn reject_response_without_question_section() {
// A response carrying answers but no question section must be rejected,
// even with the correct transaction ID, so it cannot inject records for
// an arbitrary name.
let (id, _) = make_query("example.com");
/// Builds a reply packet echoing one question for `name`/`qtype`, plus an A
/// answer, so `check_response` has something to validate.
fn reply_with_question(id: u16, name: &str, qtype: TYPE) -> Packet<'static> {
let mut packet = Packet::new_reply(id);
packet.set_flags(PacketFlag::RECURSION_DESIRED | PacketFlag::RECURSION_AVAILABLE);
packet.answers.push(ResourceRecord::new(
Name::new_unchecked("attacker.example"),
CLASS::IN,
300,
RData::A(A {
address: u32::from(Ipv4Addr::new(6, 6, 6, 6)),
}),
packet.questions.push(Question::new(
Name::new_unchecked(name).into_owned(),
QTYPE::TYPE(qtype),
QCLASS::CLASS(CLASS::IN),
false,
));
let resp = packet.build_bytes_vec().unwrap();
packet
}
#[test]
fn check_response_accepts_a_matching_reply() {
let name = Name::new_unchecked("example.com");
let packet = reply_with_question(42, "example.com", TYPE::A);
assert!(check_response(&packet, 42, &name, TYPE::A).is_ok());
}
#[test]
fn check_response_rejects_mismatches() {
let name = Name::new_unchecked("example.com");
// Wrong transaction id.
let packet = reply_with_question(42, "example.com", TYPE::A);
assert!(matches!(
parse_a_response(&resp, id),
check_response(&packet, 7, &name, TYPE::A),
Err(QueryError::Unexpected { .. })
));
// Question name does not echo the query.
let packet = reply_with_question(42, "attacker.example", TYPE::A);
assert!(matches!(
check_response(&packet, 42, &name, TYPE::A),
Err(QueryError::Unexpected { .. })
));
// Question type does not match.
let packet = reply_with_question(42, "example.com", TYPE::AAAA);
assert!(matches!(
check_response(&packet, 42, &name, TYPE::A),
Err(QueryError::Unexpected { .. })
));
// No question section at all.
let mut packet = reply_with_question(42, "example.com", TYPE::A);
packet.questions.clear();
assert!(matches!(
check_response(&packet, 42, &name, TYPE::A),
Err(QueryError::Unexpected { .. })
));
}
+12 -18
View File
@@ -293,10 +293,9 @@ mod tests {
#[tokio::test]
async fn test_udp_query() {
let (addr, handle) = mock_udp_server(&[Ipv4Addr::new(93, 184, 216, 34)]).await;
let (id, query) = build_query();
let (_, query) = build_query();
let (addrs, _) =
super::super::query::parse_a_response(&udp_query(addr, &query).await.unwrap(), id)
.unwrap();
super::super::query::parse_a_response(&udp_query(addr, &query).await.unwrap()).unwrap();
assert_eq!(addrs, [Ipv4Addr::new(93, 184, 216, 34)]);
handle.await.unwrap();
}
@@ -304,13 +303,11 @@ mod tests {
#[tokio::test]
async fn test_tcp_query() {
let (addr, handle) = mock_tcp_server(&[Ipv4Addr::new(93, 184, 216, 34)]).await;
let (id, query) = build_query();
let (_, query) = build_query();
let pool = ConnPool::new();
let (addrs, _) = super::super::query::parse_a_response(
&tcp_query(&pool, addr, &query).await.unwrap(),
id,
)
.unwrap();
let (addrs, _) =
super::super::query::parse_a_response(&tcp_query(&pool, addr, &query).await.unwrap())
.unwrap();
assert_eq!(addrs, [Ipv4Addr::new(93, 184, 216, 34)]);
handle.await.unwrap();
}
@@ -323,10 +320,9 @@ mod tests {
Ipv4Addr::new(9, 10, 11, 12),
];
let (addr, handle) = mock_udp_server(&expected).await;
let (id, query) = build_query();
let (_, query) = build_query();
let (addrs, ttl) =
super::super::query::parse_a_response(&udp_query(addr, &query).await.unwrap(), id)
.unwrap();
super::super::query::parse_a_response(&udp_query(addr, &query).await.unwrap()).unwrap();
assert_eq!(addrs, expected);
assert_eq!(ttl, 300);
handle.await.unwrap();
@@ -336,13 +332,11 @@ mod tests {
async fn test_tcp_large_response() {
let expected: Vec<Ipv4Addr> = (0..50).map(|i| Ipv4Addr::new(10, 0, 0, i)).collect();
let (addr, handle) = mock_tcp_server(&expected).await;
let (id, query) = build_query();
let (_, query) = build_query();
let pool = ConnPool::new();
let (addrs, _) = super::super::query::parse_a_response(
&tcp_query(&pool, addr, &query).await.unwrap(),
id,
)
.unwrap();
let (addrs, _) =
super::super::query::parse_a_response(&tcp_query(&pool, addr, &query).await.unwrap())
.unwrap();
assert_eq!(addrs, expected);
handle.await.unwrap();
}