dnsguide/examples/sample1.rs

438 lines
12 KiB
Rust
Raw Permalink Normal View History

2017-11-23 20:51:20 +07:00
use std::fs::File;
2020-06-18 05:45:03 +07:00
use std::io::Read;
use std::net::Ipv4Addr;
type Error = Box<dyn std::error::Error>;
type Result<T> = std::result::Result<T, Error>;
2016-07-13 19:35:16 +07:00
pub struct BytePacketBuffer {
pub buf: [u8; 512],
2020-06-18 05:45:03 +07:00
pub pos: usize,
2016-07-13 19:35:16 +07:00
}
impl BytePacketBuffer {
2020-06-18 06:47:09 +07:00
/// This gives us a fresh buffer for holding the packet contents, and a
/// field for keeping track of where we are.
2016-07-13 19:35:16 +07:00
pub fn new() -> BytePacketBuffer {
BytePacketBuffer {
buf: [0; 512],
2020-06-18 05:45:03 +07:00
pos: 0,
2016-07-13 19:35:16 +07:00
}
}
2020-06-18 06:47:09 +07:00
/// Current position within buffer
2017-11-23 20:51:20 +07:00
fn pos(&self) -> usize {
2016-07-13 19:35:16 +07:00
self.pos
}
2020-06-18 06:47:09 +07:00
/// Step the buffer position forward a specific number of steps
2017-11-23 20:51:20 +07:00
fn step(&mut self, steps: usize) -> Result<()> {
2016-07-13 19:35:16 +07:00
self.pos += steps;
Ok(())
}
2020-06-18 06:47:09 +07:00
/// Change the buffer position
2017-11-23 20:51:20 +07:00
fn seek(&mut self, pos: usize) -> Result<()> {
2016-07-13 19:35:16 +07:00
self.pos = pos;
Ok(())
}
2020-06-18 06:47:09 +07:00
/// Read a single byte and move the position one step forward
2017-11-23 20:51:20 +07:00
fn read(&mut self) -> Result<u8> {
2016-07-13 19:35:16 +07:00
if self.pos >= 512 {
2020-06-18 05:45:03 +07:00
return Err("End of buffer".into());
2016-07-13 19:35:16 +07:00
}
let res = self.buf[self.pos];
self.pos += 1;
Ok(res)
}
2020-06-18 06:47:09 +07:00
/// Get a single byte, without changing the buffer position
2017-11-23 20:51:20 +07:00
fn get(&mut self, pos: usize) -> Result<u8> {
2016-07-13 19:35:16 +07:00
if pos >= 512 {
2020-06-18 05:45:03 +07:00
return Err("End of buffer".into());
2016-07-13 19:35:16 +07:00
}
Ok(self.buf[pos])
}
2020-06-18 06:47:09 +07:00
/// Get a range of bytes
2017-11-23 20:51:20 +07:00
fn get_range(&mut self, start: usize, len: usize) -> Result<&[u8]> {
2016-07-13 19:35:16 +07:00
if start + len >= 512 {
2020-06-18 05:45:03 +07:00
return Err("End of buffer".into());
2016-07-13 19:35:16 +07:00
}
2020-06-18 05:45:03 +07:00
Ok(&self.buf[start..start + len as usize])
2016-07-13 19:35:16 +07:00
}
2020-06-18 06:47:09 +07:00
/// Read two bytes, stepping two steps forward
2020-06-18 05:45:03 +07:00
fn read_u16(&mut self) -> Result<u16> {
let res = ((self.read()? as u16) << 8) | (self.read()? as u16);
2016-07-13 19:35:16 +07:00
Ok(res)
}
2020-06-18 06:47:09 +07:00
/// Read four bytes, stepping four steps forward
2020-06-18 05:45:03 +07:00
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);
2016-07-13 19:35:16 +07:00
Ok(res)
}
2020-06-18 06:47:09 +07:00
/// Read a qname
///
/// The tricky part: Reading domain names, taking labels into consideration.
/// Will take something like [3]www[6]google[3]com[0] and append
/// www.google.com to outstr.
2020-06-18 05:45:03 +07:00
fn read_qname(&mut self, outstr: &mut String) -> Result<()> {
2020-06-18 06:47:09 +07:00
// Since we might encounter jumps, we'll keep track of our position
// locally as opposed to using the position within the struct. This
// allows us to move the shared position to a point past our current
// qname, while keeping track of our progress on the current qname
// using this variable.
2016-07-13 19:35:16 +07:00
let mut pos = self.pos();
2020-06-18 06:47:09 +07:00
// track whether or not we've jumped
let mut jumped = false;
2020-06-18 05:45:03 +07:00
let max_jumps = 5;
let mut jumps_performed = 0;
2020-06-18 06:47:09 +07:00
// Our delimiter which we append for each label. Since we don't want a
// dot at the beginning of the domain name we'll leave it empty for now
// and set it to "." at the end of the first iteration.
let mut delim = "";
2016-07-13 19:35:16 +07:00
loop {
2020-06-18 05:45:03 +07:00
// 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());
}
2020-06-18 06:47:09 +07:00
// At this point, we're always at the beginning of a label. Recall
// that labels start with a length byte.
2020-06-18 05:45:03 +07:00
let len = self.get(pos)?;
2016-07-13 19:35:16 +07:00
2020-06-18 06:47:09 +07:00
// If len has the two most significant bit are set, it represents a
// jump to some other offset in the packet:
2018-03-19 17:37:16 +07:00
if (len & 0xC0) == 0xC0 {
2020-06-18 06:47:09 +07:00
// Update the buffer position to a point past the current
// label. We don't need to touch it any further.
2016-07-13 19:35:16 +07:00
if !jumped {
2020-06-18 05:45:03 +07:00
self.seek(pos + 2)?;
2016-07-13 19:35:16 +07:00
}
2020-06-18 06:47:09 +07:00
// Read another byte, calculate offset and perform the jump by
// updating our local position variable
2020-06-18 05:45:03 +07:00
let b2 = self.get(pos + 1)? as u16;
2016-07-13 19:35:16 +07:00
let offset = (((len as u16) ^ 0xC0) << 8) | b2;
pos = offset as usize;
2020-06-18 06:47:09 +07:00
// Indicate that a jump was performed.
2016-07-13 19:35:16 +07:00
jumped = true;
2020-06-18 05:45:03 +07:00
jumps_performed += 1;
2016-07-13 19:35:16 +07:00
2020-06-18 06:47:09 +07:00
continue;
2016-07-13 19:35:16 +07:00
}
2020-06-18 06:47:09 +07:00
// The base scenario, where we're reading a single label and
// appending it to the output:
else {
// Move a single byte forward to move past the length byte.
pos += 1;
// Domain names are terminated by an empty label of length 0,
// so if the length is zero we're done.
if len == 0 {
break;
}
2016-07-13 19:35:16 +07:00
2020-06-18 06:47:09 +07:00
// Append the delimiter to our output buffer first.
outstr.push_str(delim);
2016-07-13 19:35:16 +07:00
2020-06-18 06:47:09 +07:00
// Extract the actual ASCII bytes for this label and append them
// to the output buffer.
let str_buffer = self.get_range(pos, len as usize)?;
outstr.push_str(&String::from_utf8_lossy(str_buffer).to_lowercase());
2016-07-13 19:35:16 +07:00
2020-06-18 06:47:09 +07:00
delim = ".";
2016-07-13 19:35:16 +07:00
2020-06-18 06:47:09 +07:00
// Move forward the full length of the label.
pos += len as usize;
}
2016-07-13 19:35:16 +07:00
}
if !jumped {
2020-06-18 05:45:03 +07:00
self.seek(pos)?;
2016-07-13 19:35:16 +07:00
}
Ok(())
}
}
2020-06-18 05:45:03 +07:00
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2016-07-13 19:35:16 +07:00
pub enum ResultCode {
NOERROR = 0,
FORMERR = 1,
SERVFAIL = 2,
NXDOMAIN = 3,
NOTIMP = 4,
2020-06-18 05:45:03 +07:00
REFUSED = 5,
2016-07-13 19:35:16 +07:00
}
impl ResultCode {
pub fn from_num(num: u8) -> ResultCode {
match num {
1 => ResultCode::FORMERR,
2 => ResultCode::SERVFAIL,
3 => ResultCode::NXDOMAIN,
4 => ResultCode::NOTIMP,
5 => ResultCode::REFUSED,
2020-06-18 05:45:03 +07:00
0 | _ => ResultCode::NOERROR,
2016-07-13 19:35:16 +07:00
}
}
}
2020-06-18 05:45:03 +07:00
#[derive(Clone, Debug)]
2016-07-13 19:35:16 +07:00
pub struct DnsHeader {
pub id: u16, // 16 bits
2020-06-18 05:45:03 +07:00
pub recursion_desired: bool, // 1 bit
pub truncated_message: bool, // 1 bit
2016-07-13 19:35:16 +07:00
pub authoritative_answer: bool, // 1 bit
2020-06-18 05:45:03 +07:00
pub opcode: u8, // 4 bits
pub response: bool, // 1 bit
2016-07-13 19:35:16 +07:00
2020-06-18 05:45:03 +07:00
pub rescode: ResultCode, // 4 bits
pub checking_disabled: bool, // 1 bit
pub authed_data: bool, // 1 bit
pub z: bool, // 1 bit
2016-07-13 19:35:16 +07:00
pub recursion_available: bool, // 1 bit
2020-06-18 05:45:03 +07:00
pub questions: u16, // 16 bits
pub answers: u16, // 16 bits
2016-07-13 19:35:16 +07:00
pub authoritative_entries: u16, // 16 bits
2020-06-18 05:45:03 +07:00
pub resource_entries: u16, // 16 bits
2016-07-13 19:35:16 +07:00
}
impl DnsHeader {
pub fn new() -> DnsHeader {
2020-06-18 05:45:03 +07:00
DnsHeader {
id: 0,
recursion_desired: false,
truncated_message: false,
authoritative_answer: false,
opcode: 0,
response: false,
rescode: ResultCode::NOERROR,
checking_disabled: false,
authed_data: false,
z: false,
recursion_available: false,
questions: 0,
answers: 0,
authoritative_entries: 0,
resource_entries: 0,
}
2016-07-13 19:35:16 +07:00
}
pub fn read(&mut self, buffer: &mut BytePacketBuffer) -> Result<()> {
2020-06-18 05:45:03 +07:00
self.id = buffer.read_u16()?;
2016-07-13 19:35:16 +07:00
2020-06-18 05:45:03 +07:00
let flags = buffer.read_u16()?;
2016-07-13 19:35:16 +07:00
let a = (flags >> 8) as u8;
let b = (flags & 0xFF) as u8;
self.recursion_desired = (a & (1 << 0)) > 0;
self.truncated_message = (a & (1 << 1)) > 0;
self.authoritative_answer = (a & (1 << 2)) > 0;
self.opcode = (a >> 3) & 0x0F;
self.response = (a & (1 << 7)) > 0;
self.rescode = ResultCode::from_num(b & 0x0F);
self.checking_disabled = (b & (1 << 4)) > 0;
self.authed_data = (b & (1 << 5)) > 0;
self.z = (b & (1 << 6)) > 0;
self.recursion_available = (b & (1 << 7)) > 0;
2020-06-18 05:45:03 +07:00
self.questions = buffer.read_u16()?;
self.answers = buffer.read_u16()?;
self.authoritative_entries = buffer.read_u16()?;
self.resource_entries = buffer.read_u16()?;
2016-07-13 19:35:16 +07:00
// Return the constant header size
Ok(())
}
}
2020-06-18 05:45:03 +07:00
#[derive(PartialEq, Eq, Debug, Clone, Hash, Copy)]
2016-07-13 19:35:16 +07:00
pub enum QueryType {
UNKNOWN(u16),
A, // 1
}
impl QueryType {
pub fn to_num(&self) -> u16 {
match *self {
QueryType::UNKNOWN(x) => x,
QueryType::A => 1,
}
}
pub fn from_num(num: u16) -> QueryType {
match num {
1 => QueryType::A,
2020-06-18 05:45:03 +07:00
_ => QueryType::UNKNOWN(num),
2016-07-13 19:35:16 +07:00
}
}
}
2020-06-18 05:45:03 +07:00
#[derive(Debug, Clone, PartialEq, Eq)]
2016-07-13 19:35:16 +07:00
pub struct DnsQuestion {
pub name: String,
2020-06-18 05:45:03 +07:00
pub qtype: QueryType,
2016-07-13 19:35:16 +07:00
}
impl DnsQuestion {
pub fn new(name: String, qtype: QueryType) -> DnsQuestion {
2020-11-28 20:29:04 +07:00
DnsQuestion { name, qtype }
2016-07-13 19:35:16 +07:00
}
pub fn read(&mut self, buffer: &mut BytePacketBuffer) -> Result<()> {
2020-06-18 05:45:03 +07:00
buffer.read_qname(&mut self.name)?;
self.qtype = QueryType::from_num(buffer.read_u16()?); // qtype
let _ = buffer.read_u16()?; // class
2016-07-13 19:35:16 +07:00
Ok(())
}
}
2020-06-18 05:45:03 +07:00
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
2016-07-13 19:35:16 +07:00
#[allow(dead_code)]
pub enum DnsRecord {
UNKNOWN {
domain: String,
qtype: u16,
data_len: u16,
2020-06-18 05:45:03 +07:00
ttl: u32,
2016-07-13 19:35:16 +07:00
}, // 0
A {
domain: String,
addr: Ipv4Addr,
2020-06-18 05:45:03 +07:00
ttl: u32,
2016-07-13 19:35:16 +07:00
}, // 1
}
impl DnsRecord {
pub fn read(buffer: &mut BytePacketBuffer) -> Result<DnsRecord> {
let mut domain = String::new();
2020-06-18 05:45:03 +07:00
buffer.read_qname(&mut domain)?;
2016-07-13 19:35:16 +07:00
2020-06-18 05:45:03 +07:00
let qtype_num = buffer.read_u16()?;
2016-07-13 19:35:16 +07:00
let qtype = QueryType::from_num(qtype_num);
2020-06-18 05:45:03 +07:00
let _ = buffer.read_u16()?;
let ttl = buffer.read_u32()?;
let data_len = buffer.read_u16()?;
2016-07-13 19:35:16 +07:00
match qtype {
2020-06-18 05:45:03 +07:00
QueryType::A => {
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,
);
2016-07-13 19:35:16 +07:00
2020-11-28 20:29:04 +07:00
Ok(DnsRecord::A { domain, addr, ttl })
2020-06-18 05:45:03 +07:00
}
2016-07-13 19:35:16 +07:00
QueryType::UNKNOWN(_) => {
2020-06-18 05:45:03 +07:00
buffer.step(data_len as usize)?;
2016-07-13 19:35:16 +07:00
Ok(DnsRecord::UNKNOWN {
2020-11-28 20:27:23 +07:00
domain,
2016-07-13 19:35:16 +07:00
qtype: qtype_num,
2020-11-28 20:27:23 +07:00
data_len,
ttl,
2016-07-13 19:35:16 +07:00
})
}
}
}
}
#[derive(Clone, Debug)]
pub struct DnsPacket {
pub header: DnsHeader,
pub questions: Vec<DnsQuestion>,
pub answers: Vec<DnsRecord>,
pub authorities: Vec<DnsRecord>,
2020-06-18 05:45:03 +07:00
pub resources: Vec<DnsRecord>,
2016-07-13 19:35:16 +07:00
}
impl DnsPacket {
pub fn new() -> DnsPacket {
DnsPacket {
header: DnsHeader::new(),
questions: Vec::new(),
answers: Vec::new(),
authorities: Vec::new(),
2020-06-18 05:45:03 +07:00
resources: Vec::new(),
2016-07-13 19:35:16 +07:00
}
}
pub fn from_buffer(buffer: &mut BytePacketBuffer) -> Result<DnsPacket> {
let mut result = DnsPacket::new();
2020-06-18 05:45:03 +07:00
result.header.read(buffer)?;
2016-07-13 19:35:16 +07:00
for _ in 0..result.header.questions {
2020-06-18 05:45:03 +07:00
let mut question = DnsQuestion::new("".to_string(), QueryType::UNKNOWN(0));
question.read(buffer)?;
2016-07-13 19:35:16 +07:00
result.questions.push(question);
}
for _ in 0..result.header.answers {
2020-06-18 05:45:03 +07:00
let rec = DnsRecord::read(buffer)?;
2016-07-13 19:35:16 +07:00
result.answers.push(rec);
}
for _ in 0..result.header.authoritative_entries {
2020-06-18 05:45:03 +07:00
let rec = DnsRecord::read(buffer)?;
2016-07-13 19:35:16 +07:00
result.authorities.push(rec);
}
for _ in 0..result.header.resource_entries {
2020-06-18 05:45:03 +07:00
let rec = DnsRecord::read(buffer)?;
2016-07-13 19:35:16 +07:00
result.resources.push(rec);
}
Ok(result)
}
}
2017-11-23 20:51:20 +07:00
2020-06-18 05:45:03 +07:00
fn main() -> Result<()> {
let mut f = File::open("response_packet.txt")?;
2017-11-23 20:51:20 +07:00
let mut buffer = BytePacketBuffer::new();
2020-06-18 05:45:03 +07:00
f.read(&mut buffer.buf)?;
2017-11-23 20:51:20 +07:00
2020-06-18 05:45:03 +07:00
let packet = DnsPacket::from_buffer(&mut buffer)?;
2020-06-18 06:47:09 +07:00
println!("{:#?}", packet.header);
2017-11-23 20:51:20 +07:00
for q in packet.questions {
2020-06-18 06:47:09 +07:00
println!("{:#?}", q);
2017-11-23 20:51:20 +07:00
}
for rec in packet.answers {
2020-06-18 06:47:09 +07:00
println!("{:#?}", rec);
2017-11-23 20:51:20 +07:00
}
for rec in packet.authorities {
2020-06-18 06:47:09 +07:00
println!("{:#?}", rec);
2017-11-23 20:51:20 +07:00
}
for rec in packet.resources {
2020-06-18 06:47:09 +07:00
println!("{:#?}", rec);
2017-11-23 20:51:20 +07:00
}
2020-06-18 05:45:03 +07:00
Ok(())
2017-11-23 20:51:20 +07:00
}