tcp_headers.rs 7.2 KB

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