DataReelDataReelC++ Transition Guide

Examples › Socket Examples

socket_fuzz_fuzz_proto

C++20 or laterC++ standard library onlyPortable C++ (tested on Linux)

Legacy: examples_socket/fuzz/fuzz_proto.cpp · Modern: examples_modern/socket/fuzz/fuzz_proto.cpp

Modern equivalent of the libFuzzer targets for the 6.x HTTP, URL, SMTP, POP3 and FTP readers, aimed at the modern parsers in common/proto_parse.h: every input must give a value or a refusal, never a crash or a read out of bounds. The input is a std::string_view over the fuzzer's bytes; the first byte picks the parser.

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

Legacy calls in this program

LegacyModern C++StandardNotes
gxString / UStringstd::string, std::string_viewC++98 / C++17string_view looks at text without copying it.
Find(), IFind(), FindLast()find(), a std::search with a case-folding predicate, rfind()C++98Watch out: rfind("") returns size(), where FindLast("") returns -1.
gxsHTTPClient, gxsSMTPClient, gxsPOP3Client, gxsIMAPClient, gxsFTPClient, gxsTelnetClientkeep them; std::string buffers; reply parsing with std::string_view and std::from_charsC++17

From the transition tables.

Side by side

DataReel 6.4 (legacy)

examples_socket/fuzz/fuzz_proto.cpp 152 lines
#include "gxdlcode.h"

#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <string>
#include <vector>
#include "gxshttp.h"
#include "gxshttpc.h"
#include "gxsurl.h"
#include "gxsmtp.h"
#include "gxspop3.h"
#include "gxsftp.h"
#include "gxsutils.h"

#if defined (FUZZ_RECV)
#include <sys/socket.h>
#include <unistd.h>
#endif

#if defined (FUZZ_HTTPHDR)
static void fuzz_httphdr(const uint8_t *data, size_t size)
{
  gxsHTTPClient client;
  gxsURLInfo u;
  u.host = "fuzz.example";
  gxString header;
  if(size > 0) header.Cat((const char *)data, (unsigned)size);
  gxsHTTPHeader hdr;
  client.ParseHTTPHeader(u, header, hdr);
  gxsHTTPHeader copy(hdr);
  (void)copy;
}
#endif

#if defined (FUZZ_URL)
static void fuzz_url(const uint8_t *data, size_t size)
{
  std::string s((const char *)data, size);
  gxString g;
  if(size > 0) g.SetString(s.data(), (unsigned)size);
  gxsURL url;
  gxsURLInfo u;
  url.ParseURL(s.c_str(), u);
  url.ParseURL(g, u, 1);
  url.GetProtocolType(g);
  url.GetProtocolString(size > 0 ? (int)(signed char)data[0] : 0);
  gxString d, f;
  url.HasFile(g, d, f);
  gxString q(g);
  url.FilterQueryCharacters(q);
  gxString out;
  gxsURL::DecodeStrict(g, out, size & 1);
  gxsURL::HasControlChars(g);
  url.IsDynamicPage(g);
}
#endif

#if defined (FUZZ_REPLY)
static void fuzz_reply(const uint8_t *data, size_t size)
{
  const char *p = (const char *)data;
  int len = (int)size;
  int code = 0, used = 0;
  gxsSMTPClient::ParseReply(p, len, &code, &used);
  if(used < 0 || used > len) __builtin_trap();
  gxsFTPClient::ParseReply(p, len, &code, &used);
  if(used < 0 || used > len) __builtin_trap();
  gxsPOP3Client::CheckReply(p, len, "+OK");
  gxsPOP3Client::CheckReply(p, len, "\r\n.\r\n");

  std::string c(p, size); // As a C string
  std::string cs(c.c_str());
  gxString a;
  gxsSMTPClient::NormalizeAddress(cs.c_str(), a, size & 1);
  if(a.Find("\r") != -1 || a.Find("\n") != -1 || a.Find(" ") != -1) {
    __builtin_trap(); // Must not get into a command
  }
  int port = gxsFTPClient::ParsePASVPort(cs.c_str());
  if(port == 0 || port > 65535) __builtin_trap();

  std::vector<char> entry(cs.begin(), cs.end());
  entry.push_back(0);
  size_t n = entry.size();
  std::vector<char> b1(n), b2(n), b3(n), b4(n);
  int sport = 0;
  ParseServiceFileEntry(&entry[0], &b1[0], &sport, &b2[0], &b3[0], &b4[0]);
}
#endif

#if defined (FUZZ_RECV)
template <class T>
static void recv_one(T &client, const uint8_t *data, size_t size,
		     int bufsize, const char *response)
{
  int sv[2];
  if(socketpair(AF_UNIX, SOCK_STREAM, 0, sv) != 0) return;
  if(size > 0 && write(sv[1], data, size) != (ssize_t)size) {
    close(sv[0]); close(sv[1]);
    return;
  }
  shutdown(sv[1], SHUT_WR);
  client.SetSocket(sv[0]);
  client.SetTimeOut(1, 0);
  std::vector<char> buf(bufsize + 16, 'G');
  client.RecvResponse(&buf[0], bufsize, response);
  for(int i = bufsize; i < bufsize + 16; i++) {
    if(buf[i] != 'G') __builtin_trap(); // Wrote past the buffer
  }
  if(memchr(&buf[0], 0, bufsize) == 0) __builtin_trap(); // No NUL
  client.ReleaseSocket();
  close(sv[0]);
  close(sv[1]);
}

static void fuzz_recv(const uint8_t *data, size_t size)
{
  if(size < 2 || size > 16384) return;
  int which = data[0] % 7;
  int bufsize = 2 + data[1];
  data += 2; size -= 2;
  switch(which) {
    case 0: { gxsSMTPClient c; recv_one(c, data, size, bufsize, "250"); break; }
    case 1: { gxsSMTPClient c; recv_one(c, data, size, bufsize, "3"); break; }
    case 2: { gxsPOP3Client c; recv_one(c, data, size, bufsize, "+OK"); break; }
    case 3: { gxsPOP3Client c; recv_one(c, data, size, bufsize, "\r\n.\r\n"); break; }
    case 4: { gxsFTPClient c; recv_one(c, data, size, bufsize, "220 "); break; }
    case 5: { gxsFTPClient c; recv_one(c, data, size, bufsize, "227"); break; }
    default: { gxsFTPClient c; recv_one(c, data, size, bufsize, "150"); break; }
  }
}
#endif

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
{
#if defined (FUZZ_HTTPHDR)
  fuzz_httphdr(data, size);
#elif defined (FUZZ_URL)
  fuzz_url(data, size);
#elif defined (FUZZ_REPLY)
  fuzz_reply(data, size);
#elif defined (FUZZ_RECV)
  fuzz_recv(data, size);
#else
#error Define FUZZ_HTTPHDR, FUZZ_URL, FUZZ_REPLY or FUZZ_RECV
#endif
  return 0;
}
// ----------------------------------------------------------- //
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //

Modern C++ (C++20)

examples_modern/socket/fuzz/fuzz_proto.cpp 59 lines
#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <random>
#include <string>
#include <string_view>

#include "../common/proto_parse.h"

using namespace proto_parse;

extern "C" int LLVMFuzzerTestOneInput(const std::uint8_t *data, std::size_t size)
{
  if(size == 0) return 0;
  std::string_view in(reinterpret_cast<const char *>(data) + 1, size - 1);
  switch(data[0] % 4) {
    case 0: {
      auto r = smtp_reply(in);
      if(r && r->length > in.size()) std::abort();   // Never past the input
      break;
    }
    case 1: {
      auto a = normalize_address(in);
      if(a && a->find_first_of("\r\n ") != std::string::npos) std::abort();
      break;
    }
    case 2: {
      auto p = pasv_port(in);
      if(p && (*p < 1 || *p > 65535)) std::abort();
      break;
    }
    default:
      (void)http_header(in, 4096);
  }
  return 0;
}

#if !defined(MODERN_LIBFUZZER)
int main(int argc, char **argv)
{
  int runs = argc > 1 ? std::atoi(argv[1]) : 50000;
  const std::string alphabet = "0123456789 -,()<>@:\r\nHTTP/1.0abcxyzOK";
  std::mt19937 gen(99);
  std::uniform_int_distribution<std::size_t> pick(0, alphabet.size() - 1), len(0, 80);
  std::uniform_int_distribution<int> which(0, 3);
  std::string in;
  for(int r = 0; r < runs; r++) {
    in.assign(1, char(which(gen)));
    for(std::size_t n = len(gen); n > 0; n--) in += alphabet[pick(gen)];
    LLVMFuzzerTestOneInput(reinterpret_cast<const std::uint8_t *>(in.data()), in.size());
  }
  std::cout << "fuzz_proto: " << runs << " random inputs, no failures\n";
  return 0;
}
#endif
// ----------------------------------------------------------- // 
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //
examples_modern/socket/common/proto_parse.h 124 lines
#ifndef MODERN_PROTO_PARSE_H
#define MODERN_PROTO_PARSE_H

#include <algorithm>
#include <array>
#include <cctype>
#include <charconv>
#include <map>
#include <optional>
#include <string>
#include <string_view>

namespace proto_parse {

struct Reply { int code; std::size_t length; };

inline std::optional<int> three_digit_code(std::string_view line)
{
  if(line.size() < 4 || !(line[3] == ' ' || line[3] == '-')) return std::nullopt;
  int code = 0;
  auto [p, ec] = std::from_chars(line.data(), line.data() + 3, code);
  if(ec != std::errc() || p != line.data() + 3 || code < 100 || code > 599) return std::nullopt;
  return code;
}

// Returns the reply when it is complete; nothing if it is not complete
// yet or not valid (check `valid` to tell them apart).
inline std::optional<Reply> smtp_reply(std::string_view buf, bool *valid = nullptr)
{
  if(valid) *valid = true;
  std::size_t pos = 0;
  while(true) {
    auto eol = buf.find("\r\n", pos);
    if(eol == std::string_view::npos) return std::nullopt;   // Incomplete
    auto code = three_digit_code(buf.substr(pos, eol - pos));
    if(!code) { if(valid) *valid = false; return std::nullopt; }
    if(buf[pos + 3] == ' ') return Reply{*code, eol + 2};
    pos = eol + 2;
  }
}

inline std::optional<std::string> normalize_address(std::string_view a)
{
  auto lt = a.find('<');
  if(lt != std::string_view::npos) {
    auto gt = a.find('>', lt);
    if(gt == std::string_view::npos) return std::nullopt;
    auto after = a.substr(gt + 1);
    if(after.find_first_not_of(' ') != std::string_view::npos) return std::nullopt;
    a = a.substr(lt + 1, gt - lt - 1);
  }
  else {
    auto b = a.find_first_not_of(' '), e = a.find_last_not_of(' ');
    if(b == std::string_view::npos) return std::nullopt;
    a = a.substr(b, e - b + 1);
  }
  if(a.empty() || a.find_first_of("<> \r\n\t") != std::string_view::npos ||
     a.find('@') == std::string_view::npos) return std::nullopt;
  return "<" + std::string(a) + ">";
}

inline std::optional<int> pasv_port(std::string_view reply)
{
  if(!three_digit_code(reply)) return std::nullopt;
  reply.remove_prefix(4);                       // Skip "227 "
  std::string_view nums;
  if(auto open = reply.find('('); open != std::string_view::npos) {
    auto close = reply.find(')', open);
    if(close == std::string_view::npos) return std::nullopt;
    nums = reply.substr(open + 1, close - open - 1);
  }
  else {
    auto first = reply.find_first_of("0123456789");
    if(first == std::string_view::npos) return std::nullopt;
    nums = reply.substr(first);
  }
  std::array<int, 6> v{};
  for(std::size_t i = 0; i < 6; i++) {
    auto [p, ec] = std::from_chars(nums.data(), nums.data() + nums.size(), v[i]);
    if(ec != std::errc() || v[i] < 0 || v[i] > 255) return std::nullopt;
    nums.remove_prefix(std::size_t(p - nums.data()));
    if(i < 5) { if(nums.empty() || nums[0] != ',') return std::nullopt; nums.remove_prefix(1); }
  }
  int port = v[4] * 256 + v[5];
  if(port == 0) return std::nullopt;
  return port;
}

struct HttpHeader { int status = 0; std::map<std::string, std::string> fields; };

inline std::optional<HttpHeader> http_header(std::string_view text, std::size_t max_size = 64 * 1024)
{
  auto end = text.find("\r\n\r\n");
  if(end == std::string_view::npos || end > max_size) return std::nullopt;
  text = text.substr(0, end + 2);
  auto eol = text.find("\r\n");
  std::string_view status = text.substr(0, eol);
  if(!status.starts_with("HTTP/") || status.size() < 12) return std::nullopt;
  HttpHeader h;
  auto sp = status.find(' ');
  auto [p, ec] = std::from_chars(status.data() + sp + 1, status.data() + status.size(), h.status);
  if(ec != std::errc() || h.status < 100 || h.status > 599) return std::nullopt;
  for(text.remove_prefix(eol + 2); !text.empty();) {
    eol = text.find("\r\n");
    std::string_view line = text.substr(0, eol);
    text.remove_prefix(eol + 2);
    auto colon = line.find(':');
    if(colon == std::string_view::npos || colon == 0) return std::nullopt;
    std::string name(line.substr(0, colon));
    std::ranges::transform(name, name.begin(), [](unsigned char c) { return char(std::tolower(c)); });
    std::string_view value = line.substr(colon + 1);
    value.remove_prefix(std::min(value.find_first_not_of(' '), value.size()));
    h.fields[name] = std::string(value);
  }
  return h;
}

} // namespace proto_parse

#endif // MODERN_PROTO_PARSE_H
// ----------------------------------------------------------- // 
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //

Build and run

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

Output of the modern program

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

fuzz_proto: 50000 random inputs, no failures