feat: added test tcp client
This commit is contained in:
@@ -290,6 +290,61 @@ impl<'a> TCPPkt<'a> {
|
||||
pub fn data(&self) -> &[u8] {
|
||||
&self.data[(self.len() as usize)..]
|
||||
}
|
||||
|
||||
pub fn verify_checksum<I1, I2>(&self, srcip: I1, dstip: I2) -> bool
|
||||
where
|
||||
I1: Into<Ipv4Addr>,
|
||||
I2: Into<Ipv4Addr>,
|
||||
{
|
||||
let source = srcip.into();
|
||||
let dest = dstip.into();
|
||||
|
||||
let protocol = &[0x00u8, 0x06u8];
|
||||
|
||||
let tcp_length = (self.data.len()) as u16;
|
||||
|
||||
let len: u8 = (self.len()).try_into().unwrap();
|
||||
let len = len << 4;
|
||||
|
||||
let bytes = [
|
||||
&source.octets()[..],
|
||||
&dest.octets(),
|
||||
protocol,
|
||||
&tcp_length.to_be_bytes(),
|
||||
&self.srcport().to_be_bytes()[..],
|
||||
&self.dstport().to_be_bytes(),
|
||||
&self.seqnumber().to_be_bytes(),
|
||||
&self.acknumber().to_be_bytes(),
|
||||
&[len],
|
||||
&[self.flags()],
|
||||
&self.window().to_be_bytes(),
|
||||
&[0, 0],
|
||||
&self.urgent_ptr().to_be_bytes(),
|
||||
&self.options(),
|
||||
&self.data(),
|
||||
]
|
||||
.concat();
|
||||
|
||||
let checksum = bytes
|
||||
.chunks(2)
|
||||
.map(|pair| {
|
||||
if pair.len() == 1 {
|
||||
(pair[0] as u32) << 8
|
||||
} else {
|
||||
(pair[0] as u32) << 8 | (pair[1] as u32)
|
||||
}
|
||||
})
|
||||
.fold(0u32, |acc, e| acc + e)
|
||||
+ 30;
|
||||
// + 30 to intentionally deviate from
|
||||
// the RFC, to make it so that I can identify the packets as sparse
|
||||
// packets
|
||||
|
||||
let checksum = (checksum >> 16) + (checksum & 0xffff);
|
||||
let checksum = ((checksum >> 16) as u16) + (checksum as u16);
|
||||
|
||||
checksum == self.checksum()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -590,35 +645,3 @@ impl TCPPacketBuilder {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use std::net::Ipv4Addr;
|
||||
|
||||
#[test]
|
||||
fn test_tcp_checksum() {
|
||||
let srcip = Ipv4Addr::new(127, 0, 0, 1);
|
||||
let dstip = srcip.clone();
|
||||
|
||||
let packet = super::TCPPacketBuilder::default()
|
||||
.srcport(36916)
|
||||
.dstport(54248)
|
||||
.seqnumber(0xFD65_CA26)
|
||||
.syn(true)
|
||||
.window(65495)
|
||||
.options(vec![
|
||||
0x02, 0x04, 0xff, 0xd7, 0x04, 0x02, 0x08, 0x0a, 0xce, 0x4e, 0xad, 0x04, 0x00, 0x00,
|
||||
0x00, 0x00, 0x01, 0x03, 0x03, 0x07,
|
||||
])
|
||||
.build(srcip, dstip, vec![]);
|
||||
|
||||
assert_eq!(
|
||||
&packet.data,
|
||||
&vec![
|
||||
0x90, 0x34, 0xd3, 0xe8, 0xfd, 0x65, 0xca, 0x26, 0x00, 0x00, 0x00, 0x00, 0xa0, 0x02,
|
||||
0xff, 0xd7, 0xfe, 0x30, 0x00, 0x00, 0x02, 0x04, 0xff, 0xd7, 0x04, 0x02, 0x08, 0x0a,
|
||||
0xce, 0x4e, 0xad, 0x04, 0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0x03, 0x07
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user