dnsguide/samples/sample2.rs

551 lines
15 KiB
Rust
Raw Normal View History

2017-11-23 20:51:20 +07:00
use std::io::{Result, Read};
use std::io::{Error, ErrorKind};
use std::net::Ipv4Addr;
use std::net::UdpSocket;
2016-07-13 19:35:16 +07:00
pub struct BytePacketBuffer {
pub buf: [u8; 512],
pub pos: usize
}
impl BytePacketBuffer {
pub fn new() -> BytePacketBuffer {
BytePacketBuffer {
buf: [0; 512],
pos: 0
}
}
2017-11-23 20:51:20 +07:00
fn pos(&self) -> usize {
2016-07-13 19:35:16 +07:00
self.pos
}
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(())
}
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(())
}
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 {
return Err(Error::new(ErrorKind::InvalidInput, "End of buffer"));
}
let res = self.buf[self.pos];
self.pos += 1;
Ok(res)
}
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 {
return Err(Error::new(ErrorKind::InvalidInput, "End of buffer"));
}
Ok(self.buf[pos])
}
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 {
return Err(Error::new(ErrorKind::InvalidInput, "End of buffer"));
}
Ok(&self.buf[start..start+len as usize])
}
2017-11-23 20:51:20 +07:00
fn read_u16(&mut self) -> Result<u16>
2016-07-13 19:35:16 +07:00
{
let res = ((try!(self.read()) as u16) << 8) |
(try!(self.read()) as u16);
Ok(res)
}
2017-11-23 20:51:20 +07:00
fn read_u32(&mut self) -> Result<u32>
2016-07-13 19:35:16 +07:00
{
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);
Ok(res)
}
2017-11-23 20:51:20 +07:00
fn read_qname(&mut self, outstr: &mut String) -> Result<()>
2016-07-13 19:35:16 +07:00
{
let mut pos = self.pos();
let mut jumped = false;
let mut delim = "";
loop {
let len = try!(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.
2018-03-19 17:37:16 +07:00
if (len & 0xC0) == 0xC0 {
2016-07-13 19:35:16 +07:00
// 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));
}
let b2 = try!(self.get(pos+1)) as u16;
let offset = (((len as u16) ^ 0xC0) << 8) | b2;
pos = offset as usize;
jumped = true;
continue;
}
pos += 1;
// Names are terminated by an empty label of length 0
if len == 0 {
break;
}
outstr.push_str(delim);
let str_buffer = try!(self.get_range(pos, len as usize));
outstr.push_str(&String::from_utf8_lossy(str_buffer).to_lowercase());
delim = ".";
pos += len as usize;
}
if !jumped {
try!(self.seek(pos));
}
Ok(())
}
2017-11-23 20:51:20 +07:00
fn write(&mut self, val: u8) -> Result<()> {
if self.pos >= 512 {
return Err(Error::new(ErrorKind::InvalidInput, "End of buffer"));
}
self.buf[self.pos] = val;
self.pos += 1;
Ok(())
}
fn write_u8(&mut self, val: u8) -> Result<()> {
try!(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));
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));
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"));
}
try!(self.write_u8(len as u8));
for b in label.as_bytes() {
try!(self.write_u8(*b));
}
}
try!(self.write_u8(0));
Ok(())
}
2016-07-13 19:35:16 +07:00
}
#[derive(Copy,Clone,Debug,PartialEq,Eq)]
pub enum ResultCode {
NOERROR = 0,
FORMERR = 1,
SERVFAIL = 2,
NXDOMAIN = 3,
NOTIMP = 4,
REFUSED = 5
}
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,
0 | _ => ResultCode::NOERROR
}
}
}
#[derive(Clone,Debug)]
pub struct DnsHeader {
pub id: u16, // 16 bits
pub recursion_desired: bool, // 1 bit
pub truncated_message: bool, // 1 bit
pub authoritative_answer: bool, // 1 bit
pub opcode: u8, // 4 bits
pub response: bool, // 1 bit
pub rescode: ResultCode, // 4 bits
pub checking_disabled: bool, // 1 bit
pub authed_data: bool, // 1 bit
pub z: bool, // 1 bit
pub recursion_available: bool, // 1 bit
pub questions: u16, // 16 bits
pub answers: u16, // 16 bits
pub authoritative_entries: u16, // 16 bits
pub resource_entries: u16 // 16 bits
}
impl DnsHeader {
pub fn new() -> DnsHeader {
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 }
}
pub fn read(&mut self, buffer: &mut BytePacketBuffer) -> Result<()> {
self.id = try!(buffer.read_u16());
let flags = try!(buffer.read_u16());
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;
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());
// Return the constant header size
Ok(())
}
2017-11-23 20:51:20 +07:00
pub fn write(&self, buffer: &mut BytePacketBuffer) -> Result<()> {
try!(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) );
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) ));
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));
Ok(())
}
2016-07-13 19:35:16 +07:00
}
#[derive(PartialEq,Eq,Debug,Clone,Hash,Copy)]
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,
_ => QueryType::UNKNOWN(num)
}
}
}
#[derive(Debug,Clone,PartialEq,Eq)]
pub struct DnsQuestion {
pub name: String,
pub qtype: QueryType
}
impl DnsQuestion {
pub fn new(name: String, qtype: QueryType) -> DnsQuestion {
DnsQuestion {
name: name,
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
Ok(())
}
2017-11-23 20:51:20 +07:00
pub fn write(&self, buffer: &mut BytePacketBuffer) -> Result<()> {
try!(buffer.write_qname(&self.name));
let typenum = self.qtype.to_num();
try!(buffer.write_u16(typenum));
try!(buffer.write_u16(1));
Ok(())
}
2016-07-13 19:35:16 +07:00
}
#[derive(Debug,Clone,PartialEq,Eq,Hash,PartialOrd,Ord)]
#[allow(dead_code)]
pub enum DnsRecord {
UNKNOWN {
domain: String,
qtype: u16,
data_len: u16,
ttl: u32
}, // 0
A {
domain: String,
addr: Ipv4Addr,
ttl: u32
}, // 1
}
impl DnsRecord {
pub fn read(buffer: &mut BytePacketBuffer) -> Result<DnsRecord> {
let mut domain = String::new();
try!(buffer.read_qname(&mut domain));
let qtype_num = try!(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());
match qtype {
QueryType::A => {
let raw_addr = try!(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);
Ok(DnsRecord::A {
domain: domain,
addr: addr,
ttl: ttl
})
},
QueryType::UNKNOWN(_) => {
try!(buffer.step(data_len as usize));
Ok(DnsRecord::UNKNOWN {
domain: domain,
qtype: qtype_num,
data_len: data_len,
ttl: ttl
})
}
}
}
2017-11-23 20:51:20 +07:00
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));
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::UNKNOWN { .. } => {
println!("Skipping record: {:?}", self);
}
}
Ok(buffer.pos() - start_pos)
}
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>,
pub resources: Vec<DnsRecord>
}
impl DnsPacket {
pub fn new() -> DnsPacket {
DnsPacket {
header: DnsHeader::new(),
questions: Vec::new(),
answers: Vec::new(),
authorities: Vec::new(),
resources: Vec::new()
}
}
pub fn from_buffer(buffer: &mut BytePacketBuffer) -> Result<DnsPacket> {
let mut result = DnsPacket::new();
try!(result.header.read(buffer));
for _ in 0..result.header.questions {
let mut question = DnsQuestion::new("".to_string(),
QueryType::UNKNOWN(0));
try!(question.read(buffer));
result.questions.push(question);
}
for _ in 0..result.header.answers {
let rec = try!(DnsRecord::read(buffer));
result.answers.push(rec);
}
for _ in 0..result.header.authoritative_entries {
let rec = try!(DnsRecord::read(buffer));
result.authorities.push(rec);
}
for _ in 0..result.header.resource_entries {
let rec = try!(DnsRecord::read(buffer));
result.resources.push(rec);
}
Ok(result)
}
2017-11-23 20:51:20 +07:00
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));
for question in &self.questions {
try!(question.write(buffer));
}
for rec in &self.answers {
try!(rec.write(buffer));
}
for rec in &self.authorities {
try!(rec.write(buffer));
}
for rec in &self.resources {
try!(rec.write(buffer));
}
Ok(())
}
}
fn main() {
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 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));
let mut req_buffer = BytePacketBuffer::new();
packet.write(&mut req_buffer).unwrap();
socket.send_to(&req_buffer.buf[0..req_buffer.pos], server).unwrap();
let mut res_buffer = BytePacketBuffer::new();
socket.recv_from(&mut res_buffer.buf).unwrap();
let res_packet = DnsPacket::from_buffer(&mut res_buffer).unwrap();
println!("{:?}", res_packet.header);
for q in res_packet.questions {
println!("{:?}", q);
}
for rec in res_packet.answers {
println!("{:?}", rec);
}
for rec in res_packet.authorities {
println!("{:?}", rec);
}
for rec in res_packet.resources {
println!("{:?}", rec);
}
2016-07-13 19:35:16 +07:00
}