Modernize samples

This commit is contained in:
Emil Hernvall 2020-06-18 00:45:03 +02:00
parent 2d3db41e33
commit 31369696d9
9 changed files with 1133 additions and 973 deletions

5
.gitignore vendored
View File

@ -1,3 +1,8 @@
*.swp
target
tango.stamp
#Added by cargo
/target

5
Cargo.lock generated Normal file
View File

@ -0,0 +1,5 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
[[package]]
name = "dnsguide"
version = "0.1.0"

9
Cargo.toml Normal file
View File

@ -0,0 +1,9 @@
[package]
name = "dnsguide"
version = "0.1.0"
authors = ["Emil Hernvall <emil@c0la.se>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View File

@ -24,3 +24,18 @@ DNS server, starting from first principles.
* [Chapter 3 - Adding more Record Types](/chapter3.md)
* [Chapter 4 - Baby's first DNS server](/chapter4.md)
* [Chapter 5 - Recursive Resolve](/chapter5.md)
Samples
-------
Each chapter has a corresponding sample which contains the full code up to
that point in the guide, named `sample1.rs` through `sample5.rs`. These can be
run using, for first chapter, `cargo run --example sample1`.
Revision History
----------------
* June 2020 - Fixed a security vulnerability in `read_qname` which allowed for
a malicious packet to trigger an infinite loop. Modernized the code to
conform to current rust pratices.
* July 2016 - Initial version

View File

@ -1,18 +1,20 @@
use std::io::{Result, Read};
use std::io::{Error, ErrorKind};
use std::net::Ipv4Addr;
use std::fs::File;
use std::io::Read;
use std::net::Ipv4Addr;
type Error = Box<dyn std::error::Error>;
type Result<T> = std::result::Result<T, Error>;
pub struct BytePacketBuffer {
pub buf: [u8; 512],
pub pos: usize
pub pos: usize,
}
impl BytePacketBuffer {
pub fn new() -> BytePacketBuffer {
BytePacketBuffer {
buf: [0; 512],
pos: 0
pos: 0,
}
}
@ -34,7 +36,7 @@ impl BytePacketBuffer {
fn read(&mut self) -> Result<u8> {
if self.pos >= 512 {
return Err(Error::new(ErrorKind::InvalidInput, "End of buffer"));
return Err("End of buffer".into());
}
let res = self.buf[self.pos];
self.pos += 1;
@ -44,61 +46,66 @@ impl BytePacketBuffer {
fn get(&mut self, pos: usize) -> Result<u8> {
if pos >= 512 {
return Err(Error::new(ErrorKind::InvalidInput, "End of buffer"));
return Err("End of buffer".into());
}
Ok(self.buf[pos])
}
fn get_range(&mut self, start: usize, len: usize) -> Result<&[u8]> {
if start + len >= 512 {
return Err(Error::new(ErrorKind::InvalidInput, "End of buffer"));
return Err("End of buffer".into());
}
Ok(&self.buf[start..start+len as usize])
Ok(&self.buf[start..start + len as usize])
}
fn read_u16(&mut self) -> Result<u16>
{
let res = ((try!(self.read()) as u16) << 8) |
(try!(self.read()) as u16);
fn read_u16(&mut self) -> Result<u16> {
let res = ((self.read()? as u16) << 8) | (self.read()? as u16);
Ok(res)
}
fn read_u32(&mut self) -> Result<u32>
{
let res = ((try!(self.read()) as u32) << 24) |
((try!(self.read()) as u32) << 16) |
((try!(self.read()) as u32) << 8) |
((try!(self.read()) as u32) << 0);
fn read_u32(&mut self) -> Result<u32> {
let res = ((self.read()? as u32) << 24)
| ((self.read()? as u32) << 16)
| ((self.read()? as u32) << 8)
| ((self.read()? as u32) << 0);
Ok(res)
}
fn read_qname(&mut self, outstr: &mut String) -> Result<()>
{
fn read_qname(&mut self, outstr: &mut String) -> Result<()> {
let mut pos = self.pos();
let mut jumped = false;
let mut delim = "";
let max_jumps = 5;
let mut jumps_performed = 0;
loop {
let len = try!(self.get(pos));
// Dns Packets are untrusted data, so we need to be paranoid. Someone
// can craft a packet with a cycle in the jump instructions. This guards
// against such packets.
if jumps_performed > max_jumps {
return Err(format!("Limit of {} jumps exceeded", max_jumps).into());
}
let len = self.get(pos)?;
// A two byte sequence, where the two highest bits of the first byte is
// set, represents a offset relative to the start of the buffer. We
// handle this by jumping to the offset, setting a flag to indicate
// that we shouldn't update the shared buffer position once done.
if (len & 0xC0) == 0xC0 {
// When a jump is performed, we only modify the shared buffer
// position once, and avoid making the change later on.
if !jumped {
try!(self.seek(pos+2));
self.seek(pos + 2)?;
}
let b2 = try!(self.get(pos+1)) as u16;
let b2 = self.get(pos + 1)? as u16;
let offset = (((len as u16) ^ 0xC0) << 8) | b2;
pos = offset as usize;
jumped = true;
jumps_performed += 1;
continue;
}
@ -111,7 +118,7 @@ impl BytePacketBuffer {
outstr.push_str(delim);
let str_buffer = try!(self.get_range(pos, len as usize));
let str_buffer = self.get_range(pos, len as usize)?;
outstr.push_str(&String::from_utf8_lossy(str_buffer).to_lowercase());
delim = ".";
@ -120,21 +127,21 @@ impl BytePacketBuffer {
}
if !jumped {
try!(self.seek(pos));
self.seek(pos)?;
}
Ok(())
}
}
#[derive(Copy,Clone,Debug,PartialEq,Eq)]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum ResultCode {
NOERROR = 0,
FORMERR = 1,
SERVFAIL = 2,
NXDOMAIN = 3,
NOTIMP = 4,
REFUSED = 5
REFUSED = 5,
}
impl ResultCode {
@ -145,12 +152,12 @@ impl ResultCode {
3 => ResultCode::NXDOMAIN,
4 => ResultCode::NOTIMP,
5 => ResultCode::REFUSED,
0 | _ => ResultCode::NOERROR
0 | _ => ResultCode::NOERROR,
}
}
}
#[derive(Clone,Debug)]
#[derive(Clone, Debug)]
pub struct DnsHeader {
pub id: u16, // 16 bits
@ -169,12 +176,13 @@ pub struct DnsHeader {
pub questions: u16, // 16 bits
pub answers: u16, // 16 bits
pub authoritative_entries: u16, // 16 bits
pub resource_entries: u16 // 16 bits
pub resource_entries: u16, // 16 bits
}
impl DnsHeader {
pub fn new() -> DnsHeader {
DnsHeader { id: 0,
DnsHeader {
id: 0,
recursion_desired: false,
truncated_message: false,
@ -191,13 +199,14 @@ impl DnsHeader {
questions: 0,
answers: 0,
authoritative_entries: 0,
resource_entries: 0 }
resource_entries: 0,
}
}
pub fn read(&mut self, buffer: &mut BytePacketBuffer) -> Result<()> {
self.id = try!(buffer.read_u16());
self.id = buffer.read_u16()?;
let flags = try!(buffer.read_u16());
let flags = buffer.read_u16()?;
let a = (flags >> 8) as u8;
let b = (flags & 0xFF) as u8;
self.recursion_desired = (a & (1 << 0)) > 0;
@ -212,17 +221,17 @@ impl DnsHeader {
self.z = (b & (1 << 6)) > 0;
self.recursion_available = (b & (1 << 7)) > 0;
self.questions = try!(buffer.read_u16());
self.answers = try!(buffer.read_u16());
self.authoritative_entries = try!(buffer.read_u16());
self.resource_entries = try!(buffer.read_u16());
self.questions = buffer.read_u16()?;
self.answers = buffer.read_u16()?;
self.authoritative_entries = buffer.read_u16()?;
self.resource_entries = buffer.read_u16()?;
// Return the constant header size
Ok(())
}
}
#[derive(PartialEq,Eq,Debug,Clone,Hash,Copy)]
#[derive(PartialEq, Eq, Debug, Clone, Hash, Copy)]
pub enum QueryType {
UNKNOWN(u16),
A, // 1
@ -239,84 +248,85 @@ impl QueryType {
pub fn from_num(num: u16) -> QueryType {
match num {
1 => QueryType::A,
_ => QueryType::UNKNOWN(num)
_ => QueryType::UNKNOWN(num),
}
}
}
#[derive(Debug,Clone,PartialEq,Eq)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DnsQuestion {
pub name: String,
pub qtype: QueryType
pub qtype: QueryType,
}
impl DnsQuestion {
pub fn new(name: String, qtype: QueryType) -> DnsQuestion {
DnsQuestion {
name: name,
qtype: qtype
qtype: qtype,
}
}
pub fn read(&mut self, buffer: &mut BytePacketBuffer) -> Result<()> {
try!(buffer.read_qname(&mut self.name));
self.qtype = QueryType::from_num(try!(buffer.read_u16())); // qtype
let _ = try!(buffer.read_u16()); // class
buffer.read_qname(&mut self.name)?;
self.qtype = QueryType::from_num(buffer.read_u16()?); // qtype
let _ = buffer.read_u16()?; // class
Ok(())
}
}
#[derive(Debug,Clone,PartialEq,Eq,Hash,PartialOrd,Ord)]
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[allow(dead_code)]
pub enum DnsRecord {
UNKNOWN {
domain: String,
qtype: u16,
data_len: u16,
ttl: u32
ttl: u32,
}, // 0
A {
domain: String,
addr: Ipv4Addr,
ttl: u32
ttl: u32,
}, // 1
}
impl DnsRecord {
pub fn read(buffer: &mut BytePacketBuffer) -> Result<DnsRecord> {
let mut domain = String::new();
try!(buffer.read_qname(&mut domain));
buffer.read_qname(&mut domain)?;
let qtype_num = try!(buffer.read_u16());
let qtype_num = buffer.read_u16()?;
let qtype = QueryType::from_num(qtype_num);
let _ = try!(buffer.read_u16());
let ttl = try!(buffer.read_u32());
let data_len = try!(buffer.read_u16());
let _ = buffer.read_u16()?;
let ttl = buffer.read_u32()?;
let data_len = buffer.read_u16()?;
match qtype {
QueryType::A => {
let raw_addr = try!(buffer.read_u32());
let addr = Ipv4Addr::new(((raw_addr >> 24) & 0xFF) as u8,
let raw_addr = buffer.read_u32()?;
let addr = Ipv4Addr::new(
((raw_addr >> 24) & 0xFF) as u8,
((raw_addr >> 16) & 0xFF) as u8,
((raw_addr >> 8) & 0xFF) as u8,
((raw_addr >> 0) & 0xFF) as u8);
((raw_addr >> 0) & 0xFF) as u8,
);
Ok(DnsRecord::A {
domain: domain,
addr: addr,
ttl: ttl
ttl: ttl,
})
},
}
QueryType::UNKNOWN(_) => {
try!(buffer.step(data_len as usize));
buffer.step(data_len as usize)?;
Ok(DnsRecord::UNKNOWN {
domain: domain,
qtype: qtype_num,
data_len: data_len,
ttl: ttl
ttl: ttl,
})
}
}
@ -329,7 +339,7 @@ pub struct DnsPacket {
pub questions: Vec<DnsQuestion>,
pub answers: Vec<DnsRecord>,
pub authorities: Vec<DnsRecord>,
pub resources: Vec<DnsRecord>
pub resources: Vec<DnsRecord>,
}
impl DnsPacket {
@ -339,31 +349,30 @@ impl DnsPacket {
questions: Vec::new(),
answers: Vec::new(),
authorities: Vec::new(),
resources: Vec::new()
resources: Vec::new(),
}
}
pub fn from_buffer(buffer: &mut BytePacketBuffer) -> Result<DnsPacket> {
let mut result = DnsPacket::new();
try!(result.header.read(buffer));
result.header.read(buffer)?;
for _ in 0..result.header.questions {
let mut question = DnsQuestion::new("".to_string(),
QueryType::UNKNOWN(0));
try!(question.read(buffer));
let mut question = DnsQuestion::new("".to_string(), QueryType::UNKNOWN(0));
question.read(buffer)?;
result.questions.push(question);
}
for _ in 0..result.header.answers {
let rec = try!(DnsRecord::read(buffer));
let rec = DnsRecord::read(buffer)?;
result.answers.push(rec);
}
for _ in 0..result.header.authoritative_entries {
let rec = try!(DnsRecord::read(buffer));
let rec = DnsRecord::read(buffer)?;
result.authorities.push(rec);
}
for _ in 0..result.header.resource_entries {
let rec = try!(DnsRecord::read(buffer));
let rec = DnsRecord::read(buffer)?;
result.resources.push(rec);
}
@ -371,12 +380,12 @@ impl DnsPacket {
}
}
fn main() {
let mut f = File::open("response_packet.txt").unwrap();
fn main() -> Result<()> {
let mut f = File::open("response_packet.txt")?;
let mut buffer = BytePacketBuffer::new();
f.read(&mut buffer.buf).unwrap();
f.read(&mut buffer.buf)?;
let packet = DnsPacket::from_buffer(&mut buffer).unwrap();
let packet = DnsPacket::from_buffer(&mut buffer)?;
println!("{:?}", packet.header);
for q in packet.questions {
@ -391,4 +400,6 @@ fn main() {
for rec in packet.resources {
println!("{:?}", rec);
}
Ok(())
}

View File

@ -1,18 +1,19 @@
use std::io::{Result, Read};
use std::io::{Error, ErrorKind};
use std::net::Ipv4Addr;
use std::net::UdpSocket;
type Error = Box<dyn std::error::Error>;
type Result<T> = std::result::Result<T, Error>;
pub struct BytePacketBuffer {
pub buf: [u8; 512],
pub pos: usize
pub pos: usize,
}
impl BytePacketBuffer {
pub fn new() -> BytePacketBuffer {
BytePacketBuffer {
buf: [0; 512],
pos: 0
pos: 0,
}
}
@ -34,7 +35,7 @@ impl BytePacketBuffer {
fn read(&mut self) -> Result<u8> {
if self.pos >= 512 {
return Err(Error::new(ErrorKind::InvalidInput, "End of buffer"));
return Err("End of buffer".into());
}
let res = self.buf[self.pos];
self.pos += 1;
@ -44,61 +45,66 @@ impl BytePacketBuffer {
fn get(&mut self, pos: usize) -> Result<u8> {
if pos >= 512 {
return Err(Error::new(ErrorKind::InvalidInput, "End of buffer"));
return Err("End of buffer".into());
}
Ok(self.buf[pos])
}
fn get_range(&mut self, start: usize, len: usize) -> Result<&[u8]> {
if start + len >= 512 {
return Err(Error::new(ErrorKind::InvalidInput, "End of buffer"));
return Err("End of buffer".into());
}
Ok(&self.buf[start..start+len as usize])
Ok(&self.buf[start..start + len as usize])
}
fn read_u16(&mut self) -> Result<u16>
{
let res = ((try!(self.read()) as u16) << 8) |
(try!(self.read()) as u16);
fn read_u16(&mut self) -> Result<u16> {
let res = ((self.read()? as u16) << 8) | (self.read()? as u16);
Ok(res)
}
fn read_u32(&mut self) -> Result<u32>
{
let res = ((try!(self.read()) as u32) << 24) |
((try!(self.read()) as u32) << 16) |
((try!(self.read()) as u32) << 8) |
((try!(self.read()) as u32) << 0);
fn read_u32(&mut self) -> Result<u32> {
let res = ((self.read()? as u32) << 24)
| ((self.read()? as u32) << 16)
| ((self.read()? as u32) << 8)
| ((self.read()? as u32) << 0);
Ok(res)
}
fn read_qname(&mut self, outstr: &mut String) -> Result<()>
{
fn read_qname(&mut self, outstr: &mut String) -> Result<()> {
let mut pos = self.pos();
let mut jumped = false;
let mut delim = "";
let max_jumps = 5;
let mut jumps_performed = 0;
loop {
let len = try!(self.get(pos));
// Dns Packets are untrusted data, so we need to be paranoid. Someone
// can craft a packet with a cycle in the jump instructions. This guards
// against such packets.
if jumps_performed > max_jumps {
return Err(format!("Limit of {} jumps exceeded", max_jumps).into());
}
let len = self.get(pos)?;
// A two byte sequence, where the two highest bits of the first byte is
// set, represents a offset relative to the start of the buffer. We
// handle this by jumping to the offset, setting a flag to indicate
// that we shouldn't update the shared buffer position once done.
if (len & 0xC0) == 0xC0 {
// When a jump is performed, we only modify the shared buffer
// position once, and avoid making the change later on.
if !jumped {
try!(self.seek(pos+2));
self.seek(pos + 2)?;
}
let b2 = try!(self.get(pos+1)) as u16;
let b2 = self.get(pos + 1)? as u16;
let offset = (((len as u16) ^ 0xC0) << 8) | b2;
pos = offset as usize;
jumped = true;
jumps_performed += 1;
continue;
}
@ -111,7 +117,7 @@ impl BytePacketBuffer {
outstr.push_str(delim);
let str_buffer = try!(self.get_range(pos, len as usize));
let str_buffer = self.get_range(pos, len as usize)?;
outstr.push_str(&String::from_utf8_lossy(str_buffer).to_lowercase());
delim = ".";
@ -120,7 +126,7 @@ impl BytePacketBuffer {
}
if !jumped {
try!(self.seek(pos));
self.seek(pos)?;
}
Ok(())
@ -128,7 +134,7 @@ impl BytePacketBuffer {
fn write(&mut self, val: u8) -> Result<()> {
if self.pos >= 512 {
return Err(Error::new(ErrorKind::InvalidInput, "End of buffer"));
return Err("End of buffer".into());
}
self.buf[self.pos] = val;
self.pos += 1;
@ -136,58 +142,56 @@ impl BytePacketBuffer {
}
fn write_u8(&mut self, val: u8) -> Result<()> {
try!(self.write(val));
self.write(val)?;
Ok(())
}
fn write_u16(&mut self, val: u16) -> Result<()> {
try!(self.write((val >> 8) as u8));
try!(self.write((val & 0xFF) as u8));
self.write((val >> 8) as u8)?;
self.write((val & 0xFF) as u8)?;
Ok(())
}
fn write_u32(&mut self, val: u32) -> Result<()> {
try!(self.write(((val >> 24) & 0xFF) as u8));
try!(self.write(((val >> 16) & 0xFF) as u8));
try!(self.write(((val >> 8) & 0xFF) as u8));
try!(self.write(((val >> 0) & 0xFF) as u8));
self.write(((val >> 24) & 0xFF) as u8)?;
self.write(((val >> 16) & 0xFF) as u8)?;
self.write(((val >> 8) & 0xFF) as u8)?;
self.write(((val >> 0) & 0xFF) as u8)?;
Ok(())
}
fn write_qname(&mut self, qname: &str) -> Result<()> {
let split_str = qname.split('.').collect::<Vec<&str>>();
for label in split_str {
let len = label.len();
if len > 0x34 {
return Err(Error::new(ErrorKind::InvalidInput, "Single label exceeds 63 characters of length"));
return Err("Single label exceeds 63 characters of length".into());
}
try!(self.write_u8(len as u8));
self.write_u8(len as u8)?;
for b in label.as_bytes() {
try!(self.write_u8(*b));
self.write_u8(*b)?;
}
}
try!(self.write_u8(0));
self.write_u8(0)?;
Ok(())
}
}
#[derive(Copy,Clone,Debug,PartialEq,Eq)]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum ResultCode {
NOERROR = 0,
FORMERR = 1,
SERVFAIL = 2,
NXDOMAIN = 3,
NOTIMP = 4,
REFUSED = 5
REFUSED = 5,
}
impl ResultCode {
@ -198,12 +202,12 @@ impl ResultCode {
3 => ResultCode::NXDOMAIN,
4 => ResultCode::NOTIMP,
5 => ResultCode::REFUSED,
0 | _ => ResultCode::NOERROR
0 | _ => ResultCode::NOERROR,
}
}
}
#[derive(Clone,Debug)]
#[derive(Clone, Debug)]
pub struct DnsHeader {
pub id: u16, // 16 bits
@ -222,12 +226,13 @@ pub struct DnsHeader {
pub questions: u16, // 16 bits
pub answers: u16, // 16 bits
pub authoritative_entries: u16, // 16 bits
pub resource_entries: u16 // 16 bits
pub resource_entries: u16, // 16 bits
}
impl DnsHeader {
pub fn new() -> DnsHeader {
DnsHeader { id: 0,
DnsHeader {
id: 0,
recursion_desired: false,
truncated_message: false,
@ -244,13 +249,14 @@ impl DnsHeader {
questions: 0,
answers: 0,
authoritative_entries: 0,
resource_entries: 0 }
resource_entries: 0,
}
}
pub fn read(&mut self, buffer: &mut BytePacketBuffer) -> Result<()> {
self.id = try!(buffer.read_u16());
self.id = buffer.read_u16()?;
let flags = try!(buffer.read_u16());
let flags = buffer.read_u16()?;
let a = (flags >> 8) as u8;
let b = (flags & 0xFF) as u8;
self.recursion_desired = (a & (1 << 0)) > 0;
@ -265,40 +271,44 @@ impl DnsHeader {
self.z = (b & (1 << 6)) > 0;
self.recursion_available = (b & (1 << 7)) > 0;
self.questions = try!(buffer.read_u16());
self.answers = try!(buffer.read_u16());
self.authoritative_entries = try!(buffer.read_u16());
self.resource_entries = try!(buffer.read_u16());
self.questions = buffer.read_u16()?;
self.answers = buffer.read_u16()?;
self.authoritative_entries = buffer.read_u16()?;
self.resource_entries = buffer.read_u16()?;
// Return the constant header size
Ok(())
}
pub fn write(&self, buffer: &mut BytePacketBuffer) -> Result<()> {
try!(buffer.write_u16(self.id));
buffer.write_u16(self.id)?;
try!(buffer.write_u8( ((self.recursion_desired as u8)) |
((self.truncated_message as u8) << 1) |
((self.authoritative_answer as u8) << 2) |
(self.opcode << 3) |
((self.response as u8) << 7) as u8) );
buffer.write_u8(
(self.recursion_desired as u8)
| ((self.truncated_message as u8) << 1)
| ((self.authoritative_answer as u8) << 2)
| (self.opcode << 3)
| ((self.response as u8) << 7) as u8,
)?;
try!(buffer.write_u8( (self.rescode.clone() as u8) |
((self.checking_disabled as u8) << 4) |
((self.authed_data as u8) << 5) |
((self.z as u8) << 6) |
((self.recursion_available as u8) << 7) ));
buffer.write_u8(
(self.rescode.clone() as u8)
| ((self.checking_disabled as u8) << 4)
| ((self.authed_data as u8) << 5)
| ((self.z as u8) << 6)
| ((self.recursion_available as u8) << 7),
)?;
try!(buffer.write_u16(self.questions));
try!(buffer.write_u16(self.answers));
try!(buffer.write_u16(self.authoritative_entries));
try!(buffer.write_u16(self.resource_entries));
buffer.write_u16(self.questions)?;
buffer.write_u16(self.answers)?;
buffer.write_u16(self.authoritative_entries)?;
buffer.write_u16(self.resource_entries)?;
Ok(())
}
}
#[derive(PartialEq,Eq,Debug,Clone,Hash,Copy)]
#[derive(PartialEq, Eq, Debug, Clone, Hash, Copy)]
pub enum QueryType {
UNKNOWN(u16),
A, // 1
@ -315,119 +325,121 @@ impl QueryType {
pub fn from_num(num: u16) -> QueryType {
match num {
1 => QueryType::A,
_ => QueryType::UNKNOWN(num)
_ => QueryType::UNKNOWN(num),
}
}
}
#[derive(Debug,Clone,PartialEq,Eq)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DnsQuestion {
pub name: String,
pub qtype: QueryType
pub qtype: QueryType,
}
impl DnsQuestion {
pub fn new(name: String, qtype: QueryType) -> DnsQuestion {
DnsQuestion {
name: name,
qtype: qtype
qtype: qtype,
}
}
pub fn read(&mut self, buffer: &mut BytePacketBuffer) -> Result<()> {
try!(buffer.read_qname(&mut self.name));
self.qtype = QueryType::from_num(try!(buffer.read_u16())); // qtype
let _ = try!(buffer.read_u16()); // class
buffer.read_qname(&mut self.name)?;
self.qtype = QueryType::from_num(buffer.read_u16()?); // qtype
let _ = buffer.read_u16()?; // class
Ok(())
}
pub fn write(&self, buffer: &mut BytePacketBuffer) -> Result<()> {
try!(buffer.write_qname(&self.name));
buffer.write_qname(&self.name)?;
let typenum = self.qtype.to_num();
try!(buffer.write_u16(typenum));
try!(buffer.write_u16(1));
buffer.write_u16(typenum)?;
buffer.write_u16(1)?;
Ok(())
}
}
#[derive(Debug,Clone,PartialEq,Eq,Hash,PartialOrd,Ord)]
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[allow(dead_code)]
pub enum DnsRecord {
UNKNOWN {
domain: String,
qtype: u16,
data_len: u16,
ttl: u32
ttl: u32,
}, // 0
A {
domain: String,
addr: Ipv4Addr,
ttl: u32
ttl: u32,
}, // 1
}
impl DnsRecord {
pub fn read(buffer: &mut BytePacketBuffer) -> Result<DnsRecord> {
let mut domain = String::new();
try!(buffer.read_qname(&mut domain));
buffer.read_qname(&mut domain)?;
let qtype_num = try!(buffer.read_u16());
let qtype_num = buffer.read_u16()?;
let qtype = QueryType::from_num(qtype_num);
let _ = try!(buffer.read_u16());
let ttl = try!(buffer.read_u32());
let data_len = try!(buffer.read_u16());
let _ = buffer.read_u16()?;
let ttl = buffer.read_u32()?;
let data_len = buffer.read_u16()?;
match qtype {
QueryType::A => {
let raw_addr = try!(buffer.read_u32());
let addr = Ipv4Addr::new(((raw_addr >> 24) & 0xFF) as u8,
let raw_addr = buffer.read_u32()?;
let addr = Ipv4Addr::new(
((raw_addr >> 24) & 0xFF) as u8,
((raw_addr >> 16) & 0xFF) as u8,
((raw_addr >> 8) & 0xFF) as u8,
((raw_addr >> 0) & 0xFF) as u8);
((raw_addr >> 0) & 0xFF) as u8,
);
Ok(DnsRecord::A {
domain: domain,
addr: addr,
ttl: ttl
ttl: ttl,
})
},
}
QueryType::UNKNOWN(_) => {
try!(buffer.step(data_len as usize));
buffer.step(data_len as usize)?;
Ok(DnsRecord::UNKNOWN {
domain: domain,
qtype: qtype_num,
data_len: data_len,
ttl: ttl
ttl: ttl,
})
}
}
}
pub fn write(&self, buffer: &mut BytePacketBuffer) -> Result<usize> {
let start_pos = buffer.pos();
match *self {
DnsRecord::A { ref domain, ref addr, ttl } => {
try!(buffer.write_qname(domain));
try!(buffer.write_u16(QueryType::A.to_num()));
try!(buffer.write_u16(1));
try!(buffer.write_u32(ttl));
try!(buffer.write_u16(4));
DnsRecord::A {
ref domain,
ref addr,
ttl,
} => {
buffer.write_qname(domain)?;
buffer.write_u16(QueryType::A.to_num())?;
buffer.write_u16(1)?;
buffer.write_u32(ttl)?;
buffer.write_u16(4)?;
let octets = addr.octets();
try!(buffer.write_u8(octets[0]));
try!(buffer.write_u8(octets[1]));
try!(buffer.write_u8(octets[2]));
try!(buffer.write_u8(octets[3]));
},
buffer.write_u8(octets[0])?;
buffer.write_u8(octets[1])?;
buffer.write_u8(octets[2])?;
buffer.write_u8(octets[3])?;
}
DnsRecord::UNKNOWN { .. } => {
println!("Skipping record: {:?}", self);
}
@ -435,7 +447,6 @@ impl DnsRecord {
Ok(buffer.pos() - start_pos)
}
}
#[derive(Clone, Debug)]
@ -444,7 +455,7 @@ pub struct DnsPacket {
pub questions: Vec<DnsQuestion>,
pub answers: Vec<DnsRecord>,
pub authorities: Vec<DnsRecord>,
pub resources: Vec<DnsRecord>
pub resources: Vec<DnsRecord>,
}
impl DnsPacket {
@ -454,85 +465,85 @@ impl DnsPacket {
questions: Vec::new(),
answers: Vec::new(),
authorities: Vec::new(),
resources: Vec::new()
resources: Vec::new(),
}
}
pub fn from_buffer(buffer: &mut BytePacketBuffer) -> Result<DnsPacket> {
let mut result = DnsPacket::new();
try!(result.header.read(buffer));
result.header.read(buffer)?;
for _ in 0..result.header.questions {
let mut question = DnsQuestion::new("".to_string(),
QueryType::UNKNOWN(0));
try!(question.read(buffer));
let mut question = DnsQuestion::new("".to_string(), QueryType::UNKNOWN(0));
question.read(buffer)?;
result.questions.push(question);
}
for _ in 0..result.header.answers {
let rec = try!(DnsRecord::read(buffer));
let rec = DnsRecord::read(buffer)?;
result.answers.push(rec);
}
for _ in 0..result.header.authoritative_entries {
let rec = try!(DnsRecord::read(buffer));
let rec = DnsRecord::read(buffer)?;
result.authorities.push(rec);
}
for _ in 0..result.header.resource_entries {
let rec = try!(DnsRecord::read(buffer));
let rec = DnsRecord::read(buffer)?;
result.resources.push(rec);
}
Ok(result)
}
pub fn write(&mut self, buffer: &mut BytePacketBuffer) -> Result<()>
{
pub fn write(&mut self, buffer: &mut BytePacketBuffer) -> Result<()> {
self.header.questions = self.questions.len() as u16;
self.header.answers = self.answers.len() as u16;
self.header.authoritative_entries = self.authorities.len() as u16;
self.header.resource_entries = self.resources.len() as u16;
try!(self.header.write(buffer));
self.header.write(buffer)?;
for question in &self.questions {
try!(question.write(buffer));
question.write(buffer)?;
}
for rec in &self.answers {
try!(rec.write(buffer));
rec.write(buffer)?;
}
for rec in &self.authorities {
try!(rec.write(buffer));
rec.write(buffer)?;
}
for rec in &self.resources {
try!(rec.write(buffer));
rec.write(buffer)?;
}
Ok(())
}
}
fn main() {
fn main() -> Result<()> {
let qname = "www.yahoo.com";
let qtype = QueryType::A;
let server = ("8.8.8.8", 53);
let socket = UdpSocket::bind(("0.0.0.0", 43210)).unwrap();
let socket = UdpSocket::bind(("0.0.0.0", 43210))?;
let mut packet = DnsPacket::new();
packet.header.id = 6666;
packet.header.questions = 1;
packet.header.recursion_desired = true;
packet.questions.push(DnsQuestion::new(qname.to_string(), qtype));
packet
.questions
.push(DnsQuestion::new(qname.to_string(), qtype));
let mut req_buffer = BytePacketBuffer::new();
packet.write(&mut req_buffer).unwrap();
socket.send_to(&req_buffer.buf[0..req_buffer.pos], server).unwrap();
packet.write(&mut req_buffer)?;
socket.send_to(&req_buffer.buf[0..req_buffer.pos], server)?;
let mut res_buffer = BytePacketBuffer::new();
socket.recv_from(&mut res_buffer.buf).unwrap();
socket.recv_from(&mut res_buffer.buf)?;
let res_packet = DnsPacket::from_buffer(&mut res_buffer).unwrap();
let res_packet = DnsPacket::from_buffer(&mut res_buffer)?;
println!("{:?}", res_packet.header);
for q in res_packet.questions {
@ -547,4 +558,6 @@ fn main() {
for rec in res_packet.resources {
println!("{:?}", rec);
}
Ok(())
}

View File

@ -1,18 +1,19 @@
use std::io::{Result, Read};
use std::io::{Error, ErrorKind};
use std::net::{Ipv4Addr,Ipv6Addr};
use std::net::UdpSocket;
use std::net::{Ipv4Addr, Ipv6Addr};
type Error = Box<dyn std::error::Error>;
type Result<T> = std::result::Result<T, Error>;
pub struct BytePacketBuffer {
pub buf: [u8; 512],
pub pos: usize
pub pos: usize,
}
impl BytePacketBuffer {
pub fn new() -> BytePacketBuffer {
BytePacketBuffer {
buf: [0; 512],
pos: 0
pos: 0,
}
}
@ -34,7 +35,7 @@ impl BytePacketBuffer {
fn read(&mut self) -> Result<u8> {
if self.pos >= 512 {
return Err(Error::new(ErrorKind::InvalidInput, "End of buffer"));
return Err("End of buffer".into());
}
let res = self.buf[self.pos];
self.pos += 1;
@ -44,61 +45,66 @@ impl BytePacketBuffer {
fn get(&mut self, pos: usize) -> Result<u8> {
if pos >= 512 {
return Err(Error::new(ErrorKind::InvalidInput, "End of buffer"));
return Err("End of buffer".into());
}
Ok(self.buf[pos])
}
fn get_range(&mut self, start: usize, len: usize) -> Result<&[u8]> {
if start + len >= 512 {
return Err(Error::new(ErrorKind::InvalidInput, "End of buffer"));
return Err("End of buffer".into());
}
Ok(&self.buf[start..start+len as usize])
Ok(&self.buf[start..start + len as usize])
}
fn read_u16(&mut self) -> Result<u16>
{
let res = ((try!(self.read()) as u16) << 8) |
(try!(self.read()) as u16);
fn read_u16(&mut self) -> Result<u16> {
let res = ((self.read()? as u16) << 8) | (self.read()? as u16);
Ok(res)
}
fn read_u32(&mut self) -> Result<u32>
{
let res = ((try!(self.read()) as u32) << 24) |
((try!(self.read()) as u32) << 16) |
((try!(self.read()) as u32) << 8) |
((try!(self.read()) as u32) << 0);
fn read_u32(&mut self) -> Result<u32> {
let res = ((self.read()? as u32) << 24)
| ((self.read()? as u32) << 16)
| ((self.read()? as u32) << 8)
| ((self.read()? as u32) << 0);
Ok(res)
}
fn read_qname(&mut self, outstr: &mut String) -> Result<()>
{
fn read_qname(&mut self, outstr: &mut String) -> Result<()> {
let mut pos = self.pos();
let mut jumped = false;
let mut delim = "";
let max_jumps = 5;
let mut jumps_performed = 0;
loop {
let len = try!(self.get(pos));
// Dns Packets are untrusted data, so we need to be paranoid. Someone
// can craft a packet with a cycle in the jump instructions. This guards
// against such packets.
if jumps_performed > max_jumps {
return Err(format!("Limit of {} jumps exceeded", max_jumps).into());
}
let len = self.get(pos)?;
// A two byte sequence, where the two highest bits of the first byte is
// set, represents a offset relative to the start of the buffer. We
// handle this by jumping to the offset, setting a flag to indicate
// that we shouldn't update the shared buffer position once done.
if (len & 0xC0) == 0xC0 {
// When a jump is performed, we only modify the shared buffer
// position once, and avoid making the change later on.
if !jumped {
try!(self.seek(pos+2));
self.seek(pos + 2)?;
}
let b2 = try!(self.get(pos+1)) as u16;
let b2 = self.get(pos + 1)? as u16;
let offset = (((len as u16) ^ 0xC0) << 8) | b2;
pos = offset as usize;
jumped = true;
jumps_performed += 1;
continue;
}
@ -111,7 +117,7 @@ impl BytePacketBuffer {
outstr.push_str(delim);
let str_buffer = try!(self.get_range(pos, len as usize));
let str_buffer = self.get_range(pos, len as usize)?;
outstr.push_str(&String::from_utf8_lossy(str_buffer).to_lowercase());
delim = ".";
@ -120,7 +126,7 @@ impl BytePacketBuffer {
}
if !jumped {
try!(self.seek(pos));
self.seek(pos)?;
}
Ok(())
@ -128,7 +134,7 @@ impl BytePacketBuffer {
fn write(&mut self, val: u8) -> Result<()> {
if self.pos >= 512 {
return Err(Error::new(ErrorKind::InvalidInput, "End of buffer"));
return Err("End of buffer".into());
}
self.buf[self.pos] = val;
self.pos += 1;
@ -136,44 +142,43 @@ impl BytePacketBuffer {
}
fn write_u8(&mut self, val: u8) -> Result<()> {
try!(self.write(val));
self.write(val)?;
Ok(())
}
fn write_u16(&mut self, val: u16) -> Result<()> {
try!(self.write((val >> 8) as u8));
try!(self.write((val & 0xFF) as u8));
self.write((val >> 8) as u8)?;
self.write((val & 0xFF) as u8)?;
Ok(())
}
fn write_u32(&mut self, val: u32) -> Result<()> {
try!(self.write(((val >> 24) & 0xFF) as u8));
try!(self.write(((val >> 16) & 0xFF) as u8));
try!(self.write(((val >> 8) & 0xFF) as u8));
try!(self.write(((val >> 0) & 0xFF) as u8));
self.write(((val >> 24) & 0xFF) as u8)?;
self.write(((val >> 16) & 0xFF) as u8)?;
self.write(((val >> 8) & 0xFF) as u8)?;
self.write(((val >> 0) & 0xFF) as u8)?;
Ok(())
}
fn write_qname(&mut self, qname: &str) -> Result<()> {
let split_str = qname.split('.').collect::<Vec<&str>>();
for label in split_str {
let len = label.len();
if len > 0x34 {
return Err(Error::new(ErrorKind::InvalidInput, "Single label exceeds 63 characters of length"));
return Err("Single label exceeds 63 characters of length".into());
}
try!(self.write_u8(len as u8));
self.write_u8(len as u8)?;
for b in label.as_bytes() {
try!(self.write_u8(*b));
self.write_u8(*b)?;
}
}
try!(self.write_u8(0));
self.write_u8(0)?;
Ok(())
}
@ -185,21 +190,21 @@ impl BytePacketBuffer {
}
fn set_u16(&mut self, pos: usize, val: u16) -> Result<()> {
try!(self.set(pos,(val >> 8) as u8));
try!(self.set(pos+1,(val & 0xFF) as u8));
self.set(pos, (val >> 8) as u8)?;
self.set(pos + 1, (val & 0xFF) as u8)?;
Ok(())
}
}
#[derive(Copy,Clone,Debug,PartialEq,Eq)]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum ResultCode {
NOERROR = 0,
FORMERR = 1,
SERVFAIL = 2,
NXDOMAIN = 3,
NOTIMP = 4,
REFUSED = 5
REFUSED = 5,
}
impl ResultCode {
@ -210,12 +215,12 @@ impl ResultCode {
3 => ResultCode::NXDOMAIN,
4 => ResultCode::NOTIMP,
5 => ResultCode::REFUSED,
0 | _ => ResultCode::NOERROR
0 | _ => ResultCode::NOERROR,
}
}
}
#[derive(Clone,Debug)]
#[derive(Clone, Debug)]
pub struct DnsHeader {
pub id: u16, // 16 bits
@ -234,12 +239,13 @@ pub struct DnsHeader {
pub questions: u16, // 16 bits
pub answers: u16, // 16 bits
pub authoritative_entries: u16, // 16 bits
pub resource_entries: u16 // 16 bits
pub resource_entries: u16, // 16 bits
}
impl DnsHeader {
pub fn new() -> DnsHeader {
DnsHeader { id: 0,
DnsHeader {
id: 0,
recursion_desired: false,
truncated_message: false,
@ -256,13 +262,14 @@ impl DnsHeader {
questions: 0,
answers: 0,
authoritative_entries: 0,
resource_entries: 0 }
resource_entries: 0,
}
}
pub fn read(&mut self, buffer: &mut BytePacketBuffer) -> Result<()> {
self.id = try!(buffer.read_u16());
self.id = buffer.read_u16()?;
let flags = try!(buffer.read_u16());
let flags = buffer.read_u16()?;
let a = (flags >> 8) as u8;
let b = (flags & 0xFF) as u8;
self.recursion_desired = (a & (1 << 0)) > 0;
@ -277,40 +284,44 @@ impl DnsHeader {
self.z = (b & (1 << 6)) > 0;
self.recursion_available = (b & (1 << 7)) > 0;
self.questions = try!(buffer.read_u16());
self.answers = try!(buffer.read_u16());
self.authoritative_entries = try!(buffer.read_u16());
self.resource_entries = try!(buffer.read_u16());
self.questions = buffer.read_u16()?;
self.answers = buffer.read_u16()?;
self.authoritative_entries = buffer.read_u16()?;
self.resource_entries = buffer.read_u16()?;
// Return the constant header size
Ok(())
}
pub fn write(&self, buffer: &mut BytePacketBuffer) -> Result<()> {
try!(buffer.write_u16(self.id));
buffer.write_u16(self.id)?;
try!(buffer.write_u8( ((self.recursion_desired as u8)) |
((self.truncated_message as u8) << 1) |
((self.authoritative_answer as u8) << 2) |
(self.opcode << 3) |
((self.response as u8) << 7) as u8) );
buffer.write_u8(
(self.recursion_desired as u8)
| ((self.truncated_message as u8) << 1)
| ((self.authoritative_answer as u8) << 2)
| (self.opcode << 3)
| ((self.response as u8) << 7) as u8,
)?;
try!(buffer.write_u8( (self.rescode.clone() as u8) |
((self.checking_disabled as u8) << 4) |
((self.authed_data as u8) << 5) |
((self.z as u8) << 6) |
((self.recursion_available as u8) << 7) ));
buffer.write_u8(
(self.rescode.clone() as u8)
| ((self.checking_disabled as u8) << 4)
| ((self.authed_data as u8) << 5)
| ((self.z as u8) << 6)
| ((self.recursion_available as u8) << 7),
)?;
try!(buffer.write_u16(self.questions));
try!(buffer.write_u16(self.answers));
try!(buffer.write_u16(self.authoritative_entries));
try!(buffer.write_u16(self.resource_entries));
buffer.write_u16(self.questions)?;
buffer.write_u16(self.answers)?;
buffer.write_u16(self.authoritative_entries)?;
buffer.write_u16(self.resource_entries)?;
Ok(())
}
}
#[derive(PartialEq,Eq,Debug,Clone,Hash,Copy)]
#[derive(PartialEq, Eq, Debug, Clone, Hash, Copy)]
pub enum QueryType {
UNKNOWN(u16),
A, // 1
@ -339,246 +350,267 @@ impl QueryType {
5 => QueryType::CNAME,
15 => QueryType::MX,
28 => QueryType::AAAA,
_ => QueryType::UNKNOWN(num)
_ => QueryType::UNKNOWN(num),
}
}
}
#[derive(Debug,Clone,PartialEq,Eq)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DnsQuestion {
pub name: String,
pub qtype: QueryType
pub qtype: QueryType,
}
impl DnsQuestion {
pub fn new(name: String, qtype: QueryType) -> DnsQuestion {
DnsQuestion {
name: name,
qtype: qtype
qtype: qtype,
}
}
pub fn read(&mut self, buffer: &mut BytePacketBuffer) -> Result<()> {
try!(buffer.read_qname(&mut self.name));
self.qtype = QueryType::from_num(try!(buffer.read_u16())); // qtype
let _ = try!(buffer.read_u16()); // class
buffer.read_qname(&mut self.name)?;
self.qtype = QueryType::from_num(buffer.read_u16()?); // qtype
let _ = buffer.read_u16()?; // class
Ok(())
}
pub fn write(&self, buffer: &mut BytePacketBuffer) -> Result<()> {
try!(buffer.write_qname(&self.name));
buffer.write_qname(&self.name)?;
let typenum = self.qtype.to_num();
try!(buffer.write_u16(typenum));
try!(buffer.write_u16(1));
buffer.write_u16(typenum)?;
buffer.write_u16(1)?;
Ok(())
}
}
#[derive(Debug,Clone,PartialEq,Eq,Hash,PartialOrd,Ord)]
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[allow(dead_code)]
pub enum DnsRecord {
UNKNOWN {
domain: String,
qtype: u16,
data_len: u16,
ttl: u32
ttl: u32,
}, // 0
A {
domain: String,
addr: Ipv4Addr,
ttl: u32
ttl: u32,
}, // 1
NS {
domain: String,
host: String,
ttl: u32
ttl: u32,
}, // 2
CNAME {
domain: String,
host: String,
ttl: u32
ttl: u32,
}, // 5
MX {
domain: String,
priority: u16,
host: String,
ttl: u32
ttl: u32,
}, // 15
AAAA {
domain: String,
addr: Ipv6Addr,
ttl: u32
ttl: u32,
}, // 28
}
impl DnsRecord {
pub fn read(buffer: &mut BytePacketBuffer) -> Result<DnsRecord> {
let mut domain = String::new();
try!(buffer.read_qname(&mut domain));
buffer.read_qname(&mut domain)?;
let qtype_num = try!(buffer.read_u16());
let qtype_num = buffer.read_u16()?;
let qtype = QueryType::from_num(qtype_num);
let _ = try!(buffer.read_u16());
let ttl = try!(buffer.read_u32());
let data_len = try!(buffer.read_u16());
let _ = buffer.read_u16()?;
let ttl = buffer.read_u32()?;
let data_len = buffer.read_u16()?;
match qtype {
QueryType::A => {
let raw_addr = try!(buffer.read_u32());
let addr = Ipv4Addr::new(((raw_addr >> 24) & 0xFF) as u8,
let raw_addr = buffer.read_u32()?;
let addr = Ipv4Addr::new(
((raw_addr >> 24) & 0xFF) as u8,
((raw_addr >> 16) & 0xFF) as u8,
((raw_addr >> 8) & 0xFF) as u8,
((raw_addr >> 0) & 0xFF) as u8);
((raw_addr >> 0) & 0xFF) as u8,
);
Ok(DnsRecord::A {
domain: domain,
addr: addr,
ttl: ttl
ttl: ttl,
})
},
}
QueryType::AAAA => {
let raw_addr1 = try!(buffer.read_u32());
let raw_addr2 = try!(buffer.read_u32());
let raw_addr3 = try!(buffer.read_u32());
let raw_addr4 = try!(buffer.read_u32());
let addr = Ipv6Addr::new(((raw_addr1 >> 16) & 0xFFFF) as u16,
let raw_addr1 = buffer.read_u32()?;
let raw_addr2 = buffer.read_u32()?;
let raw_addr3 = buffer.read_u32()?;
let raw_addr4 = buffer.read_u32()?;
let addr = Ipv6Addr::new(
((raw_addr1 >> 16) & 0xFFFF) as u16,
((raw_addr1 >> 0) & 0xFFFF) as u16,
((raw_addr2 >> 16) & 0xFFFF) as u16,
((raw_addr2 >> 0) & 0xFFFF) as u16,
((raw_addr3 >> 16) & 0xFFFF) as u16,
((raw_addr3 >> 0) & 0xFFFF) as u16,
((raw_addr4 >> 16) & 0xFFFF) as u16,
((raw_addr4 >> 0) & 0xFFFF) as u16);
((raw_addr4 >> 0) & 0xFFFF) as u16,
);
Ok(DnsRecord::AAAA {
domain: domain,
addr: addr,
ttl: ttl
ttl: ttl,
})
},
}
QueryType::NS => {
let mut ns = String::new();
try!(buffer.read_qname(&mut ns));
buffer.read_qname(&mut ns)?;
Ok(DnsRecord::NS {
domain: domain,
host: ns,
ttl: ttl
ttl: ttl,
})
},
}
QueryType::CNAME => {
let mut cname = String::new();
try!(buffer.read_qname(&mut cname));
buffer.read_qname(&mut cname)?;
Ok(DnsRecord::CNAME {
domain: domain,
host: cname,
ttl: ttl
ttl: ttl,
})
},
}
QueryType::MX => {
let priority = try!(buffer.read_u16());
let priority = buffer.read_u16()?;
let mut mx = String::new();
try!(buffer.read_qname(&mut mx));
buffer.read_qname(&mut mx)?;
Ok(DnsRecord::MX {
domain: domain,
priority: priority,
host: mx,
ttl: ttl
ttl: ttl,
})
},
}
QueryType::UNKNOWN(_) => {
try!(buffer.step(data_len as usize));
buffer.step(data_len as usize)?;
Ok(DnsRecord::UNKNOWN {
domain: domain,
qtype: qtype_num,
data_len: data_len,
ttl: ttl
ttl: ttl,
})
}
}
}
pub fn write(&self, buffer: &mut BytePacketBuffer) -> Result<usize> {
let start_pos = buffer.pos();
match *self {
DnsRecord::A { ref domain, ref addr, ttl } => {
try!(buffer.write_qname(domain));
try!(buffer.write_u16(QueryType::A.to_num()));
try!(buffer.write_u16(1));
try!(buffer.write_u32(ttl));
try!(buffer.write_u16(4));
DnsRecord::A {
ref domain,
ref addr,
ttl,
} => {
buffer.write_qname(domain)?;
buffer.write_u16(QueryType::A.to_num())?;
buffer.write_u16(1)?;
buffer.write_u32(ttl)?;
buffer.write_u16(4)?;
let octets = addr.octets();
try!(buffer.write_u8(octets[0]));
try!(buffer.write_u8(octets[1]));
try!(buffer.write_u8(octets[2]));
try!(buffer.write_u8(octets[3]));
},
DnsRecord::NS { ref domain, ref host, ttl } => {
try!(buffer.write_qname(domain));
try!(buffer.write_u16(QueryType::NS.to_num()));
try!(buffer.write_u16(1));
try!(buffer.write_u32(ttl));
buffer.write_u8(octets[0])?;
buffer.write_u8(octets[1])?;
buffer.write_u8(octets[2])?;
buffer.write_u8(octets[3])?;
}
DnsRecord::NS {
ref domain,
ref host,
ttl,
} => {
buffer.write_qname(domain)?;
buffer.write_u16(QueryType::NS.to_num())?;
buffer.write_u16(1)?;
buffer.write_u32(ttl)?;
let pos = buffer.pos();
try!(buffer.write_u16(0));
buffer.write_u16(0)?;
try!(buffer.write_qname(host));
buffer.write_qname(host)?;
let size = buffer.pos() - (pos + 2);
try!(buffer.set_u16(pos, size as u16));
},
DnsRecord::CNAME { ref domain, ref host, ttl } => {
try!(buffer.write_qname(domain));
try!(buffer.write_u16(QueryType::CNAME.to_num()));
try!(buffer.write_u16(1));
try!(buffer.write_u32(ttl));
buffer.set_u16(pos, size as u16)?;
}
DnsRecord::CNAME {
ref domain,
ref host,
ttl,
} => {
buffer.write_qname(domain)?;
buffer.write_u16(QueryType::CNAME.to_num())?;
buffer.write_u16(1)?;
buffer.write_u32(ttl)?;
let pos = buffer.pos();
try!(buffer.write_u16(0));
buffer.write_u16(0)?;
try!(buffer.write_qname(host));
buffer.write_qname(host)?;
let size = buffer.pos() - (pos + 2);
try!(buffer.set_u16(pos, size as u16));
},
DnsRecord::MX { ref domain, priority, ref host, ttl } => {
try!(buffer.write_qname(domain));
try!(buffer.write_u16(QueryType::MX.to_num()));
try!(buffer.write_u16(1));
try!(buffer.write_u32(ttl));
buffer.set_u16(pos, size as u16)?;
}
DnsRecord::MX {
ref domain,
priority,
ref host,
ttl,
} => {
buffer.write_qname(domain)?;
buffer.write_u16(QueryType::MX.to_num())?;
buffer.write_u16(1)?;
buffer.write_u32(ttl)?;
let pos = buffer.pos();
try!(buffer.write_u16(0));
buffer.write_u16(0)?;
try!(buffer.write_u16(priority));
try!(buffer.write_qname(host));
buffer.write_u16(priority)?;
buffer.write_qname(host)?;
let size = buffer.pos() - (pos + 2);
try!(buffer.set_u16(pos, size as u16));
},
DnsRecord::AAAA { ref domain, ref addr, ttl } => {
try!(buffer.write_qname(domain));
try!(buffer.write_u16(QueryType::AAAA.to_num()));
try!(buffer.write_u16(1));
try!(buffer.write_u32(ttl));
try!(buffer.write_u16(16));
buffer.set_u16(pos, size as u16)?;
}
DnsRecord::AAAA {
ref domain,
ref addr,
ttl,
} => {
buffer.write_qname(domain)?;
buffer.write_u16(QueryType::AAAA.to_num())?;
buffer.write_u16(1)?;
buffer.write_u32(ttl)?;
buffer.write_u16(16)?;
for octet in &addr.segments() {
try!(buffer.write_u16(*octet));
buffer.write_u16(*octet)?;
}
}
},
DnsRecord::UNKNOWN { .. } => {
println!("Skipping record: {:?}", self);
}
@ -586,7 +618,6 @@ impl DnsRecord {
Ok(buffer.pos() - start_pos)
}
}
#[derive(Clone, Debug)]
@ -595,7 +626,7 @@ pub struct DnsPacket {
pub questions: Vec<DnsQuestion>,
pub answers: Vec<DnsRecord>,
pub authorities: Vec<DnsRecord>,
pub resources: Vec<DnsRecord>
pub resources: Vec<DnsRecord>,
}
impl DnsPacket {
@ -605,85 +636,85 @@ impl DnsPacket {
questions: Vec::new(),
answers: Vec::new(),
authorities: Vec::new(),
resources: Vec::new()
resources: Vec::new(),
}
}
pub fn from_buffer(buffer: &mut BytePacketBuffer) -> Result<DnsPacket> {
let mut result = DnsPacket::new();
try!(result.header.read(buffer));
result.header.read(buffer)?;
for _ in 0..result.header.questions {
let mut question = DnsQuestion::new("".to_string(),
QueryType::UNKNOWN(0));
try!(question.read(buffer));
let mut question = DnsQuestion::new("".to_string(), QueryType::UNKNOWN(0));
question.read(buffer)?;
result.questions.push(question);
}
for _ in 0..result.header.answers {
let rec = try!(DnsRecord::read(buffer));
let rec = DnsRecord::read(buffer)?;
result.answers.push(rec);
}
for _ in 0..result.header.authoritative_entries {
let rec = try!(DnsRecord::read(buffer));
let rec = DnsRecord::read(buffer)?;
result.authorities.push(rec);
}
for _ in 0..result.header.resource_entries {
let rec = try!(DnsRecord::read(buffer));
let rec = DnsRecord::read(buffer)?;
result.resources.push(rec);
}
Ok(result)
}
pub fn write(&mut self, buffer: &mut BytePacketBuffer) -> Result<()>
{
pub fn write(&mut self, buffer: &mut BytePacketBuffer) -> Result<()> {
self.header.questions = self.questions.len() as u16;
self.header.answers = self.answers.len() as u16;
self.header.authoritative_entries = self.authorities.len() as u16;
self.header.resource_entries = self.resources.len() as u16;
try!(self.header.write(buffer));
self.header.write(buffer)?;
for question in &self.questions {
try!(question.write(buffer));
question.write(buffer)?;
}
for rec in &self.answers {
try!(rec.write(buffer));
rec.write(buffer)?;
}
for rec in &self.authorities {
try!(rec.write(buffer));
rec.write(buffer)?;
}
for rec in &self.resources {
try!(rec.write(buffer));
rec.write(buffer)?;
}
Ok(())
}
}
fn main() {
fn main() -> Result<()> {
let qname = "yahoo.com";
let qtype = QueryType::MX;
let server = ("8.8.8.8", 53);
let socket = UdpSocket::bind(("0.0.0.0", 43210)).unwrap();
let socket = UdpSocket::bind(("0.0.0.0", 43210))?;
let mut packet = DnsPacket::new();
packet.header.id = 6666;
packet.header.questions = 1;
packet.header.recursion_desired = true;
packet.questions.push(DnsQuestion::new(qname.to_string(), qtype));
packet
.questions
.push(DnsQuestion::new(qname.to_string(), qtype));
let mut req_buffer = BytePacketBuffer::new();
packet.write(&mut req_buffer).unwrap();
socket.send_to(&req_buffer.buf[0..req_buffer.pos], server).unwrap();
packet.write(&mut req_buffer)?;
socket.send_to(&req_buffer.buf[0..req_buffer.pos], server)?;
let mut res_buffer = BytePacketBuffer::new();
socket.recv_from(&mut res_buffer.buf).unwrap();
socket.recv_from(&mut res_buffer.buf)?;
let res_packet = DnsPacket::from_buffer(&mut res_buffer).unwrap();
let res_packet = DnsPacket::from_buffer(&mut res_buffer)?;
println!("{:?}", res_packet.header);
for q in res_packet.questions {
@ -698,4 +729,6 @@ fn main() {
for rec in res_packet.resources {
println!("{:?}", rec);
}
Ok(())
}

View File

@ -1,18 +1,19 @@
use std::io::{Result, Read};
use std::io::{Error, ErrorKind};
use std::net::{Ipv4Addr,Ipv6Addr};
use std::net::UdpSocket;
use std::net::{Ipv4Addr, Ipv6Addr};
type Error = Box<dyn std::error::Error>;
type Result<T> = std::result::Result<T, Error>;
pub struct BytePacketBuffer {
pub buf: [u8; 512],
pub pos: usize
pub pos: usize,
}
impl BytePacketBuffer {
pub fn new() -> BytePacketBuffer {
BytePacketBuffer {
buf: [0; 512],
pos: 0
pos: 0,
}
}
@ -34,7 +35,7 @@ impl BytePacketBuffer {
fn read(&mut self) -> Result<u8> {
if self.pos >= 512 {
return Err(Error::new(ErrorKind::InvalidInput, "End of buffer"));
return Err("End of buffer".into());
}
let res = self.buf[self.pos];
self.pos += 1;
@ -44,61 +45,66 @@ impl BytePacketBuffer {
fn get(&mut self, pos: usize) -> Result<u8> {
if pos >= 512 {
return Err(Error::new(ErrorKind::InvalidInput, "End of buffer"));
return Err("End of buffer".into());
}
Ok(self.buf[pos])
}
fn get_range(&mut self, start: usize, len: usize) -> Result<&[u8]> {
if start + len >= 512 {
return Err(Error::new(ErrorKind::InvalidInput, "End of buffer"));
return Err("End of buffer".into());
}
Ok(&self.buf[start..start+len as usize])
Ok(&self.buf[start..start + len as usize])
}
fn read_u16(&mut self) -> Result<u16>
{
let res = ((try!(self.read()) as u16) << 8) |
(try!(self.read()) as u16);
fn read_u16(&mut self) -> Result<u16> {
let res = ((self.read()? as u16) << 8) | (self.read()? as u16);
Ok(res)
}
fn read_u32(&mut self) -> Result<u32>
{
let res = ((try!(self.read()) as u32) << 24) |
((try!(self.read()) as u32) << 16) |
((try!(self.read()) as u32) << 8) |
((try!(self.read()) as u32) << 0);
fn read_u32(&mut self) -> Result<u32> {
let res = ((self.read()? as u32) << 24)
| ((self.read()? as u32) << 16)
| ((self.read()? as u32) << 8)
| ((self.read()? as u32) << 0);
Ok(res)
}
fn read_qname(&mut self, outstr: &mut String) -> Result<()>
{
fn read_qname(&mut self, outstr: &mut String) -> Result<()> {
let mut pos = self.pos();
let mut jumped = false;
let mut delim = "";
let max_jumps = 5;
let mut jumps_performed = 0;
loop {
let len = try!(self.get(pos));
// Dns Packets are untrusted data, so we need to be paranoid. Someone
// can craft a packet with a cycle in the jump instructions. This guards
// against such packets.
if jumps_performed > max_jumps {
return Err(format!("Limit of {} jumps exceeded", max_jumps).into());
}
let len = self.get(pos)?;
// A two byte sequence, where the two highest bits of the first byte is
// set, represents a offset relative to the start of the buffer. We
// handle this by jumping to the offset, setting a flag to indicate
// that we shouldn't update the shared buffer position once done.
if (len & 0xC0) == 0xC0 {
// When a jump is performed, we only modify the shared buffer
// position once, and avoid making the change later on.
if !jumped {
try!(self.seek(pos+2));
self.seek(pos + 2)?;
}
let b2 = try!(self.get(pos+1)) as u16;
let b2 = self.get(pos + 1)? as u16;
let offset = (((len as u16) ^ 0xC0) << 8) | b2;
pos = offset as usize;
jumped = true;
jumps_performed += 1;
continue;
}
@ -111,7 +117,7 @@ impl BytePacketBuffer {
outstr.push_str(delim);
let str_buffer = try!(self.get_range(pos, len as usize));
let str_buffer = self.get_range(pos, len as usize)?;
outstr.push_str(&String::from_utf8_lossy(str_buffer).to_lowercase());
delim = ".";
@ -120,7 +126,7 @@ impl BytePacketBuffer {
}
if !jumped {
try!(self.seek(pos));
self.seek(pos)?;
}
Ok(())
@ -128,7 +134,7 @@ impl BytePacketBuffer {
fn write(&mut self, val: u8) -> Result<()> {
if self.pos >= 512 {
return Err(Error::new(ErrorKind::InvalidInput, "End of buffer"));
return Err("End of buffer".into());
}
self.buf[self.pos] = val;
self.pos += 1;
@ -136,44 +142,43 @@ impl BytePacketBuffer {
}
fn write_u8(&mut self, val: u8) -> Result<()> {
try!(self.write(val));
self.write(val)?;
Ok(())
}
fn write_u16(&mut self, val: u16) -> Result<()> {
try!(self.write((val >> 8) as u8));
try!(self.write((val & 0xFF) as u8));
self.write((val >> 8) as u8)?;
self.write((val & 0xFF) as u8)?;
Ok(())
}
fn write_u32(&mut self, val: u32) -> Result<()> {
try!(self.write(((val >> 24) & 0xFF) as u8));
try!(self.write(((val >> 16) & 0xFF) as u8));
try!(self.write(((val >> 8) & 0xFF) as u8));
try!(self.write(((val >> 0) & 0xFF) as u8));
self.write(((val >> 24) & 0xFF) as u8)?;
self.write(((val >> 16) & 0xFF) as u8)?;
self.write(((val >> 8) & 0xFF) as u8)?;
self.write(((val >> 0) & 0xFF) as u8)?;
Ok(())
}
fn write_qname(&mut self, qname: &str) -> Result<()> {
let split_str = qname.split('.').collect::<Vec<&str>>();
for label in split_str {
let len = label.len();
if len > 0x34 {
return Err(Error::new(ErrorKind::InvalidInput, "Single label exceeds 63 characters of length"));
return Err("Single label exceeds 63 characters of length".into());
}
try!(self.write_u8(len as u8));
self.write_u8(len as u8)?;
for b in label.as_bytes() {
try!(self.write_u8(*b));
self.write_u8(*b)?;
}
}
try!(self.write_u8(0));
self.write_u8(0)?;
Ok(())
}
@ -185,21 +190,21 @@ impl BytePacketBuffer {
}
fn set_u16(&mut self, pos: usize, val: u16) -> Result<()> {
try!(self.set(pos,(val >> 8) as u8));
try!(self.set(pos+1,(val & 0xFF) as u8));
self.set(pos, (val >> 8) as u8)?;
self.set(pos + 1, (val & 0xFF) as u8)?;
Ok(())
}
}
#[derive(Copy,Clone,Debug,PartialEq,Eq)]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum ResultCode {
NOERROR = 0,
FORMERR = 1,
SERVFAIL = 2,
NXDOMAIN = 3,
NOTIMP = 4,
REFUSED = 5
REFUSED = 5,
}
impl ResultCode {
@ -210,12 +215,12 @@ impl ResultCode {
3 => ResultCode::NXDOMAIN,
4 => ResultCode::NOTIMP,
5 => ResultCode::REFUSED,
0 | _ => ResultCode::NOERROR
0 | _ => ResultCode::NOERROR,
}
}
}
#[derive(Clone,Debug)]
#[derive(Clone, Debug)]
pub struct DnsHeader {
pub id: u16, // 16 bits
@ -234,12 +239,13 @@ pub struct DnsHeader {
pub questions: u16, // 16 bits
pub answers: u16, // 16 bits
pub authoritative_entries: u16, // 16 bits
pub resource_entries: u16 // 16 bits
pub resource_entries: u16, // 16 bits
}
impl DnsHeader {
pub fn new() -> DnsHeader {
DnsHeader { id: 0,
DnsHeader {
id: 0,
recursion_desired: false,
truncated_message: false,
@ -256,13 +262,14 @@ impl DnsHeader {
questions: 0,
answers: 0,
authoritative_entries: 0,
resource_entries: 0 }
resource_entries: 0,
}
}
pub fn read(&mut self, buffer: &mut BytePacketBuffer) -> Result<()> {
self.id = try!(buffer.read_u16());
self.id = buffer.read_u16()?;
let flags = try!(buffer.read_u16());
let flags = buffer.read_u16()?;
let a = (flags >> 8) as u8;
let b = (flags & 0xFF) as u8;
self.recursion_desired = (a & (1 << 0)) > 0;
@ -277,40 +284,44 @@ impl DnsHeader {
self.z = (b & (1 << 6)) > 0;
self.recursion_available = (b & (1 << 7)) > 0;
self.questions = try!(buffer.read_u16());
self.answers = try!(buffer.read_u16());
self.authoritative_entries = try!(buffer.read_u16());
self.resource_entries = try!(buffer.read_u16());
self.questions = buffer.read_u16()?;
self.answers = buffer.read_u16()?;
self.authoritative_entries = buffer.read_u16()?;
self.resource_entries = buffer.read_u16()?;
// Return the constant header size
Ok(())
}
pub fn write(&self, buffer: &mut BytePacketBuffer) -> Result<()> {
try!(buffer.write_u16(self.id));
buffer.write_u16(self.id)?;
try!(buffer.write_u8( ((self.recursion_desired as u8)) |
((self.truncated_message as u8) << 1) |
((self.authoritative_answer as u8) << 2) |
(self.opcode << 3) |
((self.response as u8) << 7) as u8) );
buffer.write_u8(
(self.recursion_desired as u8)
| ((self.truncated_message as u8) << 1)
| ((self.authoritative_answer as u8) << 2)
| (self.opcode << 3)
| ((self.response as u8) << 7) as u8,
)?;
try!(buffer.write_u8( (self.rescode.clone() as u8) |
((self.checking_disabled as u8) << 4) |
((self.authed_data as u8) << 5) |
((self.z as u8) << 6) |
((self.recursion_available as u8) << 7) ));
buffer.write_u8(
(self.rescode.clone() as u8)
| ((self.checking_disabled as u8) << 4)
| ((self.authed_data as u8) << 5)
| ((self.z as u8) << 6)
| ((self.recursion_available as u8) << 7),
)?;
try!(buffer.write_u16(self.questions));
try!(buffer.write_u16(self.answers));
try!(buffer.write_u16(self.authoritative_entries));
try!(buffer.write_u16(self.resource_entries));
buffer.write_u16(self.questions)?;
buffer.write_u16(self.answers)?;
buffer.write_u16(self.authoritative_entries)?;
buffer.write_u16(self.resource_entries)?;
Ok(())
}
}
#[derive(PartialEq,Eq,Debug,Clone,Hash,Copy)]
#[derive(PartialEq, Eq, Debug, Clone, Hash, Copy)]
pub enum QueryType {
UNKNOWN(u16),
A, // 1
@ -339,246 +350,267 @@ impl QueryType {
5 => QueryType::CNAME,
15 => QueryType::MX,
28 => QueryType::AAAA,
_ => QueryType::UNKNOWN(num)
_ => QueryType::UNKNOWN(num),
}
}
}
#[derive(Debug,Clone,PartialEq,Eq)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DnsQuestion {
pub name: String,
pub qtype: QueryType
pub qtype: QueryType,
}
impl DnsQuestion {
pub fn new(name: String, qtype: QueryType) -> DnsQuestion {
DnsQuestion {
name: name,
qtype: qtype
qtype: qtype,
}
}
pub fn read(&mut self, buffer: &mut BytePacketBuffer) -> Result<()> {
try!(buffer.read_qname(&mut self.name));
self.qtype = QueryType::from_num(try!(buffer.read_u16())); // qtype
let _ = try!(buffer.read_u16()); // class
buffer.read_qname(&mut self.name)?;
self.qtype = QueryType::from_num(buffer.read_u16()?); // qtype
let _ = buffer.read_u16()?; // class
Ok(())
}
pub fn write(&self, buffer: &mut BytePacketBuffer) -> Result<()> {
try!(buffer.write_qname(&self.name));
buffer.write_qname(&self.name)?;
let typenum = self.qtype.to_num();
try!(buffer.write_u16(typenum));
try!(buffer.write_u16(1));
buffer.write_u16(typenum)?;
buffer.write_u16(1)?;
Ok(())
}
}
#[derive(Debug,Clone,PartialEq,Eq,Hash,PartialOrd,Ord)]
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[allow(dead_code)]
pub enum DnsRecord {
UNKNOWN {
domain: String,
qtype: u16,
data_len: u16,
ttl: u32
ttl: u32,
}, // 0
A {
domain: String,
addr: Ipv4Addr,
ttl: u32
ttl: u32,
}, // 1
NS {
domain: String,
host: String,
ttl: u32
ttl: u32,
}, // 2
CNAME {
domain: String,
host: String,
ttl: u32
ttl: u32,
}, // 5
MX {
domain: String,
priority: u16,
host: String,
ttl: u32
ttl: u32,
}, // 15
AAAA {
domain: String,
addr: Ipv6Addr,
ttl: u32
ttl: u32,
}, // 28
}
impl DnsRecord {
pub fn read(buffer: &mut BytePacketBuffer) -> Result<DnsRecord> {
let mut domain = String::new();
try!(buffer.read_qname(&mut domain));
buffer.read_qname(&mut domain)?;
let qtype_num = try!(buffer.read_u16());
let qtype_num = buffer.read_u16()?;
let qtype = QueryType::from_num(qtype_num);
let _ = try!(buffer.read_u16());
let ttl = try!(buffer.read_u32());
let data_len = try!(buffer.read_u16());
let _ = buffer.read_u16()?;
let ttl = buffer.read_u32()?;
let data_len = buffer.read_u16()?;
match qtype {
QueryType::A => {
let raw_addr = try!(buffer.read_u32());
let addr = Ipv4Addr::new(((raw_addr >> 24) & 0xFF) as u8,
let raw_addr = buffer.read_u32()?;
let addr = Ipv4Addr::new(
((raw_addr >> 24) & 0xFF) as u8,
((raw_addr >> 16) & 0xFF) as u8,
((raw_addr >> 8) & 0xFF) as u8,
((raw_addr >> 0) & 0xFF) as u8);
((raw_addr >> 0) & 0xFF) as u8,
);
Ok(DnsRecord::A {
domain: domain,
addr: addr,
ttl: ttl
ttl: ttl,
})
},
}
QueryType::AAAA => {
let raw_addr1 = try!(buffer.read_u32());
let raw_addr2 = try!(buffer.read_u32());
let raw_addr3 = try!(buffer.read_u32());
let raw_addr4 = try!(buffer.read_u32());
let addr = Ipv6Addr::new(((raw_addr1 >> 16) & 0xFFFF) as u16,
let raw_addr1 = buffer.read_u32()?;
let raw_addr2 = buffer.read_u32()?;
let raw_addr3 = buffer.read_u32()?;
let raw_addr4 = buffer.read_u32()?;
let addr = Ipv6Addr::new(
((raw_addr1 >> 16) & 0xFFFF) as u16,
((raw_addr1 >> 0) & 0xFFFF) as u16,
((raw_addr2 >> 16) & 0xFFFF) as u16,
((raw_addr2 >> 0) & 0xFFFF) as u16,
((raw_addr3 >> 16) & 0xFFFF) as u16,
((raw_addr3 >> 0) & 0xFFFF) as u16,
((raw_addr4 >> 16) & 0xFFFF) as u16,
((raw_addr4 >> 0) & 0xFFFF) as u16);
((raw_addr4 >> 0) & 0xFFFF) as u16,
);
Ok(DnsRecord::AAAA {
domain: domain,
addr: addr,
ttl: ttl
ttl: ttl,
})
},
}
QueryType::NS => {
let mut ns = String::new();
try!(buffer.read_qname(&mut ns));
buffer.read_qname(&mut ns)?;
Ok(DnsRecord::NS {
domain: domain,
host: ns,
ttl: ttl
ttl: ttl,
})
},
}
QueryType::CNAME => {
let mut cname = String::new();
try!(buffer.read_qname(&mut cname));
buffer.read_qname(&mut cname)?;
Ok(DnsRecord::CNAME {
domain: domain,
host: cname,
ttl: ttl
ttl: ttl,
})
},
}
QueryType::MX => {
let priority = try!(buffer.read_u16());
let priority = buffer.read_u16()?;
let mut mx = String::new();
try!(buffer.read_qname(&mut mx));
buffer.read_qname(&mut mx)?;
Ok(DnsRecord::MX {
domain: domain,
priority: priority,
host: mx,
ttl: ttl
ttl: ttl,
})
},
}
QueryType::UNKNOWN(_) => {
try!(buffer.step(data_len as usize));
buffer.step(data_len as usize)?;
Ok(DnsRecord::UNKNOWN {
domain: domain,
qtype: qtype_num,
data_len: data_len,
ttl: ttl
ttl: ttl,
})
}
}
}
pub fn write(&self, buffer: &mut BytePacketBuffer) -> Result<usize> {
let start_pos = buffer.pos();
match *self {
DnsRecord::A { ref domain, ref addr, ttl } => {
try!(buffer.write_qname(domain));
try!(buffer.write_u16(QueryType::A.to_num()));
try!(buffer.write_u16(1));
try!(buffer.write_u32(ttl));
try!(buffer.write_u16(4));
DnsRecord::A {
ref domain,
ref addr,
ttl,
} => {
buffer.write_qname(domain)?;
buffer.write_u16(QueryType::A.to_num())?;
buffer.write_u16(1)?;
buffer.write_u32(ttl)?;
buffer.write_u16(4)?;
let octets = addr.octets();
try!(buffer.write_u8(octets[0]));
try!(buffer.write_u8(octets[1]));
try!(buffer.write_u8(octets[2]));
try!(buffer.write_u8(octets[3]));
},
DnsRecord::NS { ref domain, ref host, ttl } => {
try!(buffer.write_qname(domain));
try!(buffer.write_u16(QueryType::NS.to_num()));
try!(buffer.write_u16(1));
try!(buffer.write_u32(ttl));
buffer.write_u8(octets[0])?;
buffer.write_u8(octets[1])?;
buffer.write_u8(octets[2])?;
buffer.write_u8(octets[3])?;
}
DnsRecord::NS {
ref domain,
ref host,
ttl,
} => {
buffer.write_qname(domain)?;
buffer.write_u16(QueryType::NS.to_num())?;
buffer.write_u16(1)?;
buffer.write_u32(ttl)?;
let pos = buffer.pos();
try!(buffer.write_u16(0));
buffer.write_u16(0)?;
try!(buffer.write_qname(host));
buffer.write_qname(host)?;
let size = buffer.pos() - (pos + 2);
try!(buffer.set_u16(pos, size as u16));
},
DnsRecord::CNAME { ref domain, ref host, ttl } => {
try!(buffer.write_qname(domain));
try!(buffer.write_u16(QueryType::CNAME.to_num()));
try!(buffer.write_u16(1));
try!(buffer.write_u32(ttl));
buffer.set_u16(pos, size as u16)?;
}
DnsRecord::CNAME {
ref domain,
ref host,
ttl,
} => {
buffer.write_qname(domain)?;
buffer.write_u16(QueryType::CNAME.to_num())?;
buffer.write_u16(1)?;
buffer.write_u32(ttl)?;
let pos = buffer.pos();
try!(buffer.write_u16(0));
buffer.write_u16(0)?;
try!(buffer.write_qname(host));
buffer.write_qname(host)?;
let size = buffer.pos() - (pos + 2);
try!(buffer.set_u16(pos, size as u16));
},
DnsRecord::MX { ref domain, priority, ref host, ttl } => {
try!(buffer.write_qname(domain));
try!(buffer.write_u16(QueryType::MX.to_num()));
try!(buffer.write_u16(1));
try!(buffer.write_u32(ttl));
buffer.set_u16(pos, size as u16)?;
}
DnsRecord::MX {
ref domain,
priority,
ref host,
ttl,
} => {
buffer.write_qname(domain)?;
buffer.write_u16(QueryType::MX.to_num())?;
buffer.write_u16(1)?;
buffer.write_u32(ttl)?;
let pos = buffer.pos();
try!(buffer.write_u16(0));
buffer.write_u16(0)?;
try!(buffer.write_u16(priority));
try!(buffer.write_qname(host));
buffer.write_u16(priority)?;
buffer.write_qname(host)?;
let size = buffer.pos() - (pos + 2);
try!(buffer.set_u16(pos, size as u16));
},
DnsRecord::AAAA { ref domain, ref addr, ttl } => {
try!(buffer.write_qname(domain));
try!(buffer.write_u16(QueryType::AAAA.to_num()));
try!(buffer.write_u16(1));
try!(buffer.write_u32(ttl));
try!(buffer.write_u16(16));
buffer.set_u16(pos, size as u16)?;
}
DnsRecord::AAAA {
ref domain,
ref addr,
ttl,
} => {
buffer.write_qname(domain)?;
buffer.write_u16(QueryType::AAAA.to_num())?;
buffer.write_u16(1)?;
buffer.write_u32(ttl)?;
buffer.write_u16(16)?;
for octet in &addr.segments() {
try!(buffer.write_u16(*octet));
buffer.write_u16(*octet)?;
}
}
},
DnsRecord::UNKNOWN { .. } => {
println!("Skipping record: {:?}", self);
}
@ -586,7 +618,6 @@ impl DnsRecord {
Ok(buffer.pos() - start_pos)
}
}
#[derive(Clone, Debug)]
@ -595,7 +626,7 @@ pub struct DnsPacket {
pub questions: Vec<DnsQuestion>,
pub answers: Vec<DnsRecord>,
pub authorities: Vec<DnsRecord>,
pub resources: Vec<DnsRecord>
pub resources: Vec<DnsRecord>,
}
impl DnsPacket {
@ -605,57 +636,55 @@ impl DnsPacket {
questions: Vec::new(),
answers: Vec::new(),
authorities: Vec::new(),
resources: Vec::new()
resources: Vec::new(),
}
}
pub fn from_buffer(buffer: &mut BytePacketBuffer) -> Result<DnsPacket> {
let mut result = DnsPacket::new();
try!(result.header.read(buffer));
result.header.read(buffer)?;
for _ in 0..result.header.questions {
let mut question = DnsQuestion::new("".to_string(),
QueryType::UNKNOWN(0));
try!(question.read(buffer));
let mut question = DnsQuestion::new("".to_string(), QueryType::UNKNOWN(0));
question.read(buffer)?;
result.questions.push(question);
}
for _ in 0..result.header.answers {
let rec = try!(DnsRecord::read(buffer));
let rec = DnsRecord::read(buffer)?;
result.answers.push(rec);
}
for _ in 0..result.header.authoritative_entries {
let rec = try!(DnsRecord::read(buffer));
let rec = DnsRecord::read(buffer)?;
result.authorities.push(rec);
}
for _ in 0..result.header.resource_entries {
let rec = try!(DnsRecord::read(buffer));
let rec = DnsRecord::read(buffer)?;
result.resources.push(rec);
}
Ok(result)
}
pub fn write(&mut self, buffer: &mut BytePacketBuffer) -> Result<()>
{
pub fn write(&mut self, buffer: &mut BytePacketBuffer) -> Result<()> {
self.header.questions = self.questions.len() as u16;
self.header.answers = self.answers.len() as u16;
self.header.authoritative_entries = self.authorities.len() as u16;
self.header.resource_entries = self.resources.len() as u16;
try!(self.header.write(buffer));
self.header.write(buffer)?;
for question in &self.questions {
try!(question.write(buffer));
question.write(buffer)?;
}
for rec in &self.answers {
try!(rec.write(buffer));
rec.write(buffer)?;
}
for rec in &self.authorities {
try!(rec.write(buffer));
rec.write(buffer)?;
}
for rec in &self.resources {
try!(rec.write(buffer));
rec.write(buffer)?;
}
Ok(())
@ -663,29 +692,31 @@ impl DnsPacket {
}
fn lookup(qname: &str, qtype: QueryType, server: (&str, u16)) -> Result<DnsPacket> {
let socket = try!(UdpSocket::bind(("0.0.0.0", 43210)));
let socket = UdpSocket::bind(("0.0.0.0", 43210))?;
let mut packet = DnsPacket::new();
packet.header.id = 6666;
packet.header.questions = 1;
packet.header.recursion_desired = true;
packet.questions.push(DnsQuestion::new(qname.to_string(), qtype));
packet
.questions
.push(DnsQuestion::new(qname.to_string(), qtype));
let mut req_buffer = BytePacketBuffer::new();
packet.write(&mut req_buffer).unwrap();
try!(socket.send_to(&req_buffer.buf[0..req_buffer.pos], server));
packet.write(&mut req_buffer)?;
socket.send_to(&req_buffer.buf[0..req_buffer.pos], server)?;
let mut res_buffer = BytePacketBuffer::new();
socket.recv_from(&mut res_buffer.buf).unwrap();
socket.recv_from(&mut res_buffer.buf)?;
DnsPacket::from_buffer(&mut res_buffer)
}
fn main() {
fn main() -> Result<()> {
let server = ("8.8.8.8", 53);
let socket = UdpSocket::bind(("0.0.0.0", 2053)).unwrap();
let socket = UdpSocket::bind(("0.0.0.0", 2053))?;
loop {
let mut req_buffer = BytePacketBuffer::new();
@ -713,8 +744,7 @@ fn main() {
if request.questions.is_empty() {
packet.header.rescode = ResultCode::FORMERR;
}
else {
} else {
let question = &request.questions[0];
println!("Received query: {:?}", question);
@ -741,7 +771,7 @@ fn main() {
let mut res_buffer = BytePacketBuffer::new();
match packet.write(&mut res_buffer) {
Ok(_) => {},
Ok(_) => {}
Err(e) => {
println!("Failed to encode UDP response packet: {:?}", e);
continue;
@ -758,7 +788,7 @@ fn main() {
};
match socket.send_to(data, src) {
Ok(_) => {},
Ok(_) => {}
Err(e) => {
println!("Failed to send response buffer: {:?}", e);
continue;

View File

@ -1,18 +1,19 @@
use std::io::{Result, Read};
use std::io::{Error, ErrorKind};
use std::net::{Ipv4Addr,Ipv6Addr};
use std::net::UdpSocket;
use std::net::{Ipv4Addr, Ipv6Addr};
type Error = Box<dyn std::error::Error>;
type Result<T> = std::result::Result<T, Error>;
pub struct BytePacketBuffer {
pub buf: [u8; 512],
pub pos: usize
pub pos: usize,
}
impl BytePacketBuffer {
pub fn new() -> BytePacketBuffer {
BytePacketBuffer {
buf: [0; 512],
pos: 0
pos: 0,
}
}
@ -34,7 +35,7 @@ impl BytePacketBuffer {
fn read(&mut self) -> Result<u8> {
if self.pos >= 512 {
return Err(Error::new(ErrorKind::InvalidInput, "End of buffer"));
return Err("End of buffer".into());
}
let res = self.buf[self.pos];
self.pos += 1;
@ -44,61 +45,66 @@ impl BytePacketBuffer {
fn get(&mut self, pos: usize) -> Result<u8> {
if pos >= 512 {
return Err(Error::new(ErrorKind::InvalidInput, "End of buffer"));
return Err("End of buffer".into());
}
Ok(self.buf[pos])
}
fn get_range(&mut self, start: usize, len: usize) -> Result<&[u8]> {
if start + len >= 512 {
return Err(Error::new(ErrorKind::InvalidInput, "End of buffer"));
return Err("End of buffer".into());
}
Ok(&self.buf[start..start+len as usize])
Ok(&self.buf[start..start + len as usize])
}
fn read_u16(&mut self) -> Result<u16>
{
let res = ((try!(self.read()) as u16) << 8) |
(try!(self.read()) as u16);
fn read_u16(&mut self) -> Result<u16> {
let res = ((self.read()? as u16) << 8) | (self.read()? as u16);
Ok(res)
}
fn read_u32(&mut self) -> Result<u32>
{
let res = ((try!(self.read()) as u32) << 24) |
((try!(self.read()) as u32) << 16) |
((try!(self.read()) as u32) << 8) |
((try!(self.read()) as u32) << 0);
fn read_u32(&mut self) -> Result<u32> {
let res = ((self.read()? as u32) << 24)
| ((self.read()? as u32) << 16)
| ((self.read()? as u32) << 8)
| ((self.read()? as u32) << 0);
Ok(res)
}
fn read_qname(&mut self, outstr: &mut String) -> Result<()>
{
fn read_qname(&mut self, outstr: &mut String) -> Result<()> {
let mut pos = self.pos();
let mut jumped = false;
let mut delim = "";
let max_jumps = 5;
let mut jumps_performed = 0;
loop {
let len = try!(self.get(pos));
// Dns Packets are untrusted data, so we need to be paranoid. Someone
// can craft a packet with a cycle in the jump instructions. This guards
// against such packets.
if jumps_performed > max_jumps {
return Err(format!("Limit of {} jumps exceeded", max_jumps).into());
}
let len = self.get(pos)?;
// A two byte sequence, where the two highest bits of the first byte is
// set, represents a offset relative to the start of the buffer. We
// handle this by jumping to the offset, setting a flag to indicate
// that we shouldn't update the shared buffer position once done.
if (len & 0xC0) == 0xC0 {
// When a jump is performed, we only modify the shared buffer
// position once, and avoid making the change later on.
if !jumped {
try!(self.seek(pos+2));
self.seek(pos + 2)?;
}
let b2 = try!(self.get(pos+1)) as u16;
let b2 = self.get(pos + 1)? as u16;
let offset = (((len as u16) ^ 0xC0) << 8) | b2;
pos = offset as usize;
jumped = true;
jumps_performed += 1;
continue;
}
@ -111,7 +117,7 @@ impl BytePacketBuffer {
outstr.push_str(delim);
let str_buffer = try!(self.get_range(pos, len as usize));
let str_buffer = self.get_range(pos, len as usize)?;
outstr.push_str(&String::from_utf8_lossy(str_buffer).to_lowercase());
delim = ".";
@ -120,7 +126,7 @@ impl BytePacketBuffer {
}
if !jumped {
try!(self.seek(pos));
self.seek(pos)?;
}
Ok(())
@ -128,7 +134,7 @@ impl BytePacketBuffer {
fn write(&mut self, val: u8) -> Result<()> {
if self.pos >= 512 {
return Err(Error::new(ErrorKind::InvalidInput, "End of buffer"));
return Err("End of buffer".into());
}
self.buf[self.pos] = val;
self.pos += 1;
@ -136,44 +142,43 @@ impl BytePacketBuffer {
}
fn write_u8(&mut self, val: u8) -> Result<()> {
try!(self.write(val));
self.write(val)?;
Ok(())
}
fn write_u16(&mut self, val: u16) -> Result<()> {
try!(self.write((val >> 8) as u8));
try!(self.write((val & 0xFF) as u8));
self.write((val >> 8) as u8)?;
self.write((val & 0xFF) as u8)?;
Ok(())
}
fn write_u32(&mut self, val: u32) -> Result<()> {
try!(self.write(((val >> 24) & 0xFF) as u8));
try!(self.write(((val >> 16) & 0xFF) as u8));
try!(self.write(((val >> 8) & 0xFF) as u8));
try!(self.write(((val >> 0) & 0xFF) as u8));
self.write(((val >> 24) & 0xFF) as u8)?;
self.write(((val >> 16) & 0xFF) as u8)?;
self.write(((val >> 8) & 0xFF) as u8)?;
self.write(((val >> 0) & 0xFF) as u8)?;
Ok(())
}
fn write_qname(&mut self, qname: &str) -> Result<()> {
let split_str = qname.split('.').collect::<Vec<&str>>();
for label in split_str {
let len = label.len();
if len > 0x34 {
return Err(Error::new(ErrorKind::InvalidInput, "Single label exceeds 63 characters of length"));
return Err("Single label exceeds 63 characters of length".into());
}
try!(self.write_u8(len as u8));
self.write_u8(len as u8)?;
for b in label.as_bytes() {
try!(self.write_u8(*b));
self.write_u8(*b)?;
}
}
try!(self.write_u8(0));
self.write_u8(0)?;
Ok(())
}
@ -185,21 +190,21 @@ impl BytePacketBuffer {
}
fn set_u16(&mut self, pos: usize, val: u16) -> Result<()> {
try!(self.set(pos,(val >> 8) as u8));
try!(self.set(pos+1,(val & 0xFF) as u8));
self.set(pos, (val >> 8) as u8)?;
self.set(pos + 1, (val & 0xFF) as u8)?;
Ok(())
}
}
#[derive(Copy,Clone,Debug,PartialEq,Eq)]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum ResultCode {
NOERROR = 0,
FORMERR = 1,
SERVFAIL = 2,
NXDOMAIN = 3,
NOTIMP = 4,
REFUSED = 5
REFUSED = 5,
}
impl ResultCode {
@ -210,12 +215,12 @@ impl ResultCode {
3 => ResultCode::NXDOMAIN,
4 => ResultCode::NOTIMP,
5 => ResultCode::REFUSED,
0 | _ => ResultCode::NOERROR
0 | _ => ResultCode::NOERROR,
}
}
}
#[derive(Clone,Debug)]
#[derive(Clone, Debug)]
pub struct DnsHeader {
pub id: u16, // 16 bits
@ -234,12 +239,13 @@ pub struct DnsHeader {
pub questions: u16, // 16 bits
pub answers: u16, // 16 bits
pub authoritative_entries: u16, // 16 bits
pub resource_entries: u16 // 16 bits
pub resource_entries: u16, // 16 bits
}
impl DnsHeader {
pub fn new() -> DnsHeader {
DnsHeader { id: 0,
DnsHeader {
id: 0,
recursion_desired: false,
truncated_message: false,
@ -256,13 +262,14 @@ impl DnsHeader {
questions: 0,
answers: 0,
authoritative_entries: 0,
resource_entries: 0 }
resource_entries: 0,
}
}
pub fn read(&mut self, buffer: &mut BytePacketBuffer) -> Result<()> {
self.id = try!(buffer.read_u16());
self.id = buffer.read_u16()?;
let flags = try!(buffer.read_u16());
let flags = buffer.read_u16()?;
let a = (flags >> 8) as u8;
let b = (flags & 0xFF) as u8;
self.recursion_desired = (a & (1 << 0)) > 0;
@ -277,40 +284,44 @@ impl DnsHeader {
self.z = (b & (1 << 6)) > 0;
self.recursion_available = (b & (1 << 7)) > 0;
self.questions = try!(buffer.read_u16());
self.answers = try!(buffer.read_u16());
self.authoritative_entries = try!(buffer.read_u16());
self.resource_entries = try!(buffer.read_u16());
self.questions = buffer.read_u16()?;
self.answers = buffer.read_u16()?;
self.authoritative_entries = buffer.read_u16()?;
self.resource_entries = buffer.read_u16()?;
// Return the constant header size
Ok(())
}
pub fn write(&self, buffer: &mut BytePacketBuffer) -> Result<()> {
try!(buffer.write_u16(self.id));
buffer.write_u16(self.id)?;
try!(buffer.write_u8( ((self.recursion_desired as u8)) |
((self.truncated_message as u8) << 1) |
((self.authoritative_answer as u8) << 2) |
(self.opcode << 3) |
((self.response as u8) << 7) as u8) );
buffer.write_u8(
(self.recursion_desired as u8)
| ((self.truncated_message as u8) << 1)
| ((self.authoritative_answer as u8) << 2)
| (self.opcode << 3)
| ((self.response as u8) << 7) as u8,
)?;
try!(buffer.write_u8( (self.rescode.clone() as u8) |
((self.checking_disabled as u8) << 4) |
((self.authed_data as u8) << 5) |
((self.z as u8) << 6) |
((self.recursion_available as u8) << 7) ));
buffer.write_u8(
(self.rescode.clone() as u8)
| ((self.checking_disabled as u8) << 4)
| ((self.authed_data as u8) << 5)
| ((self.z as u8) << 6)
| ((self.recursion_available as u8) << 7),
)?;
try!(buffer.write_u16(self.questions));
try!(buffer.write_u16(self.answers));
try!(buffer.write_u16(self.authoritative_entries));
try!(buffer.write_u16(self.resource_entries));
buffer.write_u16(self.questions)?;
buffer.write_u16(self.answers)?;
buffer.write_u16(self.authoritative_entries)?;
buffer.write_u16(self.resource_entries)?;
Ok(())
}
}
#[derive(PartialEq,Eq,Debug,Clone,Hash,Copy)]
#[derive(PartialEq, Eq, Debug, Clone, Hash, Copy)]
pub enum QueryType {
UNKNOWN(u16),
A, // 1
@ -339,246 +350,267 @@ impl QueryType {
5 => QueryType::CNAME,
15 => QueryType::MX,
28 => QueryType::AAAA,
_ => QueryType::UNKNOWN(num)
_ => QueryType::UNKNOWN(num),
}
}
}
#[derive(Debug,Clone,PartialEq,Eq)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DnsQuestion {
pub name: String,
pub qtype: QueryType
pub qtype: QueryType,
}
impl DnsQuestion {
pub fn new(name: String, qtype: QueryType) -> DnsQuestion {
DnsQuestion {
name: name,
qtype: qtype
qtype: qtype,
}
}
pub fn read(&mut self, buffer: &mut BytePacketBuffer) -> Result<()> {
try!(buffer.read_qname(&mut self.name));
self.qtype = QueryType::from_num(try!(buffer.read_u16())); // qtype
let _ = try!(buffer.read_u16()); // class
buffer.read_qname(&mut self.name)?;
self.qtype = QueryType::from_num(buffer.read_u16()?); // qtype
let _ = buffer.read_u16()?; // class
Ok(())
}
pub fn write(&self, buffer: &mut BytePacketBuffer) -> Result<()> {
try!(buffer.write_qname(&self.name));
buffer.write_qname(&self.name)?;
let typenum = self.qtype.to_num();
try!(buffer.write_u16(typenum));
try!(buffer.write_u16(1));
buffer.write_u16(typenum)?;
buffer.write_u16(1)?;
Ok(())
}
}
#[derive(Debug,Clone,PartialEq,Eq,Hash,PartialOrd,Ord)]
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[allow(dead_code)]
pub enum DnsRecord {
UNKNOWN {
domain: String,
qtype: u16,
data_len: u16,
ttl: u32
ttl: u32,
}, // 0
A {
domain: String,
addr: Ipv4Addr,
ttl: u32
ttl: u32,
}, // 1
NS {
domain: String,
host: String,
ttl: u32
ttl: u32,
}, // 2
CNAME {
domain: String,
host: String,
ttl: u32
ttl: u32,
}, // 5
MX {
domain: String,
priority: u16,
host: String,
ttl: u32
ttl: u32,
}, // 15
AAAA {
domain: String,
addr: Ipv6Addr,
ttl: u32
ttl: u32,
}, // 28
}
impl DnsRecord {
pub fn read(buffer: &mut BytePacketBuffer) -> Result<DnsRecord> {
let mut domain = String::new();
try!(buffer.read_qname(&mut domain));
buffer.read_qname(&mut domain)?;
let qtype_num = try!(buffer.read_u16());
let qtype_num = buffer.read_u16()?;
let qtype = QueryType::from_num(qtype_num);
let _ = try!(buffer.read_u16());
let ttl = try!(buffer.read_u32());
let data_len = try!(buffer.read_u16());
let _ = buffer.read_u16()?;
let ttl = buffer.read_u32()?;
let data_len = buffer.read_u16()?;
match qtype {
QueryType::A => {
let raw_addr = try!(buffer.read_u32());
let addr = Ipv4Addr::new(((raw_addr >> 24) & 0xFF) as u8,
let raw_addr = buffer.read_u32()?;
let addr = Ipv4Addr::new(
((raw_addr >> 24) & 0xFF) as u8,
((raw_addr >> 16) & 0xFF) as u8,
((raw_addr >> 8) & 0xFF) as u8,
((raw_addr >> 0) & 0xFF) as u8);
((raw_addr >> 0) & 0xFF) as u8,
);
Ok(DnsRecord::A {
domain: domain,
addr: addr,
ttl: ttl
ttl: ttl,
})
},
}
QueryType::AAAA => {
let raw_addr1 = try!(buffer.read_u32());
let raw_addr2 = try!(buffer.read_u32());
let raw_addr3 = try!(buffer.read_u32());
let raw_addr4 = try!(buffer.read_u32());
let addr = Ipv6Addr::new(((raw_addr1 >> 16) & 0xFFFF) as u16,
let raw_addr1 = buffer.read_u32()?;
let raw_addr2 = buffer.read_u32()?;
let raw_addr3 = buffer.read_u32()?;
let raw_addr4 = buffer.read_u32()?;
let addr = Ipv6Addr::new(
((raw_addr1 >> 16) & 0xFFFF) as u16,
((raw_addr1 >> 0) & 0xFFFF) as u16,
((raw_addr2 >> 16) & 0xFFFF) as u16,
((raw_addr2 >> 0) & 0xFFFF) as u16,
((raw_addr3 >> 16) & 0xFFFF) as u16,
((raw_addr3 >> 0) & 0xFFFF) as u16,
((raw_addr4 >> 16) & 0xFFFF) as u16,
((raw_addr4 >> 0) & 0xFFFF) as u16);
((raw_addr4 >> 0) & 0xFFFF) as u16,
);
Ok(DnsRecord::AAAA {
domain: domain,
addr: addr,
ttl: ttl
ttl: ttl,
})
},
}
QueryType::NS => {
let mut ns = String::new();
try!(buffer.read_qname(&mut ns));
buffer.read_qname(&mut ns)?;
Ok(DnsRecord::NS {
domain: domain,
host: ns,
ttl: ttl
ttl: ttl,
})
},
}
QueryType::CNAME => {
let mut cname = String::new();
try!(buffer.read_qname(&mut cname));
buffer.read_qname(&mut cname)?;
Ok(DnsRecord::CNAME {
domain: domain,
host: cname,
ttl: ttl
ttl: ttl,
})
},
}
QueryType::MX => {
let priority = try!(buffer.read_u16());
let priority = buffer.read_u16()?;
let mut mx = String::new();
try!(buffer.read_qname(&mut mx));
buffer.read_qname(&mut mx)?;
Ok(DnsRecord::MX {
domain: domain,
priority: priority,
host: mx,
ttl: ttl
ttl: ttl,
})
},
}
QueryType::UNKNOWN(_) => {
try!(buffer.step(data_len as usize));
buffer.step(data_len as usize)?;
Ok(DnsRecord::UNKNOWN {
domain: domain,
qtype: qtype_num,
data_len: data_len,
ttl: ttl
ttl: ttl,
})
}
}
}
pub fn write(&self, buffer: &mut BytePacketBuffer) -> Result<usize> {
let start_pos = buffer.pos();
match *self {
DnsRecord::A { ref domain, ref addr, ttl } => {
try!(buffer.write_qname(domain));
try!(buffer.write_u16(QueryType::A.to_num()));
try!(buffer.write_u16(1));
try!(buffer.write_u32(ttl));
try!(buffer.write_u16(4));
DnsRecord::A {
ref domain,
ref addr,
ttl,
} => {
buffer.write_qname(domain)?;
buffer.write_u16(QueryType::A.to_num())?;
buffer.write_u16(1)?;
buffer.write_u32(ttl)?;
buffer.write_u16(4)?;
let octets = addr.octets();
try!(buffer.write_u8(octets[0]));
try!(buffer.write_u8(octets[1]));
try!(buffer.write_u8(octets[2]));
try!(buffer.write_u8(octets[3]));
},
DnsRecord::NS { ref domain, ref host, ttl } => {
try!(buffer.write_qname(domain));
try!(buffer.write_u16(QueryType::NS.to_num()));
try!(buffer.write_u16(1));
try!(buffer.write_u32(ttl));
buffer.write_u8(octets[0])?;
buffer.write_u8(octets[1])?;
buffer.write_u8(octets[2])?;
buffer.write_u8(octets[3])?;
}
DnsRecord::NS {
ref domain,
ref host,
ttl,
} => {
buffer.write_qname(domain)?;
buffer.write_u16(QueryType::NS.to_num())?;
buffer.write_u16(1)?;
buffer.write_u32(ttl)?;
let pos = buffer.pos();
try!(buffer.write_u16(0));
buffer.write_u16(0)?;
try!(buffer.write_qname(host));
buffer.write_qname(host)?;
let size = buffer.pos() - (pos + 2);
try!(buffer.set_u16(pos, size as u16));
},
DnsRecord::CNAME { ref domain, ref host, ttl } => {
try!(buffer.write_qname(domain));
try!(buffer.write_u16(QueryType::CNAME.to_num()));
try!(buffer.write_u16(1));
try!(buffer.write_u32(ttl));
buffer.set_u16(pos, size as u16)?;
}
DnsRecord::CNAME {
ref domain,
ref host,
ttl,
} => {
buffer.write_qname(domain)?;
buffer.write_u16(QueryType::CNAME.to_num())?;
buffer.write_u16(1)?;
buffer.write_u32(ttl)?;
let pos = buffer.pos();
try!(buffer.write_u16(0));
buffer.write_u16(0)?;
try!(buffer.write_qname(host));
buffer.write_qname(host)?;
let size = buffer.pos() - (pos + 2);
try!(buffer.set_u16(pos, size as u16));
},
DnsRecord::MX { ref domain, priority, ref host, ttl } => {
try!(buffer.write_qname(domain));
try!(buffer.write_u16(QueryType::MX.to_num()));
try!(buffer.write_u16(1));
try!(buffer.write_u32(ttl));
buffer.set_u16(pos, size as u16)?;
}
DnsRecord::MX {
ref domain,
priority,
ref host,
ttl,
} => {
buffer.write_qname(domain)?;
buffer.write_u16(QueryType::MX.to_num())?;
buffer.write_u16(1)?;
buffer.write_u32(ttl)?;
let pos = buffer.pos();
try!(buffer.write_u16(0));
buffer.write_u16(0)?;
try!(buffer.write_u16(priority));
try!(buffer.write_qname(host));
buffer.write_u16(priority)?;
buffer.write_qname(host)?;
let size = buffer.pos() - (pos + 2);
try!(buffer.set_u16(pos, size as u16));
},
DnsRecord::AAAA { ref domain, ref addr, ttl } => {
try!(buffer.write_qname(domain));
try!(buffer.write_u16(QueryType::AAAA.to_num()));
try!(buffer.write_u16(1));
try!(buffer.write_u32(ttl));
try!(buffer.write_u16(16));
buffer.set_u16(pos, size as u16)?;
}
DnsRecord::AAAA {
ref domain,
ref addr,
ttl,
} => {
buffer.write_qname(domain)?;
buffer.write_u16(QueryType::AAAA.to_num())?;
buffer.write_u16(1)?;
buffer.write_u32(ttl)?;
buffer.write_u16(16)?;
for octet in &addr.segments() {
try!(buffer.write_u16(*octet));
buffer.write_u16(*octet)?;
}
}
},
DnsRecord::UNKNOWN { .. } => {
println!("Skipping record: {:?}", self);
}
@ -586,7 +618,6 @@ impl DnsRecord {
Ok(buffer.pos() - start_pos)
}
}
#[derive(Clone, Debug)]
@ -595,7 +626,7 @@ pub struct DnsPacket {
pub questions: Vec<DnsQuestion>,
pub answers: Vec<DnsRecord>,
pub authorities: Vec<DnsRecord>,
pub resources: Vec<DnsRecord>
pub resources: Vec<DnsRecord>,
}
impl DnsPacket {
@ -605,57 +636,55 @@ impl DnsPacket {
questions: Vec::new(),
answers: Vec::new(),
authorities: Vec::new(),
resources: Vec::new()
resources: Vec::new(),
}
}
pub fn from_buffer(buffer: &mut BytePacketBuffer) -> Result<DnsPacket> {
let mut result = DnsPacket::new();
try!(result.header.read(buffer));
result.header.read(buffer)?;
for _ in 0..result.header.questions {
let mut question = DnsQuestion::new("".to_string(),
QueryType::UNKNOWN(0));
try!(question.read(buffer));
let mut question = DnsQuestion::new("".to_string(), QueryType::UNKNOWN(0));
question.read(buffer)?;
result.questions.push(question);
}
for _ in 0..result.header.answers {
let rec = try!(DnsRecord::read(buffer));
let rec = DnsRecord::read(buffer)?;
result.answers.push(rec);
}
for _ in 0..result.header.authoritative_entries {
let rec = try!(DnsRecord::read(buffer));
let rec = DnsRecord::read(buffer)?;
result.authorities.push(rec);
}
for _ in 0..result.header.resource_entries {
let rec = try!(DnsRecord::read(buffer));
let rec = DnsRecord::read(buffer)?;
result.resources.push(rec);
}
Ok(result)
}
pub fn write(&mut self, buffer: &mut BytePacketBuffer) -> Result<()>
{
pub fn write(&mut self, buffer: &mut BytePacketBuffer) -> Result<()> {
self.header.questions = self.questions.len() as u16;
self.header.answers = self.answers.len() as u16;
self.header.authoritative_entries = self.authorities.len() as u16;
self.header.resource_entries = self.resources.len() as u16;
try!(self.header.write(buffer));
self.header.write(buffer)?;
for question in &self.questions {
try!(question.write(buffer));
question.write(buffer)?;
}
for rec in &self.answers {
try!(rec.write(buffer));
rec.write(buffer)?;
}
for rec in &self.authorities {
try!(rec.write(buffer));
rec.write(buffer)?;
}
for rec in &self.resources {
try!(rec.write(buffer));
rec.write(buffer)?;
}
Ok(())
@ -664,7 +693,7 @@ impl DnsPacket {
pub fn get_random_a(&self) -> Option<String> {
if !self.answers.is_empty() {
let a_record = &self.answers[0];
if let DnsRecord::A{ ref addr, .. } = *a_record {
if let DnsRecord::A { ref addr, .. } = *a_record {
return Some(addr.to_string());
}
}
@ -673,16 +702,25 @@ impl DnsPacket {
}
pub fn get_resolved_ns(&self, qname: &str) -> Option<String> {
let mut new_authorities = Vec::new();
for auth in &self.authorities {
if let DnsRecord::NS { ref domain, ref host, .. } = *auth {
if let DnsRecord::NS {
ref domain,
ref host,
..
} = *auth
{
if !qname.ends_with(domain) {
continue;
}
for rsrc in &self.resources {
if let DnsRecord::A{ ref domain, ref addr, ttl } = *rsrc {
if let DnsRecord::A {
ref domain,
ref addr,
ttl,
} = *rsrc
{
if domain != host {
continue;
}
@ -690,7 +728,7 @@ impl DnsPacket {
let rec = DnsRecord::A {
domain: host.clone(),
addr: *addr,
ttl: ttl
ttl: ttl,
};
new_authorities.push(rec);
@ -709,10 +747,14 @@ impl DnsPacket {
}
pub fn get_unresolved_ns(&self, qname: &str) -> Option<String> {
let mut new_authorities = Vec::new();
for auth in &self.authorities {
if let DnsRecord::NS { ref domain, ref host, .. } = *auth {
if let DnsRecord::NS {
ref domain,
ref host,
..
} = *auth
{
if !qname.ends_with(domain) {
continue;
}
@ -727,31 +769,31 @@ impl DnsPacket {
None
}
}
fn lookup(qname: &str, qtype: QueryType, server: (&str, u16)) -> Result<DnsPacket> {
let socket = try!(UdpSocket::bind(("0.0.0.0", 43210)));
let socket = UdpSocket::bind(("0.0.0.0", 43210))?;
let mut packet = DnsPacket::new();
packet.header.id = 6666;
packet.header.questions = 1;
packet.header.recursion_desired = true;
packet.questions.push(DnsQuestion::new(qname.to_string(), qtype));
packet
.questions
.push(DnsQuestion::new(qname.to_string(), qtype));
let mut req_buffer = BytePacketBuffer::new();
packet.write(&mut req_buffer).unwrap();
try!(socket.send_to(&req_buffer.buf[0..req_buffer.pos], server));
packet.write(&mut req_buffer)?;
socket.send_to(&req_buffer.buf[0..req_buffer.pos], server)?;
let mut res_buffer = BytePacketBuffer::new();
socket.recv_from(&mut res_buffer.buf).unwrap();
socket.recv_from(&mut res_buffer.buf)?;
DnsPacket::from_buffer(&mut res_buffer)
}
fn recursive_lookup(qname: &str, qtype: QueryType) -> Result<DnsPacket> {
let mut ns = "198.41.0.4".to_string();
// Start querying name servers
@ -761,12 +803,10 @@ fn recursive_lookup(qname: &str, qtype: QueryType) -> Result<DnsPacket> {
let ns_copy = ns.clone();
let server = (ns_copy.as_str(), 53);
let response = try!(lookup(qname, qtype.clone(), server));
let response = lookup(qname, qtype.clone(), server)?;
// If we've got an actual answer, we're done!
if !response.answers.is_empty() &&
response.header.rescode == ResultCode::NOERROR {
if !response.answers.is_empty() && response.header.rescode == ResultCode::NOERROR {
return Ok(response.clone());
}
@ -786,23 +826,23 @@ fn recursive_lookup(qname: &str, qtype: QueryType) -> Result<DnsPacket> {
// If not, we'll have to resolve the ip of a NS record
let new_ns_name = match response.get_unresolved_ns(qname) {
Some(x) => x,
None => return Ok(response.clone())
None => return Ok(response.clone()),
};
// Recursively resolve the NS
let recursive_response = try!(recursive_lookup(&new_ns_name, QueryType::A));
let recursive_response = recursive_lookup(&new_ns_name, QueryType::A)?;
// Pick a random IP and restart
if let Some(new_ns) = recursive_response.get_random_a() {
ns = new_ns.clone();
} else {
return Ok(response.clone())
return Ok(response.clone());
}
}
}
fn main() {
let socket = UdpSocket::bind(("0.0.0.0", 2053)).unwrap();
fn main() -> Result<()> {
let socket = UdpSocket::bind(("0.0.0.0", 2053))?;
loop {
let mut req_buffer = BytePacketBuffer::new();
@ -830,8 +870,7 @@ fn main() {
if request.questions.is_empty() {
packet.header.rescode = ResultCode::FORMERR;
}
else {
} else {
let question = &request.questions[0];
println!("Received query: {:?}", question);
@ -858,7 +897,7 @@ fn main() {
let mut res_buffer = BytePacketBuffer::new();
match packet.write(&mut res_buffer) {
Ok(_) => {},
Ok(_) => {}
Err(e) => {
println!("Failed to encode UDP response packet: {:?}", e);
continue;
@ -875,7 +914,7 @@ fn main() {
};
match socket.send_to(data, src) {
Ok(_) => {},
Ok(_) => {}
Err(e) => {
println!("Failed to send response buffer: {:?}", e);
continue;