dns.rs 9.17 KB
Newer Older
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
1
use std::net::{Ipv6Addr, Ipv4Addr};
2
use std::fmt;
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
3
4
5
6
use std::ops::{Deref, DerefMut};


use rocket::{Request, State, http::Status, request::{FromParam, FromRequest, Outcome}};
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
7
8
9

use serde::{Serialize, Deserialize};

Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
10
11
12
13
14
15
16
17
18
use tokio::{net::TcpStream as TokioTcpStream, task};

use trust_dns_client::{client::AsyncClient, serialize::binary::BinEncoder, tcp::TcpClientStream};
use trust_dns_proto::error::{ProtoError};
use trust_dns_proto::iocompat::AsyncIoTokioAsStd;


use super::trust_dns_types::{self, Name};
use crate::config::Config;
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
19
20
21
22


#[derive(Deserialize, Serialize)]
#[serde(tag = "Type")]
23
#[serde(rename_all = "UPPERCASE")]
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
24
25
26
27
28
29
30
31
32
pub enum RData {
    #[serde(rename_all = "PascalCase")]
    A {
        address: Ipv4Addr
    },
    #[serde(rename_all = "PascalCase")]
    AAAA {
        address: Ipv6Addr
    },
33
34
35
36
37
38
39
40
41
42
    #[serde(rename_all = "PascalCase")]
    CAA {
        issuer_critical: bool,
        value: String,
        property_tag: String,
    },
    #[serde(rename_all = "PascalCase")]
    CNAME {
        target: String
    },
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
43
44
    // HINFO(HINFO),
    // HTTPS(SVCB),
45
46
47
48
49
    #[serde(rename_all = "PascalCase")]
    MX {
        preference: u16,
        mail_exchanger: String
    },
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
50
    // NAPTR(NAPTR),
51
52
53
54
55
56
57
58
    #[serde(rename_all = "PascalCase")]
    NULL {
        data: String
    },
    #[serde(rename_all = "PascalCase")]
    NS {
        target: String
    },
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
59
60
    // OPENPGPKEY(OPENPGPKEY),
    // OPT(OPT),
61
62
63
64
65
66
67
68
69
70
71
72
73
74
    #[serde(rename_all = "PascalCase")]
    PTR {
        target: String
    },
    #[serde(rename_all = "PascalCase")]
    SOA {
        master_server_name: String,
        maintainer_name: String,
        refresh: i32,
        retry: i32,
        expire: i32,
        minimum: u32,
        serial: u32
    },
75
76
77
78
79
80
81
82
83
84
85
86
87
    #[serde(rename_all = "PascalCase")]
    SRV {
        server: String,
        port: u16,
        priority: u16,
        weight: u16,
    },
    #[serde(rename_all = "PascalCase")]
    SSHFP {
        algorithm: u8,
        digest_type: u8,
        fingerprint: String,
    },
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
88
89
    // SVCB(SVCB),
    // TLSA(TLSA),
90
91
92
93
    #[serde(rename_all = "PascalCase")]
    TXT {
        text: String
    },
94
95
96
97
98

    // TODO: Eventually allow deserialization of DNSSEC records
    #[serde(skip)]
    DNSSEC(trust_dns_types::DNSSECRData),
    #[serde(rename_all = "PascalCase")]
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
99
100
    Unknown {
        code: u16,
101
        data: String,
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
102
103
104
105
106
107
108
109
110
    },
    // ZERO,
}

impl From<trust_dns_types::RData> for RData {
    fn from(rdata: trust_dns_types::RData) -> RData {
        match rdata {
            trust_dns_types::RData::A(address) => RData::A { address },
            trust_dns_types::RData::AAAA(address) => RData::AAAA { address },
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
            // Still a draft, no iana number yet, I don't to put something that is not currently supported so that's why NULL and not unknown.
            // TODO: probably need better error here, I don't know what to do about that as this would require to change the From for something else.
            // (empty data because I'm lazy)
            trust_dns_types::RData::ANAME(_) =>  RData::NULL {
                data: String::new()
            },
            trust_dns_types::RData::CNAME(target) => RData::CNAME {
                target: target.to_utf8()
            },
            trust_dns_types::RData::CAA(caa) => RData::CAA {
                issuer_critical: caa.issuer_critical(),
                value: format!("{}", CAAValue(caa.value())),
                property_tag: caa.tag().as_str().to_string(),
            },
            trust_dns_types::RData::MX(mx) => RData::MX {
                preference: mx.preference(),
                mail_exchanger: mx.exchange().to_utf8()
            },
            trust_dns_types::RData::NULL(null) =>  RData::NULL {
                data: base64::encode(null.anything().map(|data| data.to_vec()).unwrap_or_default())
            },
            trust_dns_types::RData::NS(target) => RData::NS {
                target: target.to_utf8()
            },
            trust_dns_types::RData::PTR(target) => RData::PTR {
                target: target.to_utf8()
            },
            trust_dns_types::RData::SOA(soa) => RData::SOA {
                master_server_name: soa.mname().to_utf8(),
                maintainer_name: soa.rname().to_utf8(),
                refresh: soa.refresh(),
                retry: soa.retry(),
                expire: soa.expire(),
                minimum: soa.minimum(),
                serial: soa.serial()
            },
147
148
149
150
151
152
153
154
155
156
157
158
            trust_dns_types::RData::SRV(srv) => RData::SRV {
                server: srv.target().to_utf8(),
                port: srv.port(),
                priority: srv.priority(),
                weight: srv.weight(),
            },
            trust_dns_types::RData::SSHFP(sshfp) => RData::SSHFP {
                algorithm: sshfp.algorithm().into(),
                digest_type: sshfp.fingerprint_type().into(),
                fingerprint: trust_dns_types::sshfp::HEX.encode(sshfp.fingerprint()),
            },
            trust_dns_types::RData::TXT(txt) => RData::TXT { text: format!("{}", txt) },
159
160
161
162
163
            trust_dns_types::RData::DNSSEC(data) => RData::DNSSEC(data),
            rdata => {
                let code = rdata.to_record_type().into();
                let mut data = Vec::new();
                let mut encoder = BinEncoder::new(&mut data);
164
                // TODO: need better error handling (use TryFrom ?)
165
166
167
168
169
170
171
                rdata.emit(&mut encoder).expect("could not encode data");

                RData::Unknown {
                    code,
                    data: base64::encode(data),
                }
            }
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
172
173
174
175
        }
    }
}

176
struct CAAValue<'a>(&'a trust_dns_types::caa::Value);
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
177

178
179
180
181
182
183
184
// trust_dns Display implementation panics if no parameters
// Implementation based on caa::emit_value
// Also the quotes are strips to render in JSON
impl<'a> fmt::Display for CAAValue<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        match self.0 {
            trust_dns_types::caa::Value::Issuer(name, parameters) => {
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
185

186
187
188
                if let Some(name) = name {
                    write!(f, "{}", name)?;
                }
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
189

190
191
192
                if name.is_none() && parameters.is_empty() {
                    write!(f, ";")?;
                }
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
193

194
195
196
197
198
199
                for value in parameters {
                    write!(f, "; {}", value)?;
                }
            }
            trust_dns_types::caa::Value::Url(url) => write!(f, "{}", url)?,
            trust_dns_types::caa::Value::Unknown(v) => write!(f, "{:?}", v)?,
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
200
        }
201
        Ok(())
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
    }
}

#[derive(Deserialize, Serialize)]
pub enum DNSClass {
    IN,
    CH,
    HS,
    NONE,
    ANY,
    OPT(u16),
}

impl From<trust_dns_types::DNSClass> for DNSClass {
    fn from(dns_class: trust_dns_types::DNSClass) -> DNSClass {
        match dns_class {
            trust_dns_types::DNSClass::IN => DNSClass::IN,
            trust_dns_types::DNSClass::CH => DNSClass::CH,
            trust_dns_types::DNSClass::HS => DNSClass::HS,
            trust_dns_types::DNSClass::NONE => DNSClass::NONE,
            trust_dns_types::DNSClass::ANY => DNSClass::ANY,
            trust_dns_types::DNSClass::OPT(v) => DNSClass::OPT(v),
        }
    }
}


#[derive(Deserialize, Serialize)]
pub struct Record {
    #[serde(rename = "Name")]
232
    pub name: String,
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
233
    #[serde(rename = "Class")]
234
    pub dns_class: DNSClass,
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
235
    #[serde(rename = "TTL")]
236
    pub ttl: u32,
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
237
    #[serde(flatten)]
238
    pub rdata: RData,
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
239
240
241
242
243
}

impl From<trust_dns_types::Record> for Record {
    fn from(record: trust_dns_types::Record) -> Record {
        Record {
244
            name: record.name().to_utf8(),
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
245
246
247
248
249
250
251
            //rr_type: record.rr_type().into(),
            dns_class: record.dns_class().into(),
            ttl: record.ttl(),
            rdata: record.into_data().into(),
        }
    }
}
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312

pub struct AbsoluteName(Name);

impl<'r> FromParam<'r> for AbsoluteName {
    type Error = ProtoError;

    fn from_param(param: &'r str) -> Result<Self, Self::Error> {
        let mut name = Name::from_utf8(&param).unwrap();
        if !name.is_fqdn() {
            name.set_fqdn(true);
        }
        Ok(AbsoluteName(name))
    }
}

impl Deref for AbsoluteName {
    type Target = Name;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

pub struct DnsClient(AsyncClient);

impl Deref for DnsClient {
    type Target = AsyncClient;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl DerefMut for DnsClient {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}


#[rocket::async_trait]
impl<'r> FromRequest<'r> for DnsClient {
    type Error = ();
    async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
        let config = try_outcome!(request.guard::<State<Config>>().await);
        let (stream, handle) = TcpClientStream::<AsyncIoTokioAsStd<TokioTcpStream>>::new(config.dns.server);
        let client = AsyncClient::with_timeout(
            stream,
            handle,
            std::time::Duration::from_secs(5),
            None);
        let (client, bg) = match client.await {
            Err(e) => {
                println!("Failed to connect to DNS server {:#?}", e);
                return Outcome::Failure((Status::InternalServerError, ()))
            },
            Ok(c) => c
        };
        task::spawn(bg);
        Outcome::Success(DnsClient(client))
    }
}