tcp_headers.rs 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. #![no_main]
  2. #[macro_use] extern crate libfuzzer_sys;
  3. extern crate smoltcp;
  4. use std as core;
  5. extern crate getopts;
  6. use core::cmp;
  7. use smoltcp::phy::{Loopback, Medium};
  8. use smoltcp::wire::{EthernetAddress, EthernetFrame, EthernetProtocol};
  9. use smoltcp::wire::{IpAddress, IpCidr, Ipv4Packet, Ipv6Packet, TcpPacket};
  10. use smoltcp::iface::{NeighborCache, InterfaceBuilder};
  11. use smoltcp::socket::{SocketSet, TcpSocket, TcpSocketBuffer};
  12. use smoltcp::time::{Duration, Instant};
  13. mod utils {
  14. include!("../utils.rs");
  15. }
  16. mod mock {
  17. use std::sync::Arc;
  18. use std::sync::atomic::{Ordering, AtomicUsize};
  19. use smoltcp::time::{Duration, Instant};
  20. // should be AtomicU64 but that's unstable
  21. #[derive(Debug, Clone)]
  22. #[cfg_attr(feature = "defmt", derive(defmt::Format))]
  23. pub struct Clock(Arc<AtomicUsize>);
  24. impl Clock {
  25. pub fn new() -> Clock {
  26. Clock(Arc::new(AtomicUsize::new(0)))
  27. }
  28. pub fn advance(&self, duration: Duration) {
  29. self.0.fetch_add(duration.total_millis() as usize, Ordering::SeqCst);
  30. }
  31. pub fn elapsed(&self) -> Instant {
  32. Instant::from_millis(self.0.load(Ordering::SeqCst) as i64)
  33. }
  34. }
  35. }
  36. struct TcpHeaderFuzzer([u8; 56], usize);
  37. impl TcpHeaderFuzzer {
  38. // The fuzzer won't fuzz any packets with the SYN flag set in order to make sure the connection
  39. // is established before the fuzzed headers arrive.
  40. //
  41. // It will also not fuzz the source and dest port so it reaches the open socket.
  42. //
  43. // Otherwise, it replaces the entire rest of the TCP header with the fuzzer's output.
  44. pub fn new(data: &[u8]) -> TcpHeaderFuzzer {
  45. let copy_len = cmp::min(data.len(), 56 /* max TCP header length without port numbers*/);
  46. let mut fuzzer = TcpHeaderFuzzer([0; 56], copy_len);
  47. fuzzer.0[..copy_len].copy_from_slice(&data[..copy_len]);
  48. fuzzer
  49. }
  50. }
  51. impl smoltcp::phy::Fuzzer for TcpHeaderFuzzer {
  52. fn fuzz_packet(&self, frame_data: &mut [u8]) {
  53. if self.1 == 0 {
  54. return;
  55. }
  56. let tcp_packet_offset = {
  57. let eth_frame = EthernetFrame::new_unchecked(&frame_data);
  58. EthernetFrame::<&mut [u8]>::header_len() + match eth_frame.ethertype() {
  59. EthernetProtocol::Ipv4 =>
  60. Ipv4Packet::new_unchecked(eth_frame.payload()).header_len() as usize,
  61. EthernetProtocol::Ipv6 =>
  62. Ipv6Packet::new_unchecked(eth_frame.payload()).header_len() as usize,
  63. _ => return
  64. }
  65. };
  66. let tcp_is_syn = {
  67. let tcp_packet = TcpPacket::new_checked(&frame_data[tcp_packet_offset..]).unwrap();
  68. tcp_packet.syn()
  69. };
  70. if tcp_is_syn {
  71. return;
  72. }
  73. if !frame_data.ends_with(b"abcdef") {
  74. return;
  75. }
  76. let tcp_header_len = {
  77. let tcp_packet = &frame_data[tcp_packet_offset..];
  78. (tcp_packet[12] as usize >> 4) * 4
  79. };
  80. let tcp_packet = &mut frame_data[tcp_packet_offset+4..];
  81. let replacement_data = &self.0[..self.1];
  82. let copy_len = cmp::min(replacement_data.len(), tcp_header_len);
  83. assert!(copy_len < tcp_packet.len());
  84. tcp_packet[..copy_len].copy_from_slice(&replacement_data[..copy_len]);
  85. }
  86. }
  87. struct EmptyFuzzer();
  88. impl smoltcp::phy::Fuzzer for EmptyFuzzer {
  89. fn fuzz_packet(&self, _: &mut [u8]) {}
  90. }
  91. fuzz_target!(|data: &[u8]| {
  92. let clock = mock::Clock::new();
  93. let device = {
  94. let (mut opts, mut free) = utils::create_options();
  95. utils::add_middleware_options(&mut opts, &mut free);
  96. let mut matches = utils::parse_options(&opts, free);
  97. let device = utils::parse_middleware_options(&mut matches, Loopback::new(Medium::Ethernet),
  98. /*loopback=*/true);
  99. smoltcp::phy::FuzzInjector::new(device,
  100. EmptyFuzzer(),
  101. TcpHeaderFuzzer::new(data))
  102. };
  103. let mut neighbor_cache_entries = [None; 8];
  104. let neighbor_cache = NeighborCache::new(&mut neighbor_cache_entries[..]);
  105. let ip_addrs = [IpCidr::new(IpAddress::v4(127, 0, 0, 1), 8)];
  106. let mut iface = InterfaceBuilder::new(device)
  107. .ethernet_addr(EthernetAddress::default())
  108. .neighbor_cache(neighbor_cache)
  109. .ip_addrs(ip_addrs)
  110. .finalize();
  111. let server_socket = {
  112. // It is not strictly necessary to use a `static mut` and unsafe code here, but
  113. // on embedded systems that smoltcp targets it is far better to allocate the data
  114. // statically to verify that it fits into RAM rather than get undefined behavior
  115. // when stack overflows.
  116. static mut TCP_SERVER_RX_DATA: [u8; 1024] = [0; 1024];
  117. static mut TCP_SERVER_TX_DATA: [u8; 1024] = [0; 1024];
  118. let tcp_rx_buffer = TcpSocketBuffer::new(unsafe { &mut TCP_SERVER_RX_DATA[..] });
  119. let tcp_tx_buffer = TcpSocketBuffer::new(unsafe { &mut TCP_SERVER_TX_DATA[..] });
  120. TcpSocket::new(tcp_rx_buffer, tcp_tx_buffer)
  121. };
  122. let client_socket = {
  123. static mut TCP_CLIENT_RX_DATA: [u8; 1024] = [0; 1024];
  124. static mut TCP_CLIENT_TX_DATA: [u8; 1024] = [0; 1024];
  125. let tcp_rx_buffer = TcpSocketBuffer::new(unsafe { &mut TCP_CLIENT_RX_DATA[..] });
  126. let tcp_tx_buffer = TcpSocketBuffer::new(unsafe { &mut TCP_CLIENT_TX_DATA[..] });
  127. TcpSocket::new(tcp_rx_buffer, tcp_tx_buffer)
  128. };
  129. let mut socket_set_entries: [_; 2] = Default::default();
  130. let mut socket_set = SocketSet::new(&mut socket_set_entries[..]);
  131. let server_handle = socket_set.add(server_socket);
  132. let client_handle = socket_set.add(client_socket);
  133. let mut did_listen = false;
  134. let mut did_connect = false;
  135. let mut done = false;
  136. while !done && clock.elapsed() < Instant::from_millis(4_000) {
  137. let _ = iface.poll(&mut socket_set, clock.elapsed());
  138. {
  139. let mut socket = socket_set.get::<TcpSocket>(server_handle);
  140. if !socket.is_active() && !socket.is_listening() {
  141. if !did_listen {
  142. socket.listen(1234).unwrap();
  143. did_listen = true;
  144. }
  145. }
  146. if socket.can_recv() {
  147. socket.close();
  148. done = true;
  149. }
  150. }
  151. {
  152. let mut socket = socket_set.get::<TcpSocket>(client_handle);
  153. if !socket.is_open() {
  154. if !did_connect {
  155. socket.connect((IpAddress::v4(127, 0, 0, 1), 1234),
  156. (IpAddress::Unspecified, 65000)).unwrap();
  157. did_connect = true;
  158. }
  159. }
  160. if socket.can_send() {
  161. socket.send_slice(b"0123456789abcdef0123456789abcdef0123456789abcdef").unwrap();
  162. socket.close();
  163. }
  164. }
  165. match iface.poll_delay(&socket_set, clock.elapsed()) {
  166. Some(Duration { millis: 0 }) => {},
  167. Some(delay) => {
  168. clock.advance(delay)
  169. },
  170. None => clock.advance(Duration::from_millis(1))
  171. }
  172. }
  173. });