Compare commits

...

3 Commits

15 changed files with 210 additions and 133 deletions

View File

@ -6,11 +6,8 @@ use clap::Parser;
use log::{info, LevelFilter};
use rand::RngCore;
use simplelog::*;
use dnstplib::message::header::{Direction, DNSHeader, Opcode, ResponseCode};
use dnstplib::message::question::{DNSQuestion, QClass, QType};
use dnstplib::message::request::DNSRequest;
use dnstplib::net::socket::DNSSocket;
use dnstplib::net::raw_request::NetworkMessage;
use dnstplib::message::{DNSQuestion, DNSRequest, DNSHeader, QClass, QType, Direction, Opcode, ResponseCode};
use dnstplib::net::{DNSSocket, NetworkMessage};
use dnstplib::processor::ResponseProcesor;
#[derive(Parser, Debug)]
@ -49,31 +46,7 @@ fn main() {
info!("sending...");
let message = DNSRequest {
header: DNSHeader {
id: rng.next_u32() as u16,
direction: Direction::Request,
opcode: Opcode::Query,
authoritative: false,
truncation: false,
recursion_desired: true,
recursion_available: false,
valid_zeroes: true,
response: ResponseCode::NoError,
question_count: 1,
answer_record_count: 0,
authority_record_count: 0,
additional_record_count: 0
},
questions: vec![
DNSQuestion {
qname: "duck.com".to_string(),
qtype: QType::A,
qclass: QClass::Internet
}
],
peer: address
};
let message = DNSRequest::from_hostname(address, rng.next_u32() as u16, "duck.com".to_string());
let bytes = message.to_bytes();

View File

@ -8,7 +8,7 @@ use simplelog::*;
use std::fs::File;
use std::net::SocketAddr;
use dnstplib::net::socket::DNSSocket;
use dnstplib::net::DNSSocket;
use dnstplib::processor::RequestProcesor;
/// Command-line arguments for configuring the server

View File

@ -1,12 +1,12 @@
use std::fmt::{Debug, Formatter};
use std::net::{IpAddr, Ipv4Addr};
use std::net::Ipv4Addr;
use crate::message::answer::RData;
pub struct IpRData {
pub struct ARdata {
pub rdata: Ipv4Addr
}
impl Debug for IpRData {
impl Debug for ARdata {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("IP")
.field("data", &self.rdata)
@ -14,16 +14,16 @@ impl Debug for IpRData {
}
}
impl RData for IpRData {
impl RData for ARdata {
fn to_bytes(&self) -> Vec<u8> {
return self.rdata.octets().to_vec();
}
}
impl IpRData {
pub fn from(rdata: Ipv4Addr) -> IpRData
impl ARdata {
pub fn from(rdata: Ipv4Addr) -> ARdata
{
IpRData {
ARdata {
rdata
}
}

View File

@ -1,17 +1,16 @@
mod raw_rdata;
pub use raw_rdata::RawRData;
mod ip_address;
pub use ip_address::IpRData;
mod a_rdata;
pub use a_rdata::ARdata;
#[cfg(test)]
mod tests;
use std::fmt::{Debug, Display};
use std::fmt::Debug;
use std::fmt::Display;
use crate::byte::{four_byte_split, two_byte_split};
use crate::message::question::{DNSQuestion, QClass, QType, QuestionParseError};
use crate::string::encode_domain_name;
use crate::message::question::{DNSQuestion, QClass, QType};
pub trait RData: Debug {
fn to_bytes(&self) -> Vec<u8>;
@ -19,7 +18,7 @@ pub trait RData: Debug {
#[derive(Debug)]
pub struct DNSAnswer {
pub name: String,
pub name_offset: u16,
pub answer_type: QType,
pub class: QClass,
pub ttl: u32,
@ -31,7 +30,8 @@ impl DNSAnswer {
pub fn to_bytes(&self) -> Vec<u8>
{
let mut ret = encode_domain_name(&self.name);
let (name_1, name_2) = two_byte_split(self.name_offset | (0b11 << 14));
let mut ret = vec![name_1, name_2];
let type_split = two_byte_split(self.answer_type as u16);
ret.push(type_split.0);
@ -56,10 +56,10 @@ impl DNSAnswer {
return ret
}
pub fn from_query(query: &DNSQuestion, data: Box<dyn RData>, ttl: Option<u32>) -> DNSAnswer
pub fn from_query(query: &DNSQuestion, name_offset: u16, data: Box<dyn RData>, ttl: Option<u32>) -> DNSAnswer
{
DNSAnswer {
name: query.qname.clone(),
name_offset,
answer_type: query.qtype,
class: query.qclass,
ttl: ttl.unwrap_or(0),

View File

@ -6,7 +6,8 @@ use super::*;
#[ignore]
fn one_answer_back_and_forth() {
let q = DNSAnswer {
name: "google.com".to_string(),
// name_offset: "google.com".to_string(),
name_offset: 12,
answer_type: QType::A,
class: QClass::Internet,
ttl: 0,
@ -19,7 +20,7 @@ fn one_answer_back_and_forth() {
let (q_read, q_reconstructed) = answers_from_bytes(q_bytes, 0).unwrap();
assert_eq!(q.name, q_reconstructed[0].name);
assert_eq!(q.name_offset, q_reconstructed[0].name_offset);
assert_eq!(q.answer_type, q_reconstructed[0].answer_type);
assert_eq!(q.class, q_reconstructed[0].class);
assert_eq!(q.ttl, q_reconstructed[0].ttl);

View File

@ -1,6 +1,7 @@
use std::convert::TryFrom;
use crate::byte::apply_split_bytes;
use crate::message::header::Direction::Response;
use crate::message::Direction::Response;
/// Size in bytes for a DNS message
pub const HEADER_SIZE: usize = 12;
@ -127,4 +128,26 @@ impl DNSHeader {
header_bytes
}
pub fn new_request(id: u16, questions: Option<u16>) -> DNSHeader
{
DNSHeader {
id,
direction: Direction::Request,
opcode: Opcode::Query,
authoritative: false,
truncation: false,
recursion_desired: true,
recursion_available: false,
valid_zeroes: true,
response: ResponseCode::NoError,
question_count: match questions {
None => 1,
Some(v) => v
},
answer_record_count: 0,
authority_record_count: 0,
additional_record_count: 0
}
}
}

View File

@ -4,3 +4,9 @@ pub mod question;
pub mod request;
pub mod answer;
pub mod response;
pub use question::{DNSQuestion, QClass, QType, QuestionParseError, questions_to_bytes, questions_from_bytes};
pub use answer::{DNSAnswer, RawRData, RData, ARdata, AnswerParseError, answers_to_bytes, answers_from_bytes};
pub use header::{DNSHeader, Direction, Opcode, ResponseCode, HEADER_SIZE};
pub use request::DNSRequest;
pub use response::DNSResponse;

View File

@ -2,8 +2,10 @@
mod tests;
use urlencoding::decode;
use crate::byte::{two_byte_extraction, two_byte_split};
use crate::string::encode_domain_name;
#[repr(u16)]
#[derive(Ord, PartialOrd, Eq, PartialEq, Debug, Copy, Clone)]
pub enum QType {
A = 1,
@ -21,29 +23,30 @@ pub enum QType {
SRV = 33
}
impl TryFrom<u8> for QType {
type Error = u8;
impl TryFrom<u16> for QType {
type Error = u16;
fn try_from(v: u8) -> Result<Self, Self::Error> {
fn try_from(v: u16) -> Result<Self, Self::Error> {
match v {
x if x == QType::A as u8 => Ok(QType::A),
x if x == QType::NS as u8 => Ok(QType::NS),
x if x == QType::CNAME as u8 => Ok(QType::CNAME),
x if x == QType::SOA as u8 => Ok(QType::SOA),
x if x == QType::WKS as u8 => Ok(QType::WKS),
x if x == QType::PTR as u8 => Ok(QType::PTR),
x if x == QType::HINFO as u8 => Ok(QType::HINFO),
x if x == QType::MINFO as u8 => Ok(QType::MINFO),
x if x == QType::MX as u8 => Ok(QType::MX),
x if x == QType::TXT as u8 => Ok(QType::TXT),
x if x == QType::RP as u8 => Ok(QType::RP),
x if x == QType::AAAA as u8 => Ok(QType::AAAA),
x if x == QType::SRV as u8 => Ok(QType::SRV),
x if x == QType::A as u16 => Ok(QType::A),
x if x == QType::NS as u16 => Ok(QType::NS),
x if x == QType::CNAME as u16 => Ok(QType::CNAME),
x if x == QType::SOA as u16 => Ok(QType::SOA),
x if x == QType::WKS as u16 => Ok(QType::WKS),
x if x == QType::PTR as u16 => Ok(QType::PTR),
x if x == QType::HINFO as u16 => Ok(QType::HINFO),
x if x == QType::MINFO as u16 => Ok(QType::MINFO),
x if x == QType::MX as u16 => Ok(QType::MX),
x if x == QType::TXT as u16 => Ok(QType::TXT),
x if x == QType::RP as u16 => Ok(QType::RP),
x if x == QType::AAAA as u16 => Ok(QType::AAAA),
x if x == QType::SRV as u16 => Ok(QType::SRV),
_ => Err(v),
}
}
}
#[repr(u16)]
#[derive(Ord, PartialOrd, Eq, PartialEq, Debug, Copy, Clone)]
pub enum QClass {
Internet = 1,
@ -51,14 +54,14 @@ pub enum QClass {
Hesiod = 4,
}
impl TryFrom<u8> for QClass {
type Error = u8;
impl TryFrom<u16> for QClass {
type Error = u16;
fn try_from(v: u8) -> Result<Self, Self::Error> {
fn try_from(v: u16) -> Result<Self, Self::Error> {
match v {
x if x == QClass::Internet as u8 => Ok(QClass::Internet),
x if x == QClass::Chaos as u8 => Ok(QClass::Chaos),
x if x == QClass::Hesiod as u8 => Ok(QClass::Hesiod),
x if x == QClass::Internet as u16 => Ok(QClass::Internet),
x if x == QClass::Chaos as u16 => Ok(QClass::Chaos),
x if x == QClass::Hesiod as u16 => Ok(QClass::Hesiod),
_ => Err(v),
}
}
@ -85,8 +88,15 @@ impl DNSQuestion {
{
let mut ret = encode_domain_name(&self.qname);
ret.push(self.qtype as u8);
ret.push(self.qclass as u8);
let (qtype_1, qtype_2) = two_byte_split(self.qtype as u16);
ret.push(qtype_1);
ret.push(qtype_2);
let (qclass_1, qclass_2) = two_byte_split(self.qclass as u16);
ret.push(qclass_1);
ret.push(qclass_2);
ret
}
@ -107,8 +117,8 @@ pub fn questions_to_bytes(questions: &Vec<DNSQuestion>) -> Vec<u8>
#[derive(Ord, PartialOrd, Eq, PartialEq, Debug)]
pub enum QuestionParseError {
ShortLength(usize),
QTypeParse(u8),
QClassParse(u8)
QTypeParse(u16),
QClassParse(u16)
}
pub fn questions_from_bytes(bytes: Vec<u8>, total_questions: u16) -> Result<(i32, Vec<DNSQuestion>), QuestionParseError>
@ -123,7 +133,8 @@ pub fn questions_from_bytes(bytes: Vec<u8>, total_questions: u16) -> Result<(i32
let mut current_length: Option<u8> = None;
let mut remaining_length: u8 = 0;
let mut current_qtype: Option<u8> = None;
let mut current_qtype: (Option<u8>, Option<u8>) = (None, None);
let mut current_qclass: (Option<u8>, Option<u8>) = (None, None);
let mut trailers_reached = false;
let mut byte_counter = 0;
@ -137,7 +148,7 @@ pub fn questions_from_bytes(bytes: Vec<u8>, total_questions: u16) -> Result<(i32
current_query.clear();
}
Some(_) => {
if byte == 0 {
if byte == 0 && !trailers_reached {
trailers_reached = true;
continue
}
@ -148,12 +159,19 @@ pub fn questions_from_bytes(bytes: Vec<u8>, total_questions: u16) -> Result<(i32
remaining_length = byte;
}
else if trailers_reached { // trailer fields
match current_qtype {
None => {
current_qtype = Some(byte);
match (current_qtype, current_qclass) {
((None, _), (_, _)) => {
current_qtype.0 = Some(byte);
},
((_, None), (_, _)) => {
current_qtype.1 = Some(byte);
},
((_, _), (None, _)) => {
current_qclass.0 = Some(byte);
}
Some(qtype_b) => {
match (qtype_b.try_into(), byte.try_into()) {
((Some(qtype_1), Some(qtype_2)), (Some(qclass_1), None)) => {
match (two_byte_extraction(&[qtype_1, qtype_2], 0).try_into(),
two_byte_extraction(&[qclass_1, byte], 0).try_into()) {
(Ok(qtype), Ok(qclass)) => {
questions.push(DNSQuestion {
qname: decode(String::from_utf8(current_query.clone()).unwrap().as_str()).unwrap().to_string(),
@ -168,7 +186,8 @@ pub fn questions_from_bytes(bytes: Vec<u8>, total_questions: u16) -> Result<(i32
current_length = None;
remaining_length = byte;
current_query.clear();
current_qtype = None;
current_qtype = (None, None);
current_qclass = (None, None);
trailers_reached = false;
}
(Err(qtype_e), _) => {
@ -179,6 +198,7 @@ pub fn questions_from_bytes(bytes: Vec<u8>, total_questions: u16) -> Result<(i32
}
}
}
_ => {}
}
}
else {

View File

@ -1,11 +1,11 @@
use std::net::SocketAddr;
use crate::message::header::DNSHeader;
use crate::message::question::{DNSQuestion, questions_to_bytes};
use crate::message::{DNSQuestion, DNSHeader, questions_to_bytes, Direction, Opcode, ResponseCode, QType, QClass};
#[derive(Ord, PartialOrd, Eq, PartialEq, Debug, Clone)]
pub struct DNSRequest {
pub header: DNSHeader,
pub questions: Vec<DNSQuestion>,
pub additional_records: Vec<DNSQuestion>,
pub peer: SocketAddr
}
@ -20,4 +20,38 @@ impl DNSRequest {
return header_bytes
}
pub fn from_hostname(peer: SocketAddr, id: u16, hostname: String) -> DNSRequest
{
DNSRequest {
header: DNSHeader::new_request(id, None),
questions: vec![
DNSQuestion {
qname: hostname,
qtype: QType::A,
qclass: QClass::Internet
}
],
additional_records: vec![],
peer
}
}
pub fn from_hostnames(peer: SocketAddr, id: u16, hostnames: Vec<String>) -> DNSRequest
{
DNSRequest {
header: DNSHeader::new_request(id, Some(hostnames.len() as u16)),
questions: hostnames
.into_iter()
.map(|n|
DNSQuestion {
qname: n,
qclass: QClass::Internet,
qtype: QType::A
})
.collect(),
additional_records: vec![],
peer
}
}
}

View File

@ -1,7 +1,5 @@
use std::net::SocketAddr;
use crate::message::answer::{answers_to_bytes, DNSAnswer};
use crate::message::header::DNSHeader;
use crate::message::question::{DNSQuestion, questions_to_bytes};
use std::net::{Ipv4Addr, SocketAddr};
use crate::message::{Direction, DNSHeader, DNSRequest, ResponseCode, answers_to_bytes, ARdata, DNSAnswer, DNSQuestion, questions_to_bytes};
#[derive(Debug)]
pub struct DNSResponse {
@ -24,4 +22,35 @@ impl DNSResponse {
return header_bytes
}
pub fn a_from_request(request: &DNSRequest, ip: impl Fn(&DNSQuestion) -> Ipv4Addr) -> DNSResponse
{
let mut response = DNSResponse{
header: request.header.clone(),
questions: request.questions.clone(),
answers: vec![],
peer: request.peer
};
response.answers = request.questions
.iter()
.map(|x|
DNSAnswer::from_query(x,
12,
Box::from(ARdata::from(ip(x))),
None))
.collect();
response.header.direction = Direction::Response;
response.header.response = ResponseCode::NoError;
response.header.answer_record_count = response.answers.len() as u16;
response.header.authority_record_count = 0;
response.header.additional_record_count = 0;
if response.header.recursion_desired {
response.header.recursion_available = true;
}
response
}
}

View File

@ -1,6 +1,5 @@
pub mod socket;
// pub mod processor;
//
// pub mod processor::request_processor;
// pub mod processor::response_processor;
pub mod raw_request;
pub use raw_request::{NetworkMessage, NetworkMessagePtr};
pub use socket::DNSSocket;

View File

@ -4,8 +4,9 @@ use std::thread::{JoinHandle};
use log::{debug, error, info};
use std::sync::mpsc;
use std::sync::mpsc::{Receiver, Sender, TryRecvError};
use crate::message::header::HEADER_SIZE;
use crate::net::raw_request::{NetworkMessage, NetworkMessagePtr};
use crate::message::HEADER_SIZE;
use crate::net::{NetworkMessage, NetworkMessagePtr};
pub struct DNSSocket {
addresses: Vec<SocketAddr>,

View File

@ -1,13 +1,11 @@
use std::net::{IpAddr, Ipv4Addr};
use std::net::Ipv4Addr;
use std::sync::mpsc;
use std::sync::mpsc::{Receiver, Sender};
use std::thread;
use log::{error, info};
use crate::message::answer::{DNSAnswer, IpRData, RawRData};
use crate::message::header::{Direction, ResponseCode};
use crate::message::question::QuestionParseError;
use crate::message::response::DNSResponse;
use crate::net::raw_request::{NetworkMessage, NetworkMessagePtr};
use crate::message::{QuestionParseError, DNSResponse};
use crate::net::{NetworkMessage, NetworkMessagePtr};
use crate::request_parser::{HeaderParseError, parse_request, RequestParseError};
pub struct RequestProcesor {
@ -36,24 +34,7 @@ impl RequestProcesor {
Ok(r) => {
info!("received dns message: {:?}", r);
let mut response = DNSResponse{
header: r.header.clone(),
questions: r.questions.clone(),
answers: vec![],
peer: r.peer
};
// response.answers = r.questions.iter().map(|x| DNSAnswer::from_query(x, Box::from(IpRData::from(Ipv4Addr::from([127, 0, 0, 1]))), None)).collect();
response.header.direction = Direction::Response;
response.header.response = ResponseCode::NameError;
response.header.answer_record_count = 0;
response.header.authority_record_count = 0;
response.header.additional_record_count = 0;
if response.header.recursion_desired {
response.header.recursion_available = true;
}
let mut response = DNSResponse::a_from_request(&r, |q| Ipv4Addr::from([127, 0, 0, 1]));
sending_channel.send(Box::from(
NetworkMessage {

View File

@ -3,6 +3,7 @@ use std::sync::mpsc::{Receiver, Sender};
use std::thread;
use log::info;
use std::str;
use crate::message::DNSResponse;
use crate::net::raw_request::NetworkMessagePtr;
pub struct ResponseProcesor {
@ -25,9 +26,7 @@ impl ResponseProcesor {
for mut m in rx
{
info!("processing: {}", str::from_utf8(&(*(*m).buffer)).unwrap());
// (*(*m).buffer).reverse();
info!("processing response");
// match sending_channel.send(m) {
// Ok(_) => {}

View File

@ -1,8 +1,6 @@
use crate::byte;
use crate::message::header::{Direction, DNSHeader, Opcode, ResponseCode};
use crate::message::question::{QuestionParseError, questions_from_bytes};
use crate::message::request::DNSRequest;
use crate::net::raw_request::NetworkMessage;
use crate::message::{DNSRequest, Direction, DNSHeader, Opcode, ResponseCode, QuestionParseError, questions_from_bytes};
use crate::net::NetworkMessage;
use crate::request_parser::RequestParseError::{HeaderParse, QuesionsParse};
pub const ID_START: usize = 0;
@ -90,15 +88,28 @@ pub fn parse_request(msg: NetworkMessage) -> Result<DNSRequest, RequestParseErro
Ok(header) => {
let mut trimmed = msg.buffer.to_vec();
trimmed.drain(0 .. 12);
let buffer_size = trimmed.len();
match questions_from_bytes(trimmed, header.question_count)
{
Ok((bytes_read, questions)) => {
if buffer_size > bytes_read as usize {
Ok(DNSRequest {
header,
questions,
peer: msg.peer
peer: msg.peer,
additional_records: vec![]
})
}
else {
Ok(DNSRequest {
header,
questions,
peer: msg.peer,
additional_records: vec![]
})
}
}
Err(e) => Err(QuesionsParse(e))
}
},