Capstone: Secure a Legacy Codebase
You inherit a legacy C++ codebase. The kind that breathes pre-modern C++: raw pointers everywhere, hand-rolled memory management, unsafe casts, error handling that mostly amounts to crossing fingers. Your job is to drag it into the present — modern safety primitives, undefined behaviour stamped out, sanitisers in CI.
The Legacy Code
Here's a slimmed-down networking library written in proud "C with classes" style:
// legacy_network.h - THE PROBLEMS#include <cstring>#include <cstdlib>#include <iostream>
class Buffer {public: char* data; int size; int capacity;
Buffer(int cap) { data = (char*)malloc(cap); // C-style allocation size = 0; capacity = cap; }
~Buffer() { free(data); }
// No copy/move defined - Rule of Three violation // Copying this object = double free
void append(const char* src, int len) { // No bounds checking! memcpy(data + size, src, len); size += len; }
char* get_string() { data[size] = '\0'; // Might overflow if size == capacity return data; }};
class Connection {public: int* socket_fd; Buffer* read_buf; Buffer* write_buf; char* hostname; bool connected;
Connection(const char* host, int port) { hostname = strdup(host); // C-style string socket_fd = new int; // Raw new *socket_fd = connect_to(host, port); read_buf = new Buffer(1024); // Raw new write_buf = new Buffer(1024); // Raw new connected = (*socket_fd >= 0); }
~Connection() { if (connected) close_socket(*socket_fd); delete socket_fd; // Raw delete delete read_buf; // Raw delete delete write_buf; // Raw delete free(hostname); // Must match strdup's malloc }
int read_data() { char temp[256]; int n = recv(*socket_fd, temp, 256, 0); if (n > 0) { read_buf->append(temp, n); // No overflow check } return n; }
// Returns internal buffer pointer - dangling after Connection destroyed char* get_response() { return read_buf->get_string(); }};
class ConnectionPool {public: Connection** connections; int count; int max_connections;
ConnectionPool(int max) { max_connections = max; count = 0; connections = new Connection*[max]; // Raw array of raw pointers memset(connections, 0, sizeof(Connection*) * max); }
~ConnectionPool() { for (int i = 0; i < count; i++) { delete connections[i]; } delete[] connections; }
void add(Connection* conn) { // No bounds check! connections[count++] = conn; }
Connection* get(int index) { // No bounds check! return connections[index]; }};Step 1: Identify All Issues
Don't touch a line until you've catalogued the wrongs. Write your own list first: go class by class and ask who owns each pointer, what happens on copy, and which lengths are checked. Then compare it with ours.
Our list
- Buffer — C-style malloc/free, no copy/move semantics so a copy double-frees, unbounded append, and an off-by-one in
get_stringwaiting to bite. - Connection — raw new/delete (even for a lone
int), a hand-managedstrdupcopy where astd::stringbelongs (thefreeis the right partner forstrdup, but nothing stops a copy ofConnectionfreeing it twice),get_responsehands out a pointer that dangles the moment the connection dies, no error handling worth the name. - ConnectionPool — raw array of raw pointers, zero bounds checking, ownership semantics nobody can articulate out loud.
Step 2: Refactor Buffer
#include <vector>#include <string>#include <string_view>#include <stdexcept>
class Buffer { std::vector<char> data_;
public: explicit Buffer(size_t initial_capacity = 1024) { data_.reserve(initial_capacity); }
// Rule of Zero: compiler-generated special members are correct
void append(std::string_view src) { data_.insert(data_.end(), src.begin(), src.end()); }
void append(const char* src, size_t len) { data_.insert(data_.end(), src, src + len); }
[[nodiscard]] std::string_view view() const { return {data_.data(), data_.size()}; }
[[nodiscard]] std::string to_string() const { return {data_.begin(), data_.end()}; }
[[nodiscard]] size_t size() const { return data_.size(); } [[nodiscard]] bool empty() const { return data_.empty(); }
void clear() { data_.clear(); }};Notice what isn't here: any manual memory management. std::vector handles allocation, freeing, bounds checking, copy and move. The class is pure Rule of Zero — the compiler-generated specials already do the right thing.
How do you know the new Buffer still behaves like the old one? Before refactoring, write characterisation tests: tests that pin down what the legacy code does today, right or wrong, so the rewrite has something to be checked against. Here are a few, run against both classes through small adapter functions. Predict whether the embedded-NUL test passes for the legacy class.
Step 3: Refactor Connection
#include <memory>#include <string>#include <optional>
class Connection { int socket_fd_ = -1; std::string hostname_; Buffer read_buf_; Buffer write_buf_; bool connected_ = false;
public: // Factory function instead of error-prone constructor [[nodiscard]] static std::unique_ptr<Connection> create(const std::string& host, int port) { auto conn = std::unique_ptr<Connection>(new Connection()); conn->hostname_ = host; conn->socket_fd_ = connect_to(host.c_str(), port); conn->connected_ = (conn->socket_fd_ >= 0); if (!conn->connected_) return nullptr; return conn; }
~Connection() { if (connected_ && socket_fd_ >= 0) { close_socket(socket_fd_); } }
// Non-copyable, movable Connection(const Connection&) = delete; Connection& operator=(const Connection&) = delete; Connection(Connection&& other) noexcept : socket_fd_(other.socket_fd_) , hostname_(std::move(other.hostname_)) , read_buf_(std::move(other.read_buf_)) , write_buf_(std::move(other.write_buf_)) , connected_(other.connected_) { other.socket_fd_ = -1; other.connected_ = false; }
// nullopt: recv failed (errno says why). 0: the peer closed the // connection. Anything else: that many bytes were appended. [[nodiscard]] std::optional<size_t> read_data() { char temp[256]; ssize_t n = recv(socket_fd_, temp, sizeof(temp), 0); if (n < 0) return std::nullopt; read_buf_.append(temp, static_cast<size_t>(n)); return static_cast<size_t>(n); }
// Returns a copy, not an internal pointer [[nodiscard]] std::string get_response() const { return read_buf_.to_string(); }
[[nodiscard]] bool is_connected() const { return connected_; } [[nodiscard]] const std::string& hostname() const { return hostname_; }
private: Connection() = default;};Step 4: Refactor ConnectionPool
class ConnectionPool { std::vector<std::unique_ptr<Connection>> connections_; size_t max_connections_;
public: explicit ConnectionPool(size_t max) : max_connections_(max) { connections_.reserve(max); }
[[nodiscard]] bool add(std::unique_ptr<Connection> conn) { if (connections_.size() >= max_connections_) { return false; } connections_.push_back(std::move(conn)); return true; }
[[nodiscard]] Connection* get(size_t index) { if (index >= connections_.size()) return nullptr; return connections_[index].get(); }
[[nodiscard]] const Connection* get(size_t index) const { if (index >= connections_.size()) return nullptr; return connections_[index].get(); }
[[nodiscard]] size_t size() const { return connections_.size(); } [[nodiscard]] size_t capacity() const { return max_connections_; }};Step 5: Add Sanitizer CI
# .github/workflows/sanitizers.ymlname: Sanitizer Testson: [push, pull_request]
jobs: sanitize: runs-on: ubuntu-latest strategy: matrix: config: - { name: "ASan+UBSan", flags: "-fsanitize=address,undefined" } - { name: "TSan", flags: "-fsanitize=thread" } steps: - uses: actions/checkout@v4 - name: Build with ${{ matrix.config.name }} run: | g++ -std=c++20 -Wall -Wextra -Werror \ ${{ matrix.config.flags }} \ -fno-omit-frame-pointer -g -O1 \ -o test tests.cpp - name: Run tests run: ./testRefactoring Checklist
When you're dragging any legacy C++ codebase forward:
- Replace
malloc/freewith containers or smart pointers. - Replace
new/deletewithmake_uniqueormake_shared. - Swap
char*strings forstd::string. - Trade C arrays for
std::vectororstd::array. - Sprinkle
constover everything that doesn't have to mutate. - Slap
[[nodiscard]]on anything where ignoring the return value is a bug. - Rip out raw owning pointers; use references or smart pointers instead.
- Convert C casts to their C++ equivalents.
- Define or
=deletecopy and move operations (Rule of Five/Zero). - Add bounds checking —
.at(), validated indices, or contracts. - Run the whole thing under ASan, UBSan, and TSan.
- Run clang-tidy and chase the warnings to zero.
Work through it methodically and dangerous legacy code turns into something you'd put your name on, with the original behaviour preserved.