wire.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. //! Parsing the DNS wire protocol.
  2. pub(crate) use std::io::{Cursor, Read};
  3. pub(crate) use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
  4. use std::io;
  5. use log::*;
  6. use crate::record::{Record, RecordType, OPT};
  7. use crate::strings::{Labels, ReadLabels, WriteLabels};
  8. use crate::types::*;
  9. impl Request {
  10. /// Converts this request to a vector of bytes.
  11. pub fn to_bytes(&self) -> io::Result<Vec<u8>> {
  12. let mut bytes = Vec::with_capacity(32);
  13. bytes.write_u16::<BigEndian>(self.transaction_id)?;
  14. bytes.write_u16::<BigEndian>(self.flags.to_u16())?;
  15. bytes.write_u16::<BigEndian>(1)?; // query count
  16. bytes.write_u16::<BigEndian>(0)?; // answer count
  17. bytes.write_u16::<BigEndian>(0)?; // authority RR count
  18. bytes.write_u16::<BigEndian>(if self.additional.is_some() { 1 } else { 0 })?; // additional RR count
  19. bytes.write_labels(&self.query.qname)?;
  20. bytes.write_u16::<BigEndian>(self.query.qtype.type_number())?;
  21. bytes.write_u16::<BigEndian>(self.query.qclass.to_u16())?;
  22. if let Some(opt) = &self.additional {
  23. bytes.write_u8(0)?; // usually a name
  24. bytes.write_u16::<BigEndian>(OPT::RR_TYPE)?;
  25. bytes.extend(opt.to_bytes()?);
  26. }
  27. Ok(bytes)
  28. }
  29. /// Returns the OPT record to be sent as part of requests.
  30. pub fn additional_record() -> OPT {
  31. OPT {
  32. udp_payload_size: 512,
  33. higher_bits: 0,
  34. edns0_version: 0,
  35. flags: 0,
  36. data: Vec::new(),
  37. }
  38. }
  39. }
  40. impl Response {
  41. /// Reads bytes off of the given slice, parsing them into a response.
  42. #[cfg_attr(feature = "with_mutagen", ::mutagen::mutate)]
  43. pub fn from_bytes(bytes: &[u8]) -> Result<Self, WireError> {
  44. info!("Parsing response");
  45. trace!("Bytes -> {:?}", bytes);
  46. let mut c = Cursor::new(bytes);
  47. let transaction_id = c.read_u16::<BigEndian>()?;
  48. trace!("Read txid -> {:?}", transaction_id);
  49. let flags = Flags::from_u16(c.read_u16::<BigEndian>()?);
  50. trace!("Read flags -> {:#?}", flags);
  51. let query_count = c.read_u16::<BigEndian>()?;
  52. let answer_count = c.read_u16::<BigEndian>()?;
  53. let authority_count = c.read_u16::<BigEndian>()?;
  54. let additional_count = c.read_u16::<BigEndian>()?;
  55. let mut queries = Vec::new();
  56. debug!("Reading {}x query from response", query_count);
  57. for _ in 0 .. query_count {
  58. let (qname, _) = c.read_labels()?;
  59. queries.push(Query::from_bytes(qname, &mut c)?);
  60. }
  61. let mut answers = Vec::new();
  62. debug!("Reading {}x answer from response", answer_count);
  63. for _ in 0 .. answer_count {
  64. let (qname, _) = c.read_labels()?;
  65. answers.push(Answer::from_bytes(qname, &mut c)?);
  66. }
  67. let mut authorities = Vec::new();
  68. debug!("Reading {}x authority from response", authority_count);
  69. for _ in 0 .. authority_count {
  70. let (qname, _) = c.read_labels()?;
  71. authorities.push(Answer::from_bytes(qname, &mut c)?);
  72. }
  73. let mut additionals = Vec::new();
  74. debug!("Reading {}x additional answer from response", additional_count);
  75. for _ in 0 .. additional_count {
  76. let (qname, _) = c.read_labels()?;
  77. additionals.push(Answer::from_bytes(qname, &mut c)?);
  78. }
  79. Ok(Self { transaction_id, flags, queries, answers, authorities, additionals })
  80. }
  81. }
  82. impl Query {
  83. /// Reads bytes from the given cursor, and parses them into a query with
  84. /// the given domain name.
  85. #[cfg_attr(feature = "with_mutagen", ::mutagen::mutate)]
  86. fn from_bytes(qname: Labels, c: &mut Cursor<&[u8]>) -> Result<Self, WireError> {
  87. let qtype_number = c.read_u16::<BigEndian>()?;
  88. trace!("Read qtype number -> {:?}", qtype_number );
  89. let qtype = RecordType::from(qtype_number);
  90. trace!("Found qtype -> {:?}", qtype );
  91. let qclass = QClass::from_u16(c.read_u16::<BigEndian>()?);
  92. trace!("Read qclass -> {:?}", qtype);
  93. Ok(Self { qtype, qclass, qname })
  94. }
  95. }
  96. impl Answer {
  97. /// Reads bytes from the given cursor, and parses them into an answer with
  98. /// the given domain name.
  99. #[cfg_attr(feature = "with_mutagen", ::mutagen::mutate)]
  100. fn from_bytes(qname: Labels, c: &mut Cursor<&[u8]>) -> Result<Self, WireError> {
  101. let qtype_number = c.read_u16::<BigEndian>()?;
  102. trace!("Read qtype number -> {:?}", qtype_number );
  103. if qtype_number == OPT::RR_TYPE {
  104. let opt = OPT::read(c)?;
  105. Ok(Self::Pseudo { qname, opt })
  106. }
  107. else {
  108. let qtype = RecordType::from(qtype_number);
  109. trace!("Found qtype -> {:?}", qtype );
  110. let qclass = QClass::from_u16(c.read_u16::<BigEndian>()?);
  111. trace!("Read qclass -> {:?}", qtype);
  112. let ttl = c.read_u32::<BigEndian>()?;
  113. trace!("Read TTL -> {:?}", ttl);
  114. let record_length = c.read_u16::<BigEndian>()?;
  115. trace!("Read record length -> {:?}", record_length);
  116. let record = Record::from_bytes(qtype, record_length, c)?;
  117. Ok(Self::Standard { qclass, qname, record, ttl })
  118. }
  119. }
  120. }
  121. impl Record {
  122. /// Reads at most `len` bytes from the given curser, and parses them into
  123. /// a record structure depending on the type number, which has already been read.
  124. #[cfg_attr(feature = "with_mutagen", ::mutagen::mutate)]
  125. fn from_bytes(record_type: RecordType, len: u16, c: &mut Cursor<&[u8]>) -> Result<Self, WireError> {
  126. if cfg!(feature = "with_mutagen") {
  127. warn!("Mutation is enabled!");
  128. }
  129. macro_rules! read_record {
  130. ($record:tt) => { {
  131. info!("Parsing {} record (type {}, len {})", crate::record::$record::NAME, record_type.type_number(), len);
  132. Wire::read(len, c).map(Self::$record)
  133. } }
  134. }
  135. match record_type {
  136. RecordType::A => read_record!(A),
  137. RecordType::AAAA => read_record!(AAAA),
  138. RecordType::CAA => read_record!(CAA),
  139. RecordType::CNAME => read_record!(CNAME),
  140. RecordType::EUI48 => read_record!(EUI48),
  141. RecordType::EUI64 => read_record!(EUI64),
  142. RecordType::HINFO => read_record!(HINFO),
  143. RecordType::LOC => read_record!(LOC),
  144. RecordType::MX => read_record!(MX),
  145. RecordType::NAPTR => read_record!(NAPTR),
  146. RecordType::NS => read_record!(NS),
  147. RecordType::OPENPGPKEY => read_record!(OPENPGPKEY),
  148. RecordType::PTR => read_record!(PTR),
  149. RecordType::SSHFP => read_record!(SSHFP),
  150. RecordType::SOA => read_record!(SOA),
  151. RecordType::SRV => read_record!(SRV),
  152. RecordType::TLSA => read_record!(TLSA),
  153. RecordType::TXT => read_record!(TXT),
  154. RecordType::URI => read_record!(URI),
  155. RecordType::Other(type_number) => {
  156. let mut bytes = Vec::new();
  157. for _ in 0 .. len {
  158. bytes.push(c.read_u8()?);
  159. }
  160. Ok(Self::Other { type_number, bytes })
  161. }
  162. }
  163. }
  164. }
  165. impl QClass {
  166. fn from_u16(uu: u16) -> Self {
  167. match uu {
  168. 0x0001 => Self::IN,
  169. 0x0003 => Self::CH,
  170. 0x0004 => Self::HS,
  171. _ => Self::Other(uu),
  172. }
  173. }
  174. fn to_u16(self) -> u16 {
  175. match self {
  176. Self::IN => 0x0001,
  177. Self::CH => 0x0003,
  178. Self::HS => 0x0004,
  179. Self::Other(uu) => uu,
  180. }
  181. }
  182. }
  183. impl Flags {
  184. /// The set of flags that represents a query packet.
  185. pub fn query() -> Self {
  186. Self::from_u16(0b_0000_0001_0000_0000)
  187. }
  188. /// The set of flags that represents a successful response.
  189. pub fn standard_response() -> Self {
  190. Self::from_u16(0b_1000_0001_1000_0000)
  191. }
  192. /// Converts the flags into a two-byte number.
  193. pub fn to_u16(self) -> u16 { // 0123 4567 89AB CDEF
  194. let mut bits = 0b_0000_0000_0000_0000;
  195. if self.response { bits |= 0b_1000_0000_0000_0000; }
  196. match self.opcode {
  197. Opcode::Query => { bits |= 0b_0000_0000_0000_0000; }
  198. Opcode::Other(_) => { unimplemented!(); }
  199. }
  200. if self.authoritative { bits |= 0b_0000_0100_0000_0000; }
  201. if self.truncated { bits |= 0b_0000_0010_0000_0000; }
  202. if self.recursion_desired { bits |= 0b_0000_0001_0000_0000; }
  203. if self.recursion_available { bits |= 0b_0000_0000_1000_0000; }
  204. // (the Z bit is reserved) 0b_0000_0000_0100_0000
  205. if self.authentic_data { bits |= 0b_0000_0000_0010_0000; }
  206. if self.checking_disabled { bits |= 0b_0000_0000_0001_0000; }
  207. bits
  208. }
  209. /// Extracts the flags from the given two-byte number.
  210. pub fn from_u16(bits: u16) -> Self {
  211. let has_bit = |bit| { bits & bit == bit };
  212. Self {
  213. response: has_bit(0b_1000_0000_0000_0000),
  214. opcode: Opcode::from_bits((bits.to_be_bytes()[0] & 0b_0111_1000) >> 3),
  215. authoritative: has_bit(0b_0000_0100_0000_0000),
  216. truncated: has_bit(0b_0000_0010_0000_0000),
  217. recursion_desired: has_bit(0b_0000_0001_0000_0000),
  218. recursion_available: has_bit(0b_0000_0000_1000_0000),
  219. authentic_data: has_bit(0b_0000_0000_0010_0000),
  220. checking_disabled: has_bit(0b_0000_0000_0001_0000),
  221. error_code: ErrorCode::from_bits(bits & 0b_1111),
  222. }
  223. }
  224. }
  225. impl Opcode {
  226. /// Extracts the opcode from this four-bit number, which should have been
  227. /// extracted from the packet and shifted to be in the range 0–15.
  228. fn from_bits(bits: u8) -> Self {
  229. if bits == 0 {
  230. Self::Query
  231. }
  232. else {
  233. assert!(bits <= 15, "bits {:#08b} out of range", bits);
  234. Self::Other(bits)
  235. }
  236. }
  237. }
  238. impl ErrorCode {
  239. /// Extracts the rcode from the last four bits of the flags field.
  240. fn from_bits(bits: u16) -> Option<Self> {
  241. if (0x0F01 .. 0x0FFF).contains(&bits) {
  242. return Some(Self::Private(bits));
  243. }
  244. match bits {
  245. 0 => None,
  246. 1 => Some(Self::FormatError),
  247. 2 => Some(Self::ServerFailure),
  248. 3 => Some(Self::NXDomain),
  249. 4 => Some(Self::NotImplemented),
  250. 5 => Some(Self::QueryRefused),
  251. 16 => Some(Self::BadVersion),
  252. n => Some(Self::Other(n)),
  253. }
  254. }
  255. }
  256. /// Trait for decoding DNS record structures from bytes read over the wire.
  257. pub trait Wire: Sized {
  258. /// This record’s type as a string, such as `"A"` or `"CNAME"`.
  259. const NAME: &'static str;
  260. /// The number signifying that a record is of this type.
  261. /// See <https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-4>
  262. const RR_TYPE: u16;
  263. /// Read at most `len` bytes from the given `Cursor`. This cursor travels
  264. /// throughout the complete data — by this point, we have read the entire
  265. /// response into a buffer.
  266. fn read(len: u16, c: &mut Cursor<&[u8]>) -> Result<Self, WireError>;
  267. }
  268. /// Something that can go wrong deciphering a record.
  269. #[derive(PartialEq, Debug)]
  270. pub enum WireError {
  271. /// There was an IO error reading from the cursor.
  272. /// Almost all the time, this means that the buffer was too short.
  273. IO,
  274. // (io::Error is not PartialEq so we don’t propagate it)
  275. /// When the DNS standard requires records of this type to have a certain
  276. /// fixed length, but the response specified a different length.
  277. ///
  278. /// This error should be returned regardless of the _content_ of the
  279. /// record, whatever it is.
  280. WrongRecordLength {
  281. /// The length of the record’s data, as specified in the packet.
  282. stated_length: u16,
  283. /// The length of the record that the DNS specification mandates.
  284. mandated_length: MandatedLength,
  285. },
  286. /// When the length of this record as specified in the packet differs from
  287. /// the computed length, as determined by reading labels.
  288. ///
  289. /// There are two ways, in general, to read arbitrary-length data from a
  290. /// stream of bytes: length-prefixed (read the length, then read that many
  291. /// bytes) or sentinel-terminated (keep reading bytes until you read a
  292. /// certain value, usually zero). The DNS protocol uses both: each
  293. /// record’s size is specified up-front in the packet, but inside the
  294. /// record, there exist arbitrary-length strings that must be read until a
  295. /// zero is read, indicating there is no more string.
  296. ///
  297. /// Consider the case of a packet, with a specified length, containing a
  298. /// string of arbitrary length (such as the CNAME or TXT records). A DNS
  299. /// client has to deal with this in one of two ways:
  300. ///
  301. /// 1. Read exactly the specified length of bytes from the record, raising
  302. /// an error if the contents are too short or a string keeps going past
  303. /// the length (assume the length is correct but the contents are wrong).
  304. ///
  305. /// 2. Read as many bytes from the record as the string requests, raising
  306. /// an error if the number of bytes read at the end differs from the
  307. /// expected length of the record (assume the length is wrong but the
  308. /// contents are correct).
  309. ///
  310. /// Note that no matter which way is picked, the record will still be
  311. /// incorrect — it only impacts the parsing of records that occur after it
  312. /// in the packet. Knowing which method should be used requires knowing
  313. /// what caused the DNS packet to be erroneous, which we cannot know.
  314. ///
  315. /// dog picks the second way. If a record ends up reading more or fewer
  316. /// bytes than it is ‘supposed’ to, it will raise this error, but _after_
  317. /// having read a different number of bytes than the specified length.
  318. WrongLabelLength {
  319. /// The length of the record’s data, as specified in the packet.
  320. stated_length: u16,
  321. /// The computed length of the record’s data, based on the number of
  322. /// bytes consumed by reading labels from the packet.
  323. length_after_labels: u16,
  324. },
  325. /// When the data contained a string containing a cycle of pointers.
  326. /// Contains the vector of indexes that was being checked.
  327. TooMuchRecursion(Vec<u16>),
  328. /// When the data contained a string with a pointer to an index outside of
  329. /// the packet. Contains the invalid index.
  330. OutOfBounds(u16),
  331. /// When a record in the packet contained a version field that specifies
  332. /// the format of its remaining fields, but this version is too recent to
  333. /// be supported, so we cannot parse it.
  334. WrongVersion {
  335. /// The version of the record layout, as specified in the packet
  336. stated_version: u8,
  337. /// The maximum version that this version of dog supports.
  338. maximum_supported_version: u8,
  339. }
  340. }
  341. /// The rule for how long a record in a packet should be.
  342. #[derive(PartialEq, Debug, Copy, Clone)]
  343. pub enum MandatedLength {
  344. /// The record should be exactly this many bytes in length.
  345. Exactly(u16),
  346. /// The record should be _at least_ this many bytes in length.
  347. AtLeast(u16),
  348. }
  349. impl From<io::Error> for WireError {
  350. fn from(ioe: io::Error) -> Self {
  351. error!("IO error -> {:?}", ioe);
  352. Self::IO
  353. }
  354. }