/
util.rs
285 lines (252 loc) · 8.56 KB
/
util.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
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
// Copyright 2021 Fastly, Inc.
use anyhow::{bail, Result};
use bytes::{Buf, BufMut, Bytes, BytesMut};
use std::convert::TryFrom;
use std::net::IpAddr;
use thiserror::Error;
/// Utility function that converts a slice of bytes into an [`IpAddr`]. Slices of length 4 are
/// converted to IPv4 addresses and slices of length 16 are converted to IPv6 addresses. All other
/// slice lengths are invalid. This is how IP addresses are encoded in dnstap protobuf messages.
pub fn try_from_u8_slice_for_ipaddr(value: &[u8]) -> Result<IpAddr> {
match value.len() {
4 => Ok(IpAddr::from(<[u8; 4]>::try_from(value)?)),
16 => Ok(IpAddr::from(<[u8; 16]>::try_from(value)?)),
_ => bail!(
"Cannot decode an IP address from a {} byte field",
value.len()
),
}
}
#[derive(Debug, Error, PartialEq)]
pub enum DnstapHandlerError {
#[error("Mismatch between logged dnstap response and re-queried DNS response, expecting {1} but received {2}")]
Mismatch(Bytes, String, String),
#[error("Timeout sending DNS query")]
Timeout,
#[error("dnstap payload is missing a required field")]
MissingField,
}
const DNSTAP_HANDLER_ERROR_PREFIX: &[u8] = b"dnstap-replay/DnstapHandlerError\x00";
impl DnstapHandlerError {
pub fn serialize(&self) -> Bytes {
match self {
DnstapHandlerError::Mismatch(mismatch, _, _) => {
let mut b =
BytesMut::with_capacity(DNSTAP_HANDLER_ERROR_PREFIX.len() + 4 + mismatch.len());
b.extend_from_slice(DNSTAP_HANDLER_ERROR_PREFIX);
b.put_u32(1);
b.extend_from_slice(mismatch);
b
}
DnstapHandlerError::Timeout => {
let mut b = BytesMut::with_capacity(DNSTAP_HANDLER_ERROR_PREFIX.len() + 4);
b.extend_from_slice(DNSTAP_HANDLER_ERROR_PREFIX);
b.put_u32(2);
b
}
DnstapHandlerError::MissingField => {
let mut b = BytesMut::with_capacity(DNSTAP_HANDLER_ERROR_PREFIX.len() + 4);
b.extend_from_slice(DNSTAP_HANDLER_ERROR_PREFIX);
b.put_u32(3);
b
}
}
.freeze()
}
}
pub fn deserialize_dnstap_handler_error(input: &[u8]) -> Result<DnstapHandlerError> {
if input.len() < DNSTAP_HANDLER_ERROR_PREFIX.len() {
bail!("Input buffer is too small");
}
let mut buf = Bytes::copy_from_slice(input);
let prefix = buf.copy_to_bytes(DNSTAP_HANDLER_ERROR_PREFIX.len());
if prefix != DNSTAP_HANDLER_ERROR_PREFIX {
bail!("DnstapHandlerError prefix not present");
}
if buf.remaining() < 4 {
bail!("DnstapHandlerError type not present");
}
match buf.get_u32() {
1 => Ok(DnstapHandlerError::Mismatch(
buf.split_off(0),
String::from(""),
String::from(""),
)),
2 => Ok(DnstapHandlerError::Timeout),
3 => Ok(DnstapHandlerError::MissingField),
_ => {
bail!("Unknown DnstapHandlerError type");
}
}
}
#[test]
fn test_deserialize_dnstap_handler_error() {
// Test the extreme boundary condition. This is a minimally sized serialized
// DnstapHandlerError::Mismatch.
assert_eq!(
deserialize_dnstap_handler_error(b"dnstap-replay/DnstapHandlerError\x00\x00\x00\x00\x01")
.unwrap(),
DnstapHandlerError::Mismatch(Bytes::from(&b""[..]), String::from(""), String::from(""))
);
// This is the smallest serialized DnstapHandlerError::Mismatch with a single byte payload.
assert_eq!(
deserialize_dnstap_handler_error(
b"dnstap-replay/DnstapHandlerError\x00\x00\x00\x00\x01\x42"
)
.unwrap(),
DnstapHandlerError::Mismatch(
Bytes::from(&b"\x42"[..]),
String::from(""),
String::from("")
)
);
// The only way to serialize a DnstapHandlerError::Timeout.
assert_eq!(
deserialize_dnstap_handler_error(b"dnstap-replay/DnstapHandlerError\x00\x00\x00\x00\x02")
.unwrap(),
DnstapHandlerError::Timeout
);
// The only way to serialize a DnstapHandlerError::MissingField.
assert_eq!(
deserialize_dnstap_handler_error(b"dnstap-replay/DnstapHandlerError\x00\x00\x00\x00\x03")
.unwrap(),
DnstapHandlerError::MissingField
);
}
pub fn fmt_dns_message(s: &mut String, prefix: &str, raw_msg_bytes: &[u8]) {
use domain::base::iana::rtype::Rtype;
use domain::base::Message;
use domain::rdata::AllRecordData;
let msg = match Message::from_octets(raw_msg_bytes) {
Ok(msg) => msg,
Err(err) => {
s.push_str(prefix);
s.push_str(";; PARSE ERROR: ");
s.push_str(&err.to_string());
s.push('\n');
return;
}
};
let hdr = msg.header();
// opcode
s.push_str(prefix);
s.push_str(";; ->>HEADER<<- opcode: ");
s.push_str(&hdr.opcode().to_string());
// rcode
s.push_str(", rcode: ");
s.push_str(&hdr.rcode().to_string());
// id
s.push_str(", id: ");
s.push_str(&hdr.id().to_string());
s.push('\n');
// flags
s.push_str(prefix);
s.push_str(";; flags: ");
if hdr.qr() {
s.push_str("qr ");
}
if hdr.aa() {
s.push_str("aa ");
}
if hdr.tc() {
s.push_str("tc ");
}
if hdr.rd() {
s.push_str("rd ");
}
if hdr.ra() {
s.push_str("ra ");
}
if hdr.ad() {
s.push_str("ad ");
}
if hdr.cd() {
s.push_str("cd ");
}
// header counts
let hdr_counts = msg.header_counts();
s.push_str("; QUERY: ");
s.push_str(&hdr_counts.qdcount().to_string());
s.push_str(", ANSWER: ");
s.push_str(&hdr_counts.ancount().to_string());
s.push_str(", AUTHORITY: ");
s.push_str(&hdr_counts.nscount().to_string());
s.push_str(", ADDITIONAL: ");
s.push_str(&hdr_counts.adcount().to_string());
s.push_str("\n\n");
if let Ok(sections) = msg.sections() {
s.push_str(prefix);
s.push_str(";; QUESTION SECTION:\n");
for question in sections.0.flatten() {
s.push_str(prefix);
s.push(';');
s.push_str(&question.qname().to_string());
s.push_str(". ");
s.push_str(&question.qclass().to_string());
s.push(' ');
s.push_str(&question.qtype().to_string());
s.push('\n')
}
s.push('\n');
s.push_str(prefix);
s.push_str(";; ANSWER SECTION:\n");
for record in sections.1.limit_to::<AllRecordData<_, _>>().flatten() {
s.push_str(prefix);
s.push_str(&record.to_string());
s.push('\n')
}
s.push('\n');
s.push_str(prefix);
s.push_str(";; AUTHORITY SECTION:\n");
for record in sections.2.limit_to::<AllRecordData<_, _>>().flatten() {
s.push_str(prefix);
s.push_str(&record.to_string());
s.push('\n')
}
s.push('\n');
s.push_str(prefix);
s.push_str(";; ADDITIONAL SECTION:\n");
for record in sections.3.limit_to::<AllRecordData<_, _>>().flatten() {
if record.rtype() == Rtype::Opt {
continue;
}
s.push_str(prefix);
s.push_str(&record.to_string());
s.push('\n')
}
if let Some(opt) = msg.opt() {
s.push('\n');
s.push_str(prefix);
s.push_str(";; EDNS: version ");
s.push_str(&opt.version().to_string());
s.push_str("; flags: ");
if opt.dnssec_ok() {
s.push_str("do ");
}
s.push_str("; udp: ");
s.push_str(&opt.udp_payload_size().to_string());
s.push('\n');
}
}
}
pub fn dns_message_is_truncated(raw_msg_bytes: &[u8]) -> bool {
// Only check a message if the complete header (12 octets) was received.
if raw_msg_bytes.len() >= 12 {
let msg = domain::base::Header::for_message_slice(raw_msg_bytes);
return msg.tc();
}
false
}
#[test]
fn test_dns_message_is_truncated() {
// Too few bytes to be a complete DNS header.
assert!(!dns_message_is_truncated(&hex::decode("1234").unwrap()));
// Real DNS header with the TC bit set.
assert!(dns_message_is_truncated(
&hex::decode("b84587000001000000000001").unwrap()
));
// Real DNS header with the TC bit unset.
assert!(!dns_message_is_truncated(
&hex::decode("b84585000001000000010001").unwrap()
));
}