iroh_dns_server/http/doh/
extract.rs

1//! Extractors for DNS-over-HTTPS requests
2
3// This module is mostly copied from
4// https://github.com/fission-codes/fission-server/blob/394de877fad021260c69fdb1edd7bb4b2f98108c/fission-server/src/extract/doh.rs
5
6use std::{
7    fmt::{self, Display, Formatter},
8    future::Future,
9    net::SocketAddr,
10    str::FromStr,
11};
12
13use axum::{
14    body::Body,
15    extract::{ConnectInfo, FromRequest, FromRequestParts, Query},
16    http::Request,
17};
18use bytes::Bytes;
19use hickory_server::{
20    net::xfer::Protocol,
21    proto::{
22        self,
23        serialize::binary::{BinEncodable, BinEncoder},
24    },
25    server::Request as DNSRequest,
26};
27use http::{HeaderValue, StatusCode, header, request::Parts};
28use serde::Deserialize;
29use tracing::info;
30
31use crate::http::error::AppError;
32
33/// A DNS packet encoding type
34#[derive(Debug)]
35pub(super) enum DnsMimeType {
36    /// application/dns-message
37    Message,
38    /// application/dns-json
39    Json,
40}
41
42impl Display for DnsMimeType {
43    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
44        match self {
45            DnsMimeType::Message => write!(f, "application/dns-message"),
46            DnsMimeType::Json => write!(f, "application/dns-json"),
47        }
48    }
49}
50
51impl DnsMimeType {
52    /// Turn this mime type to an `Accept` HTTP header value
53    pub(super) fn to_header_value(&self) -> HeaderValue {
54        HeaderValue::from_static(match self {
55            Self::Message => "application/dns-message",
56            Self::Json => "application/dns-json",
57        })
58    }
59}
60
61#[derive(Debug, Deserialize)]
62struct DnsMessageQuery {
63    dns: String,
64}
65
66// See: https://developers.google.com/speed/public-dns/docs/doh/json#supported_parameters
67#[derive(Debug, Deserialize)]
68struct DnsQuery {
69    /// Record name to look up, e.g. example.com
70    name: String,
71    /// Record type, e.g. A/AAAA/TXT, etc.
72    #[serde(rename = "type")]
73    record_type: Option<String>,
74    /// Used to disable DNSSEC validation
75    cd: Option<bool>,
76    /// Desired content type. E.g. "application/dns-message" or "application/dns-json"
77    #[allow(dead_code)]
78    ct: Option<String>,
79    /// Whether to return DNSSEC entries such as RRSIG, NSEC or NSEC3
80    #[serde(rename = "do")]
81    dnssec_ok: Option<bool>,
82    /// Privacy setting for how your IP address is forwarded to authoritative nameservers
83    #[allow(dead_code)]
84    edns_client_subnet: Option<String>,
85    /// Some url-safe random characters to pad your messages for privacy (to avoid being fingerprinted by encrypted message length)
86    #[allow(dead_code)]
87    random_padding: Option<String>,
88    /// Whether to provide answers for all records up to the root
89    #[serde(rename = "rd")]
90    recursion_desired: Option<bool>,
91}
92
93/// A DNS request encoded in the query string
94#[derive(Debug)]
95pub(crate) struct DnsRequestQuery(pub(super) DNSRequest, pub(super) DnsMimeType);
96
97/// A DNS request encoded in the body
98#[derive(Debug)]
99pub(crate) struct DnsRequestBody(pub(crate) DNSRequest);
100
101impl<S> FromRequestParts<S> for DnsRequestQuery
102where
103    S: Send + Sync,
104{
105    type Rejection = AppError;
106
107    #[allow(clippy::manual_async_fn)]
108    fn from_request_parts(
109        parts: &mut Parts,
110        state: &S,
111    ) -> impl Future<Output = Result<Self, Self::Rejection>> + Send {
112        async move {
113            let ConnectInfo(src_addr) = ConnectInfo::from_request_parts(parts, state).await?;
114
115            match parts.headers.get(header::ACCEPT) {
116                Some(content_type) if content_type == "application/dns-message" => {
117                    handle_dns_message_query(parts, state, src_addr).await
118                }
119                Some(content_type) if content_type == "application/dns-json" => {
120                    handle_dns_json_query(parts, state, src_addr).await
121                }
122                Some(content_type) if content_type == "application/x-javascript" => {
123                    handle_dns_json_query(parts, state, src_addr).await
124                }
125                None => handle_dns_message_query(parts, state, src_addr).await,
126                _ => Err(AppError::with_status(StatusCode::NOT_ACCEPTABLE)),
127            }
128        }
129    }
130}
131
132impl<S> FromRequest<S> for DnsRequestBody
133where
134    S: Send + Sync,
135{
136    type Rejection = AppError;
137
138    #[allow(clippy::manual_async_fn)]
139    fn from_request(
140        req: Request<Body>,
141        state: &S,
142    ) -> impl Future<Output = Result<Self, Self::Rejection>> + Send {
143        async move {
144            let (mut parts, body) = req.into_parts();
145
146            let ConnectInfo(src_addr) = ConnectInfo::from_request_parts(&mut parts, state).await?;
147
148            let req = Request::from_parts(parts, body);
149
150            let body = Bytes::from_request(req, state)
151                .await
152                .map_err(|_| AppError::with_status(StatusCode::INTERNAL_SERVER_ERROR))?;
153
154            let request = decode_request(&body, src_addr)?;
155
156            Ok(DnsRequestBody(request))
157        }
158    }
159}
160
161async fn handle_dns_message_query<S>(
162    parts: &mut Parts,
163    state: &S,
164    src_addr: SocketAddr,
165) -> Result<DnsRequestQuery, AppError>
166where
167    S: Send + Sync,
168{
169    let Query(params) = Query::<DnsMessageQuery>::from_request_parts(parts, state).await?;
170
171    let buf = base64_url::decode(params.dns.as_bytes())
172        .map_err(|err| AppError::new(StatusCode::BAD_REQUEST, Some(err)))?;
173
174    let request = decode_request(&buf, src_addr)?;
175
176    Ok(DnsRequestQuery(request, DnsMimeType::Message))
177}
178
179async fn handle_dns_json_query<S>(
180    parts: &mut Parts,
181    state: &S,
182    src_addr: SocketAddr,
183) -> Result<DnsRequestQuery, AppError>
184where
185    S: Send + Sync,
186{
187    let Query(dns_query) = Query::<DnsQuery>::from_request_parts(parts, state).await?;
188
189    let request = encode_query_as_request(dns_query, src_addr)?;
190
191    Ok(DnsRequestQuery(request, DnsMimeType::Json))
192}
193
194/// Exposed to make it usable internally...
195fn encode_query_as_request(
196    question: DnsQuery,
197    src_addr: SocketAddr,
198) -> Result<DNSRequest, AppError> {
199    let query_type = if let Some(record_type) = question.record_type {
200        record_type
201            .parse::<u16>()
202            .map(proto::rr::RecordType::from)
203            .or_else(|_| FromStr::from_str(&record_type.to_uppercase()))
204            .map_err(|err| AppError::new(StatusCode::BAD_REQUEST, Some(err)))?
205    } else {
206        proto::rr::RecordType::A
207    };
208
209    let name = proto::rr::Name::from_utf8(question.name)
210        .map_err(|err| AppError::new(StatusCode::BAD_REQUEST, Some(err)))?;
211
212    let query = proto::op::Query::query(name, query_type);
213
214    let mut message = proto::op::Message::query();
215    message.metadata.checking_disabled = question.cd.unwrap_or(false);
216    message.metadata.recursion_desired = question.recursion_desired.unwrap_or(true);
217    message.metadata.recursion_available = true;
218    message.metadata.authentic_data = question.dnssec_ok.unwrap_or(false);
219    message.add_query(query);
220
221    // This is kind of a hack, but the only way I can find to
222    // create a MessageRequest is by decoding a buffer of bytes,
223    // so we encode the message into a buffer and then decode it
224    let mut buf = Vec::with_capacity(4096);
225    let mut encoder = BinEncoder::new(&mut buf);
226
227    message
228        .emit(&mut encoder)
229        .map_err(|err| AppError::new(StatusCode::BAD_REQUEST, Some(err)))?;
230
231    let request = decode_request(&buf, src_addr)?;
232
233    Ok(request)
234}
235
236fn decode_request(bytes: &[u8], src_addr: SocketAddr) -> Result<DNSRequest, AppError> {
237    match DNSRequest::from_bytes(bytes.to_vec(), src_addr, Protocol::Https) {
238        Ok(request) => {
239            info!("received message {:?}", *request);
240            if request.metadata.message_type != proto::op::MessageType::Query {
241                return Err(AppError::new(
242                    StatusCode::BAD_REQUEST,
243                    Some("Invalid message type: expected query"),
244                ));
245            }
246            Ok(request)
247        }
248        Err(err) => Err(AppError::new(
249            StatusCode::BAD_REQUEST,
250            Some(format!("Invalid DNS message: {err}")),
251        )),
252    }
253}