Update examples with modernized code

This commit is contained in:
Emil Hernvall
2020-06-18 01:47:09 +02:00
parent 31369696d9
commit f815075ae4
10 changed files with 708 additions and 627 deletions

View File

@@ -323,43 +323,43 @@ we'll use a `struct` called `BytePacketBuffer`.
```rust
pub struct BytePacketBuffer {
pub buf: [u8; 512],
pub pos: usize
pub pos: usize,
}
impl BytePacketBuffer {
// This gives us a fresh buffer for holding the packet contents, and a field for
// keeping track of where we are.
/// This gives us a fresh buffer for holding the packet contents, and a
/// field for keeping track of where we are.
pub fn new() -> BytePacketBuffer {
BytePacketBuffer {
buf: [0; 512],
pos: 0
pos: 0,
}
}
// When handling the reading of domain names, we'll need a way of
// reading and manipulating our buffer position.
/// Current position within buffer
fn pos(&self) -> usize {
self.pos
}
/// Step the buffer position forward a specific number of steps
fn step(&mut self, steps: usize) -> Result<()> {
self.pos += steps;
Ok(())
}
/// Change the buffer position
fn seek(&mut self, pos: usize) -> Result<()> {
self.pos = pos;
Ok(())
}
// A method for reading a single byte, and moving one step forward
/// Read a single byte and move the position one step forward
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;
@@ -367,49 +367,46 @@ impl BytePacketBuffer {
Ok(res)
}
// Methods for fetching data at a specified position, without modifying
// the internal position
/// Get a single byte, without changing the buffer position
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])
}
/// Get a range of bytes
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])
}
// Methods for reading a u16 and u32 from the buffer, while stepping
// forward 2 or 4 bytes
fn read_u16(&mut self) -> Result<u16>
{
let res = ((try!(self.read()) as u16) << 8) |
(try!(self.read()) as u16);
/// Read two bytes, stepping two steps forward
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);
/// Read four bytes, stepping four steps forward
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)
}
// 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.
fn read_qname(&mut self, outstr: &mut String) -> Result<()>
{
/// 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.
fn read_qname(&mut self, outstr: &mut String) -> Result<()> {
// 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
@@ -419,43 +416,54 @@ impl BytePacketBuffer {
// track whether or not we've jumped
let mut jumped = false;
let max_jumps = 5;
let mut jumps_performed = 0;
// 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.
// 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 = "";
loop {
// 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());
}
// At this point, we're always at the beginning of a label. Recall
// that labels start with a length byte.
let len = try!(self.get(pos));
let len = self.get(pos)?;
// If len has the two most significant bit are set, it represents a jump to
// some other offset in the packet:
// If len has the two most significant bit are set, it represents a
// jump to some other offset in the packet:
if (len & 0xC0) == 0xC0 {
// Update the buffer position to a point past the current
// label. We don't need to touch it any further.
if !jumped {
try!(self.seek(pos+2));
self.seek(pos + 2)?;
}
// Read another byte, calculate offset and perform the jump by
// updating our local position variable
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;
// Indicate that a jump was performed.
jumped = true;
}
jumps_performed += 1;
continue;
}
// 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.
// Domain names are terminated by an empty label of length 0,
// so if the length is zero we're done.
if len == 0 {
break;
}
@@ -463,9 +471,9 @@ impl BytePacketBuffer {
// Append the delimiter to our output buffer first.
outstr.push_str(delim);
// Extract the actual ASCII bytes for this label and append them to the output buffer.
let str_buffer = try!(self.get_range(pos, len as usize));
// 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());
delim = ".";
@@ -475,16 +483,13 @@ impl BytePacketBuffer {
}
}
// If a jump has been performed, we've already modified the buffer position state and
// shouldn't do so again.
if !jumped {
try!(self.seek(pos));
self.seek(pos)?;
}
Ok(())
} // End of read_qname
} // End of BytePacketBuffer
}
}
```
### ResultCode
@@ -492,14 +497,14 @@ impl BytePacketBuffer {
Before we move on to the header, we'll add an enum for the values of `rescode` field:
```rust
#[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 {
@@ -510,7 +515,7 @@ impl ResultCode {
3 => ResultCode::NXDOMAIN,
4 => ResultCode::NOTIMP,
5 => ResultCode::REFUSED,
0 | _ => ResultCode::NOERROR
0 | _ => ResultCode::NOERROR,
}
}
}
@@ -521,26 +526,26 @@ impl ResultCode {
Now we can get to work on the header. We'll represent it like this:
```rust
#[derive(Clone,Debug)]
#[derive(Clone, Debug)]
pub struct DnsHeader {
pub id: u16, // 16 bits
pub recursion_desired: bool, // 1 bit
pub truncated_message: bool, // 1 bit
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 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 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 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
}
```
@@ -549,30 +554,32 @@ The implementation involves a lot of bit twiddling:
```rust
impl DnsHeader {
pub fn new() -> DnsHeader {
DnsHeader { id: 0,
DnsHeader {
id: 0,
recursion_desired: false,
truncated_message: false,
authoritative_answer: false,
opcode: 0,
response: false,
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,
rescode: ResultCode::NOERROR,
checking_disabled: false,
authed_data: false,
z: false,
recursion_available: false,
questions: 0,
answers: 0,
authoritative_entries: 0,
resource_entries: 0 }
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());
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;
@@ -587,10 +594,10 @@ 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(())
@@ -604,7 +611,7 @@ Before moving on to the question part of the packet, we'll need a way to
represent the record type being queried:
```rust
#[derive(PartialEq,Eq,Debug,Clone,Hash,Copy)]
#[derive(PartialEq, Eq, Debug, Clone, Hash, Copy)]
pub enum QueryType {
UNKNOWN(u16),
A, // 1
@@ -621,7 +628,7 @@ impl QueryType {
pub fn from_num(num: u16) -> QueryType {
match num {
1 => QueryType::A,
_ => QueryType::UNKNOWN(num)
_ => QueryType::UNKNOWN(num),
}
}
}
@@ -633,24 +640,24 @@ The enum allows us to easily add more record types later on. Now for the
question entries:
```rust
#[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(())
}
@@ -666,19 +673,19 @@ We'll obviously need a way of representing the actual dns records as well, and
again we'll use an enum for easy expansion:
```rust
#[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
}
```
@@ -690,39 +697,40 @@ this:
```rust
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()); // class, which we ignore
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,
((raw_addr >> 16) & 0xFF) as u8,
((raw_addr >> 8) & 0xFF) as u8,
((raw_addr >> 0) & 0xFF) as u8);
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,
);
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,
})
}
}
@@ -741,7 +749,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 {
@@ -751,31 +759,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);
}
@@ -789,26 +796,28 @@ impl DnsPacket {
Let's use the `response_packet.txt` we generated earlier to try it out!
```rust
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();
println!("{:?}", packet.header);
let packet = DnsPacket::from_buffer(&mut buffer)?;
println!("{:#?}", packet.header);
for q in packet.questions {
println!("{:?}", q);
println!("{:#?}", q);
}
for rec in packet.answers {
println!("{:?}", rec);
println!("{:#?}", rec);
}
for rec in packet.authorities {
println!("{:?}", rec);
println!("{:#?}", rec);
}
for rec in packet.resources {
println!("{:?}", rec);
println!("{:#?}", rec);
}
Ok(())
}
```