Skip to content

Commit

Permalink
format the dns codebase
Browse files Browse the repository at this point in the history
  • Loading branch information
muathendirangu committed Jan 23, 2024
1 parent 7d8cb58 commit 1ebc623
Show file tree
Hide file tree
Showing 10 changed files with 64 additions and 89 deletions.
29 changes: 13 additions & 16 deletions src/buffer/buffer.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::utils::types::Result;

pub struct BytePacketBuffer{
pub struct BytePacketBuffer {
pub buf: [u8; 512],
pub pos: usize,
}
Expand All @@ -11,7 +11,7 @@ impl BytePacketBuffer {
///This gives us a fresh new BytePacketBuffer for holding the packet contents
/// and a field for keeping track of where we are in the buffer
pub fn new() -> BytePacketBuffer {
BytePacketBuffer{
BytePacketBuffer {
buf: [0; 512],
pos: 0,
}
Expand All @@ -23,7 +23,7 @@ impl BytePacketBuffer {
}

//step the buffer position forward a certain number of position
pub fn step(&mut self, steps: usize) -> Result<()>{
pub fn step(&mut self, steps: usize) -> Result<()> {
self.pos += steps;
Ok(())
}
Expand Down Expand Up @@ -57,7 +57,7 @@ impl BytePacketBuffer {
if start + len > 512 {
return Err("End of buffer".into());
}
Ok(&self.buf[start..start+len as usize])
Ok(&self.buf[start..start + len as usize])
}

//read two bytes stepping two bytes forward
Expand All @@ -69,9 +69,9 @@ impl BytePacketBuffer {
//read four bytes stepping four bytes forward
pub 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;
| (self.read()? as u32) << 16
| (self.read()? as u32) << 8
| (self.read()? as u32) << 0;
Ok(res)
}

Expand All @@ -88,7 +88,6 @@ impl BytePacketBuffer {
// using this variable.
let mut qname_pos = self.pos();


// track wether we have jumped or not
let mut jumped = false;
let max_jumps = 5;
Expand All @@ -101,8 +100,8 @@ impl BytePacketBuffer {
loop {
//Dns packets are untrusted data so we need to have a guard against malicious packets
// for instance one can craft a packet with a cycle in the jump instructions
if jumps_performed > max_jumps{
return Err(format!("Limit of {} jumps exceeded", max_jumps).into());
if jumps_performed > max_jumps {
return Err(format!("Limit of {} jumps exceeded", max_jumps).into());
}

// at this point we are at the begining of a label
Expand All @@ -121,7 +120,7 @@ impl BytePacketBuffer {
// read another byte, calculate the the offset and perform the jump
// by updating our local position variable
let b2 = self.get(qname_pos + 1)? as u16;
let offset = ((len as u16)^ 0xC0) << 8 | b2;
let offset = ((len as u16) ^ 0xC0) << 8 | b2;
qname_pos = offset as usize;

//indicate that a jump was performed
Expand Down Expand Up @@ -171,9 +170,9 @@ impl BytePacketBuffer {

//write_u16 writes two bytes
pub fn write_u16(&mut self, byte: u16) -> Result<()> {
self.write((byte >> 8) as u8)?;
self.write((byte & 0xff) as u8)?;
Ok(())
self.write((byte >> 8) as u8)?;
self.write((byte & 0xff) as u8)?;
Ok(())
}

//write_u32 writes four bytes
Expand Down Expand Up @@ -291,5 +290,3 @@ mod tests {
assert!(result.is_ok());
}
}


38 changes: 18 additions & 20 deletions src/dns/dns_header.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
use crate::buffer::buffer::BytePacketBuffer;
use crate::utils::types::Result;


// ResultCode
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum ResultCode {
NOERROR=0,
FORMERR=1,
SERVFAIL=2,
NXDOMAIN=3,
NOTIMP=4,
REFUSED=5,
NOERROR = 0,
FORMERR = 1,
SERVFAIL = 2,
NXDOMAIN = 3,
NOTIMP = 4,
REFUSED = 5,
}

impl ResultCode {
Expand All @@ -21,15 +20,15 @@ impl ResultCode {
3 => ResultCode::NXDOMAIN,
4 => ResultCode::NOTIMP,
5 => ResultCode::REFUSED,
0 | _ => ResultCode::NOERROR
0 | _ => ResultCode::NOERROR,
}
}
}

//DnsHeader
#[derive(Debug, Clone)]
pub struct DnsHeader{
pub id : u16, //16 bits
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
Expand All @@ -48,9 +47,8 @@ pub struct DnsHeader{
pub resource_entries: u16, // 16 bits
}


impl DnsHeader {
pub fn new() -> DnsHeader{
pub fn new() -> DnsHeader {
DnsHeader {
id: 0,

Expand Down Expand Up @@ -106,18 +104,18 @@ impl DnsHeader {
// Write recursion_desired flag
buffer.write_u8(
(self.recursion_desired as u8)
| ((self.truncated_message as u8) << 1)
| ((self.authoritative_answer as u8) << 2)
| ((self.opcode as u8) << 3)
| ((self.response as u8) << 7)
| ((self.truncated_message as u8) << 1)
| ((self.authoritative_answer as u8) << 2)
| ((self.opcode as u8) << 3)
| ((self.response as u8) << 7),
)?;
// write rescode
buffer.write_u8(
(self.rescode 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)
| ((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_u16(self.questions)?;
Expand Down
10 changes: 3 additions & 7 deletions src/dns/dns_lookup.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,15 @@
use std::net::{Ipv4Addr,UdpSocket};

use std::net::{Ipv4Addr, UdpSocket};

use crate::buffer::buffer::BytePacketBuffer;
use crate::utils::types::Result;

use super::query_type::QueryType;
use super::dns_packet::DnsPacket;
use super::dns_header::ResultCode;
use super::dns_packet::DnsPacket;
use super::dns_question::DnsQuestion;

use super::query_type::QueryType;

// Add lookup method to lookup DNS records
fn lookup(query_name: &str, query_type: QueryType, server: (Ipv4Addr, u16)) -> Result<DnsPacket> {

// bind a UDP socket to arbitrary port
let socket = UdpSocket::bind(("0.0.0.0", 42340))?;

Expand Down Expand Up @@ -40,7 +37,6 @@ fn lookup(query_name: &str, query_type: QueryType, server: (Ipv4Addr, u16)) -> R

//`DnsPacket::from_buffer()` is used to parse the response
DnsPacket::from_buffer(&mut res_buffer)

}

// Recursively query name servers until we get an answer or hit an error
Expand Down
14 changes: 6 additions & 8 deletions src/dns/dns_packet.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,21 @@
use std::net::Ipv4Addr;


use crate::buffer::buffer::BytePacketBuffer;
use crate::utils::types::Result;

use super::query_type::QueryType;
use super::dns_header::DnsHeader;
use super::dns_record::DnsRecord;
use super::dns_question::DnsQuestion;
use super::dns_record::DnsRecord;
use super::query_type::QueryType;

///DnsPacket wraps everything together
#[derive(Clone, Debug)]
pub struct DnsPacket{
pub struct DnsPacket {
pub header: DnsHeader,
pub questions: Vec<DnsQuestion>,
pub answers: Vec<DnsRecord>,
pub authorities: Vec<DnsRecord>,
pub resources: Vec<DnsRecord>
pub resources: Vec<DnsRecord>,
}

impl DnsPacket {
Expand All @@ -35,8 +34,7 @@ impl DnsPacket {
result.header.read(buffer)?;

for _ in 0..result.header.questions {
let mut question =
DnsQuestion::new("".to_string(), QueryType::UNKNOWN(0));
let mut question = DnsQuestion::new("".to_string(), QueryType::UNKNOWN(0));
question.read(buffer)?;
result.questions.push(question);
}
Expand Down Expand Up @@ -73,7 +71,7 @@ impl DnsPacket {
auth.write(buffer)?;
}
// write resource entries
for resource in &self.resources{
for resource in &self.resources {
resource.write(buffer)?;
}
Ok(())
Expand Down
12 changes: 5 additions & 7 deletions src/dns/dns_question.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,20 @@
use crate::utils::types::Result;
use crate::buffer::buffer::BytePacketBuffer;

use crate::utils::types::Result;

use super::query_type::QueryType;


//DnsQuestion allows adding of more records later on
#[derive(PartialEq, Eq, Debug,Clone)]
pub struct DnsQuestion{
#[derive(PartialEq, Eq, Debug, Clone)]
pub struct DnsQuestion {
pub name: String,
pub question_type: QueryType,
}

impl DnsQuestion {
pub fn new(name: String, question_type: QueryType) -> DnsQuestion{
pub fn new(name: String, question_type: QueryType) -> DnsQuestion {
DnsQuestion {
name,
question_type
question_type,
}
}
// read DNS question from buffer
Expand Down
18 changes: 7 additions & 11 deletions src/dns/dns_record.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::net::{Ipv4Addr, Ipv6Addr};

use crate::utils::types::Result;
use crate::buffer::buffer::BytePacketBuffer;
use crate::utils::types::Result;

use super::query_type::QueryType;

Expand Down Expand Up @@ -64,11 +64,7 @@ impl DnsRecord {
((raw_addr >> 0) & 0xFF) as u8,
);

Ok(DnsRecord::A {
domain,
addr,
ttl,
})
Ok(DnsRecord::A { domain, addr, ttl })
}
QueryType::NS => {
let mut ns = String::new();
Expand Down Expand Up @@ -159,7 +155,7 @@ impl DnsRecord {
buffer.write_u8(octets[1])?;
buffer.write_u8(octets[2])?;
buffer.write_u8(octets[3])?;
},
}
DnsRecord::NS {
ref domain,
ref host,
Expand All @@ -177,7 +173,7 @@ impl DnsRecord {

let size = buffer.pos() - (pos + 2);
buffer.set_u16(pos, size as u16)?;
},
}
DnsRecord::MX {
ref domain,
priority,
Expand All @@ -197,7 +193,7 @@ impl DnsRecord {

let size = buffer.pos() - (pos + 2);
buffer.set_u16(pos, size as u16)?;
},
}
DnsRecord::CNAME {
ref domain,
ref host,
Expand All @@ -215,7 +211,7 @@ impl DnsRecord {

let size = buffer.pos() - (pos + 2);
buffer.set_u16(pos, size as u16)?;
},
}
DnsRecord::AAAA {
ref domain,
ref addr,
Expand All @@ -230,7 +226,7 @@ impl DnsRecord {
for octet in &addr.segments() {
buffer.write_u16(*octet)?;
}
},
}
DnsRecord::UNKNOWN { .. } => {
println!("skipping unknown record : {:?}", self);
}
Expand Down
6 changes: 3 additions & 3 deletions src/dns/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
pub mod dns_header;
pub mod query_type;
pub mod dns_lookup;
pub mod dns_packet;
pub mod dns_question;
pub mod dns_record;
pub mod dns_packet;
pub mod dns_lookup;
pub mod query_type;
12 changes: 5 additions & 7 deletions src/dns/query_type.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@


//QueryType to represent the record type being queried
#[derive(PartialEq, Eq, Debug, Clone, Hash, Copy)]
pub enum QueryType {
UNKNOWN(u16),
A, //1
NS, //2
A, //1
NS, //2
CNAME, //5
MX, //15
AAAA, //28
MX, //15
AAAA, //28
}

impl QueryType {
Expand All @@ -23,7 +21,7 @@ impl QueryType {
}
}

pub fn from_num(num: u16) -> QueryType{
pub fn from_num(num: u16) -> QueryType {
match num {
1 => QueryType::A,
2 => QueryType::NS,
Expand Down
Loading

0 comments on commit 1ebc623

Please sign in to comment.