DataReelDataReelC++ Transition Guide

Examples › Socket Examples

socket_stream_fuzz_fuzz_stream

C++20 or laterC++ standard library onlyPOSIX (Linux, UNIX)

Legacy: examples_socket/stream_fuzz/fuzz_stream.cpp · Modern: examples_modern/socket/stream_fuzz/fuzz_stream.cpp

Modern equivalent of the libFuzzer target for the gxStream peer data: the fuzz input is what a peer sends over a socket pair (closed after the input), and the reader in common/block_frame.h must return good blocks or nothing, never crash, hang or allocate more than its maximum. The input arrives as a std::span; the writer runs in a std::jthread so inputs larger than the socket buffer cannot deadlock.

Build as a libFuzzer target (clang): clang++ -std=c++20 -fsanitize=fuzzer,address,undefined \ -DMODERN_LIBFUZZER fuzz_stream.cpp -o fuzz_stream Without -DMODERN_LIBFUZZER a main() feeds it random and mutated inputs from std::mt19937.

Legacy calls in this program

LegacyModern C++StandardNotes
new / deleteautomatic objects, containers, std::unique_ptr / std::make_uniqueC++11 / C++14Ownership is in the type, and release() shows a hand-over.
gxStream, gxDatagram blockskeep gxStream for mutual TLS; length-checked blocks with std::span, std::endian, std::optionalC++20

From the transition tables.

Side by side

DataReel 6.4 (legacy)

examples_socket/stream_fuzz/fuzz_stream.cpp 102 lines
#include "gxdlcode.h"

#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <sys/socket.h>
#include "gxstream.h"

static const gxUINT32 fuzz_max_block = 1 << 20;

static void fuzz_server(gxStream &st, gxsSocket_t s)
{
  st.SetRemoteSocket(s);
  for(int i = 0; i < 16; i++) {
    gxBlockHeader gx;
    if(st.ReadClientHeader(gx) != 0) break;
    __ULWORD__ block_status = gx.block_status;
    __SBYTE__ status = (__SBYTE__)((block_status & 0xFF00)>>8);
    if(status == gxSendBlock || status == gxAddRemoteBlock ||
       status == gxChangeRemoteBlock || status == gxRequestBlock ||
       status == gxDeleteRemoteBlock) {
      if(i & 1) {
	char buf[512];
	if(st.ReadRemoteBlock(buf, (int)sizeof(buf), gx) != 0) break;
      }
      else {
	// The old form, used the way a careful caller must: allocate
	// what the header says only after checking it
	if((__ULWORD__)gx.block_length > (__ULWORD__)st.MaxBlockSize()) break;
	char *buf = new char[(__ULWORD__)gx.block_length + 1];
	int rv = st.ReadRemoteBlock(buf, gx);
	delete[] buf;
	if(rv != 0) break;
      }
    }
    else if(status == gxAcknowledgeBlock) {
      FAU_t code = 0;
      (void)code;
    }
    else {
      break;
    }
  }
  st.ReleaseRemoteSocket();
}

static void fuzz_client(gxStream &st, gxsSocket_t s)
{
  gxBlockHeader req, got;
  st.SetBlockStatus(req, gxRequestBlock);
  req.block_length = 4;
  void *p = st.RequestBlock(s, "key1", req, got, 1, 0);
  if(p) delete[] (char *)p;
  FAU_t code = 0;
  st.ReadResultBlock64(s, code, 1, 0);
  int icode = 0;
  st.ReadResultBlock(s, icode, 1, 0);
  st.ReadAckBlock(s, 1, 0);
}

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
{
  static int init = 0;
  if(!init) {
    signal(SIGPIPE, SIG_IGN);
    init = 1;
  }
  if(size < 1 || size > 16384) return 0;
  int sv[2];
  if(socketpair(AF_UNIX, SOCK_STREAM, 0, sv) != 0) return 0;
  int bufsize = 256 * 1024;
  setsockopt(sv[1], SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof(bufsize));
  setsockopt(sv[0], SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof(bufsize));
  size_t left = size - 1;
  const uint8_t *p = data + 1;
  while(left > 0) {
    ssize_t n = write(sv[1], p, left);
    if(n <= 0) break;
    p += n;
    left -= (size_t)n;
  }
  shutdown(sv[1], SHUT_WR); // The peer has said everything

  gxStream st;
  st.SetMaxBlockSize(fuzz_max_block);
  st.SetTimeOut(1, 0);
  if(data[0] & 1) {
    fuzz_client(st, sv[0]);
  }
  else {
    fuzz_server(st, sv[0]);
  }
  close(sv[0]);
  close(sv[1]);
  return 0;
}
// ----------------------------------------------------------- //
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //

Modern C++ (C++20)

examples_modern/socket/stream_fuzz/fuzz_stream.cpp 56 lines
#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <random>
#include <span>
#include <sys/socket.h>
#include <thread>
#include <unistd.h>
#include <vector>

#include "../common/block_frame.h"

using namespace block_frame;

extern "C" int LLVMFuzzerTestOneInput(const std::uint8_t *data, std::size_t size)
{
  int fd[2];
  if(::socketpair(AF_UNIX, SOCK_STREAM, 0, fd) != 0) return 0;
  std::span<const std::byte> in(reinterpret_cast<const std::byte *>(data), size);
  std::jthread writer([fd, in] { write_all(fd[0], in); ::close(fd[0]); });
  std::size_t total = 0;
  while(auto block = read_block(fd[1], 64 * 1024)) {
    total += block->size();
    if(total > size) std::abort();             // Cannot read more than was sent
  }
  writer.join();
  ::close(fd[1]);
  return 0;
}

#if !defined(MODERN_LIBFUZZER)
int main(int argc, char **argv)
{
  int runs = argc > 1 ? std::atoi(argv[1]) : 5000;
  std::mt19937 gen(73);
  std::uniform_int_distribution<int> byte(0, 255), len(0, 64);
  for(int r = 0; r < runs; r++) {
    std::vector<std::uint8_t> in;
    // Half the inputs start with a good header and a random length
    if(r % 2 == 0) {
      std::uint32_t h[2] = {to_little(magic), to_little(std::uint32_t(gen()))};
      if(r % 4 == 0) h[1] = to_little(std::uint32_t(len(gen)));
      auto *p = reinterpret_cast<const std::uint8_t *>(h);
      in.assign(p, p + 8);
    }
    for(int n = len(gen); n > 0; n--) in.push_back(std::uint8_t(byte(gen)));
    LLVMFuzzerTestOneInput(in.data(), in.size());
  }
  std::cout << "fuzz_stream: " << runs << " peer inputs, no failures\n";
  return 0;
}
#endif
// ----------------------------------------------------------- // 
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //
examples_modern/socket/common/block_frame.h 72 lines
#ifndef MODERN_BLOCK_FRAME_H
#define MODERN_BLOCK_FRAME_H

#include <array>
#include <bit>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <optional>
#include <span>
#include <vector>
#include <sys/socket.h>

namespace block_frame {

constexpr std::uint32_t magic = 0x67784231;     // "gxB1"
constexpr std::size_t header_size = 8;

constexpr std::uint32_t to_little(std::uint32_t v)
{
  if constexpr(std::endian::native == std::endian::little) return v;
  else return ((v & 0xff) << 24) | ((v & 0xff00) << 8) | ((v >> 8) & 0xff00) | (v >> 24);
}

inline bool write_all(int fd, std::span<const std::byte> data)
{
  while(!data.empty()) {
    ssize_t n = ::send(fd, data.data(), data.size(), MSG_NOSIGNAL);
    if(n <= 0) return false;
    data = data.subspan(std::size_t(n));
  }
  return true;
}

inline bool read_all(int fd, std::span<std::byte> data)
{
  while(!data.empty()) {
    ssize_t n = ::recv(fd, data.data(), data.size(), 0);
    if(n <= 0) return false;                    // Closed or error
    data = data.subspan(std::size_t(n));
  }
  return true;
}

inline bool write_block(int fd, std::span<const std::byte> data)
{
  if(data.size() > 0xffffffffu) return false;
  std::array<std::uint32_t, 2> hdr = {to_little(magic), to_little(std::uint32_t(data.size()))};
  return write_all(fd, std::as_bytes(std::span(hdr))) && write_all(fd, data);
}

// One block, or nothing if the header is bad, the length is over
// max_len, or the peer closes early.
inline std::optional<std::vector<std::byte>> read_block(int fd, std::size_t max_len)
{
  std::array<std::uint32_t, 2> hdr{};
  if(!read_all(fd, std::as_writable_bytes(std::span(hdr)))) return std::nullopt;
  if(to_little(hdr[0]) != magic) return std::nullopt;
  std::size_t len = to_little(hdr[1]);
  if(len > max_len) return std::nullopt;        // Checked before allocating
  std::vector<std::byte> data(len);
  if(!read_all(fd, data)) return std::nullopt;
  return data;
}

} // namespace block_frame

#endif // MODERN_BLOCK_FRAME_H
// ----------------------------------------------------------- // 
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //

Build and run

cmake -S examples_modern -B build-modern -DCMAKE_CXX_STANDARD=20
cmake --build build-modern --target socket_stream_fuzz_fuzz_stream
./build-modern/socket_stream_fuzz_fuzz_stream
# or without CMake:
g++ -std=c++20 -pthread -o socket_stream_fuzz_fuzz_stream examples_modern/socket/stream_fuzz/fuzz_stream.cpp

Output of the modern program

From run_modern_tests.sh on RHEL 10, GCC 14, C++20.

fuzz_stream: 5000 peer inputs, no failures