tcp_headers.rs 7.1 KB

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