4
0

wire.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  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, 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)?;
  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 = c.read_u16::<BigEndian>()?;
  88. trace!("Read qtype -> {:?}", qtype);
  89. let qclass = QClass::from_u16(c.read_u16::<BigEndian>()?);
  90. trace!("Read qclass -> {:?}", qtype);
  91. Ok(Self { qtype, qclass, qname })
  92. }
  93. }
  94. impl Answer {
  95. /// Reads bytes from the given cursor, and parses them into an answer with
  96. /// the given domain name.
  97. #[cfg_attr(feature = "with_mutagen", ::mutagen::mutate)]
  98. fn from_bytes(qname: Labels, c: &mut Cursor<&[u8]>) -> Result<Self, WireError> {
  99. let qtype = c.read_u16::<BigEndian>()?;
  100. trace!("Read qtype -> {:?}", qtype);
  101. if qtype == OPT::RR_TYPE {
  102. let opt = OPT::read(c)?;
  103. Ok(Self::Pseudo { qname, opt })
  104. }
  105. else {
  106. let qclass = QClass::from_u16(c.read_u16::<BigEndian>()?);
  107. trace!("Read qclass -> {:?}", qtype);
  108. let ttl = c.read_u32::<BigEndian>()?;
  109. trace!("Read TTL -> {:?}", ttl);
  110. let record_length = c.read_u16::<BigEndian>()?;
  111. trace!("Read record length -> {:?}", record_length);
  112. let record = Record::from_bytes(qtype, record_length, c)?;
  113. Ok(Self::Standard { qclass, qname, record, ttl })
  114. }
  115. }
  116. }
  117. impl Record {
  118. /// Reads at most `len` bytes from the given curser, and parses them into
  119. /// a record structure depending on the type number, which has already been read.
  120. #[cfg_attr(feature = "with_mutagen", ::mutagen::mutate)]
  121. fn from_bytes(qtype: TypeInt, len: u16, c: &mut Cursor<&[u8]>) -> Result<Self, WireError> {
  122. use crate::record::*;
  123. if cfg!(feature = "with_mutagen") {
  124. warn!("Mutation is enabled!");
  125. }
  126. macro_rules! try_record {
  127. ($record:tt) => {
  128. if $record::RR_TYPE == qtype {
  129. info!("Parsing {} record (type {}, len {})", $record::NAME, qtype, len);
  130. return Wire::read(len, c).map(Self::$record)
  131. }
  132. }
  133. }
  134. // Try all the records, one type at a time, returning early if the
  135. // type number matches.
  136. try_record!(A);
  137. try_record!(AAAA);
  138. try_record!(CAA);
  139. try_record!(CNAME);
  140. try_record!(EUI48);
  141. try_record!(HINFO);
  142. try_record!(LOC);
  143. try_record!(MX);
  144. try_record!(NAPTR);
  145. try_record!(NS);
  146. try_record!(OPENPGPKEY);
  147. // OPT is handled separately
  148. try_record!(PTR);
  149. try_record!(SSHFP);
  150. try_record!(SOA);
  151. try_record!(SRV);
  152. try_record!(TLSA);
  153. try_record!(TXT);
  154. try_record!(URI);
  155. // Otherwise, collect the bytes into a vector and return an unknown
  156. // record type.
  157. let mut bytes = Vec::new();
  158. for _ in 0 .. len {
  159. bytes.push(c.read_u8()?);
  160. }
  161. let type_number = UnknownQtype::from(qtype);
  162. Ok(Self::Other { type_number, bytes })
  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. /// Determines the record type number to signify a record with the given name.
  184. pub fn find_qtype_number(record_type: &str) -> Option<TypeInt> {
  185. use crate::record::*;
  186. macro_rules! try_record {
  187. ($record:tt) => {
  188. if $record::NAME == record_type {
  189. return Some($record::RR_TYPE);
  190. }
  191. }
  192. }
  193. try_record!(A);
  194. try_record!(AAAA);
  195. try_record!(CAA);
  196. try_record!(CNAME);
  197. try_record!(EUI48);
  198. try_record!(HINFO);
  199. try_record!(LOC);
  200. try_record!(MX);
  201. try_record!(NAPTR);
  202. try_record!(NS);
  203. try_record!(OPENPGPKEY);
  204. // OPT is elsewhere
  205. try_record!(PTR);
  206. try_record!(SSHFP);
  207. try_record!(SOA);
  208. try_record!(SRV);
  209. try_record!(TLSA);
  210. try_record!(TXT);
  211. try_record!(URI);
  212. None
  213. }
  214. impl Flags {
  215. /// The set of flags that represents a query packet.
  216. pub fn query() -> Self {
  217. Self::from_u16(0b_0000_0001_0000_0000)
  218. }
  219. /// The set of flags that represents a successful response.
  220. pub fn standard_response() -> Self {
  221. Self::from_u16(0b_1000_0001_1000_0000)
  222. }
  223. /// Converts the flags into a two-byte number.
  224. pub fn to_u16(self) -> u16 { // 0123 4567 89AB CDEF
  225. let mut bits = 0b_0000_0000_0000_0000;
  226. if self.response { bits |= 0b_1000_0000_0000_0000; }
  227. match self.opcode {
  228. Opcode::Query => { bits |= 0b_0000_0000_0000_0000; }
  229. Opcode::Other(_) => { unimplemented!(); }
  230. }
  231. if self.authoritative { bits |= 0b_0000_0100_0000_0000; }
  232. if self.truncated { bits |= 0b_0000_0010_0000_0000; }
  233. if self.recursion_desired { bits |= 0b_0000_0001_0000_0000; }
  234. if self.recursion_available { bits |= 0b_0000_0000_1000_0000; }
  235. // (the Z bit is reserved) 0b_0000_0000_0100_0000
  236. if self.authentic_data { bits |= 0b_0000_0000_0010_0000; }
  237. if self.checking_disabled { bits |= 0b_0000_0000_0001_0000; }
  238. bits
  239. }
  240. /// Extracts the flags from the given two-byte number.
  241. pub fn from_u16(bits: u16) -> Self {
  242. let has_bit = |bit| { bits & bit == bit };
  243. Self {
  244. response: has_bit(0b_1000_0000_0000_0000),
  245. opcode: Opcode::from_bits((bits.to_be_bytes()[0] & 0b_0111_1000) >> 3),
  246. authoritative: has_bit(0b_0000_0100_0000_0000),
  247. truncated: has_bit(0b_0000_0010_0000_0000),
  248. recursion_desired: has_bit(0b_0000_0001_0000_0000),
  249. recursion_available: has_bit(0b_0000_0000_1000_0000),
  250. authentic_data: has_bit(0b_0000_0000_0010_0000),
  251. checking_disabled: has_bit(0b_0000_0000_0001_0000),
  252. error_code: ErrorCode::from_bits(bits & 0b_1111),
  253. }
  254. }
  255. }
  256. impl Opcode {
  257. /// Extracts the opcode from this four-bit number, which should have been
  258. /// extracted from the packet and shifted to be in the range 0–15.
  259. fn from_bits(bits: u8) -> Self {
  260. if bits == 0 {
  261. Self::Query
  262. }
  263. else {
  264. assert!(bits <= 15, "bits {:#08b} out of range", bits);
  265. Self::Other(bits)
  266. }
  267. }
  268. }
  269. impl ErrorCode {
  270. /// Extracts the rcode from the last four bits of the flags field.
  271. fn from_bits(bits: u16) -> Option<Self> {
  272. if (0x0F01 .. 0x0FFF).contains(&bits) {
  273. return Some(Self::Private(bits));
  274. }
  275. match bits {
  276. 0 => None,
  277. 1 => Some(Self::FormatError),
  278. 2 => Some(Self::ServerFailure),
  279. 3 => Some(Self::NXDomain),
  280. 4 => Some(Self::NotImplemented),
  281. 5 => Some(Self::QueryRefused),
  282. 16 => Some(Self::BadVersion),
  283. n => Some(Self::Other(n)),
  284. }
  285. }
  286. }
  287. /// Trait for decoding DNS record structures from bytes read over the wire.
  288. pub trait Wire: Sized {
  289. /// This record’s type as a string, such as `"A"` or `"CNAME"`.
  290. const NAME: &'static str;
  291. /// The number signifying that a record is of this type.
  292. /// See <https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-4>
  293. const RR_TYPE: u16;
  294. /// Read at most `len` bytes from the given `Cursor`. This cursor travels
  295. /// throughout the complete data — by this point, we have read the entire
  296. /// response into a buffer.
  297. fn read(len: u16, c: &mut Cursor<&[u8]>) -> Result<Self, WireError>;
  298. }
  299. /// Helper macro to get the qtype number of a record type at compile-time.
  300. ///
  301. /// # Examples
  302. ///
  303. /// ```
  304. /// use dns::{qtype, record::MX};
  305. ///
  306. /// assert_eq!(15, qtype!(MX));
  307. /// ```
  308. #[macro_export]
  309. macro_rules! qtype {
  310. ($type:ty) => {
  311. <$type as $crate::Wire>::RR_TYPE
  312. }
  313. }
  314. /// Something that can go wrong deciphering a record.
  315. #[derive(PartialEq, Debug)]
  316. pub enum WireError {
  317. /// There was an IO error reading from the cursor.
  318. /// Almost all the time, this means that the buffer was too short.
  319. IO,
  320. // (io::Error is not PartialEq so we don’t propagate it)
  321. /// When the DNS standard requires records of this type to have a certain
  322. /// fixed length, but the response specified a different length.
  323. ///
  324. /// This error should be returned regardless of the _content_ of the
  325. /// record, whatever it is.
  326. WrongRecordLength {
  327. /// The length of the record’s data, as specified in the packet.
  328. stated_length: u16,
  329. /// The length of the record that the DNS specification mandates.
  330. mandated_length: MandatedLength,
  331. },
  332. /// When the length of this record as specified in the packet differs from
  333. /// the computed length, as determined by reading labels.
  334. ///
  335. /// There are two ways, in general, to read arbitrary-length data from a
  336. /// stream of bytes: length-prefixed (read the length, then read that many
  337. /// bytes) or sentinel-terminated (keep reading bytes until you read a
  338. /// certain value, usually zero). The DNS protocol uses both: each
  339. /// record’s size is specified up-front in the packet, but inside the
  340. /// record, there exist arbitrary-length strings that must be read until a
  341. /// zero is read, indicating there is no more string.
  342. ///
  343. /// Consider the case of a packet, with a specified length, containing a
  344. /// string of arbitrary length (such as the CNAME or TXT records). A DNS
  345. /// client has to deal with this in one of two ways:
  346. ///
  347. /// 1. Read exactly the specified length of bytes from the record, raising
  348. /// an error if the contents are too short or a string keeps going past
  349. /// the length (assume the length is correct but the contents are wrong).
  350. ///
  351. /// 2. Read as many bytes from the record as the string requests, raising
  352. /// an error if the number of bytes read at the end differs from the
  353. /// expected length of the record (assume the length is wrong but the
  354. /// contents are correct).
  355. ///
  356. /// Note that no matter which way is picked, the record will still be
  357. /// incorrect — it only impacts the parsing of records that occur after it
  358. /// in the packet. Knowing which method should be used requires knowing
  359. /// what caused the DNS packet to be erroneous, which we cannot know.
  360. ///
  361. /// dog picks the second way. If a record ends up reading more or fewer
  362. /// bytes than it is ‘supposed’ to, it will raise this error, but _after_
  363. /// having read a different number of bytes than the specified length.
  364. WrongLabelLength {
  365. /// The length of the record’s data, as specified in the packet.
  366. stated_length: u16,
  367. /// The computed length of the record’s data, based on the number of
  368. /// bytes consumed by reading labels from the packet.
  369. length_after_labels: u16,
  370. },
  371. /// When the data contained a string containing a cycle of pointers.
  372. /// Contains the vector of indexes that was being checked.
  373. TooMuchRecursion(Vec<u16>),
  374. /// When the data contained a string with a pointer to an index outside of
  375. /// the packet. Contains the invalid index.
  376. OutOfBounds(u16),
  377. /// When a record in the packet contained a version field that specifies
  378. /// the format of its remaining fields, but this version is too recent to
  379. /// be supported, so we cannot parse it.
  380. WrongVersion {
  381. /// The version of the record layout, as specified in the packet
  382. stated_version: u8,
  383. /// The maximum version that this version of dog supports.
  384. maximum_supported_version: u8,
  385. }
  386. }
  387. /// The rule for how long a record in a packet should be.
  388. #[derive(PartialEq, Debug, Copy, Clone)]
  389. pub enum MandatedLength {
  390. /// The record should be exactly this many bytes in length.
  391. Exactly(u16),
  392. /// The record should be _at least_ this many bytes in length.
  393. AtLeast(u16),
  394. }
  395. impl From<io::Error> for WireError {
  396. fn from(ioe: io::Error) -> Self {
  397. error!("IO error -> {:?}", ioe);
  398. Self::IO
  399. }
  400. }