Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Makefile.cbm
Original file line number Diff line number Diff line change
Expand Up @@ -372,6 +372,7 @@ FOUNDATION_SRCS = \
src/foundation/subprocess.c \
src/foundation/git_env.c \
src/foundation/sha256.c \
src/foundation/build_stamp.c \
src/foundation/secure_random.c \
src/foundation/macos_acl.c \
src/foundation/private_file_lock.c \
Expand Down
68 changes: 68 additions & 0 deletions scripts/build-stamp.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
#!/usr/bin/env python3
"""Stamp the build identity into a linked codebase-memory-mcp image (#2683).

The build fingerprint is the SHA-256 of the image with the 32 bytes that
follow the stamp magic read as zeros (src/foundation/build_stamp.c). This
script computes that digest and writes it into those 32 bytes, so the process
can read its own fingerprint instead of hashing its whole image at startup.

It only reads and writes bytes: the image is never executed, which keeps the
release pipeline's rule that no candidate runs before VirusTotal selection.
The image must contain the magic exactly once. Prints the digest.
"""

from __future__ import annotations

import hashlib
import os
import sys

MAGIC = b"\x89CBM-BUILDSTAMP\x01"
PAYLOAD_LEN = 32


def stamp_digest(data: bytearray) -> tuple[str, list[int]]:
"""Zero every payload in stream order and hash; return digest and offsets."""
payloads = []
at = data.find(MAGIC)
while at != -1:
start = at + len(MAGIC)
data[start : start + PAYLOAD_LEN] = bytes(len(data[start : start + PAYLOAD_LEN]))
payloads.append(start)
at = data.find(MAGIC, at + 1)
return hashlib.sha256(data).hexdigest(), payloads


def main(argv: list[str]) -> int:
if len(argv) != 2:
print("usage: build-stamp.py <executable>", file=sys.stderr)
return 2
path = argv[1]
with open(path, "rb") as handle:
data = bytearray(handle.read())
digest, payloads = stamp_digest(data)
if len(payloads) != 1 or payloads[0] + PAYLOAD_LEN > len(data):
print(f"build-stamp: {path}: expected exactly one stamp slot, found {len(payloads)}",
file=sys.stderr)
return 1
payload = bytes.fromhex(digest)
fd = os.open(path, os.O_WRONLY | getattr(os, "O_NOFOLLOW", 0))
try:
os.pwrite(fd, payload, payloads[0])
os.fsync(fd)
finally:
os.close(fd)
# Re-read: the stored payload must be the digest of the stamped file.
with open(path, "rb") as handle:
stamped = bytearray(handle.read())
stored = bytes(stamped[payloads[0] : payloads[0] + PAYLOAD_LEN])
again, _ = stamp_digest(stamped)
if stored != payload or again != digest:
print(f"build-stamp: {path}: verification failed after writing", file=sys.stderr)
return 1
print(digest)
return 0


if __name__ == "__main__":
sys.exit(main(sys.argv))
17 changes: 17 additions & 0 deletions scripts/build.sh
Original file line number Diff line number Diff line change
Expand Up @@ -208,4 +208,21 @@ else
CFLAGS_EXTRA="$CFLAGS_EXTRA" "${EXTRA_MAKE_ARGS[@]+"${EXTRA_MAKE_ARGS[@]}"}"
fi

# Step 3 (#2683): stamp the build identity into ELF executables so short-lived
# processes read it instead of hashing the whole image. The stamper only reads
# and writes bytes; it never runs the binary. Release candidates are stamped
# again after strip by scripts/ci/prepare-release-candidates.sh.
case "$(uname -s)" in
Linux | FreeBSD | NetBSD)
if command -v python3 >/dev/null 2>&1; then
python3 "$ROOT/scripts/build-stamp.py" "${BUILD_DIR}/codebase-memory-mcp" >/dev/null || {
echo "error: build-stamp failed" >&2
exit 1
}
else
echo "warning: python3 not found; leaving the build unstamped (it hashes itself at startup)" >&2
fi
;;
esac

echo "=== Build complete: ${BUILD_DIR}/codebase-memory-mcp ==="
15 changes: 15 additions & 0 deletions scripts/ci/prepare-release-candidates.sh
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,21 @@ if ! "$STRIP_TOOL" --strip-debug "$DEBUG_STRIPPED" 2>/dev/null; then
DEBUG_STRIP_INVOCATION="$(basename "$STRIP_TOOL") -S"
fi

# #2683: stamp the build identity into every ELF candidate. This must run
# after strip (strip rewrites the bytes the stamp covers) and before any
# signing; Mach-O and PE stay unstamped and keep hashing their image. The
# stamper reads and writes bytes only: no candidate is executed here.
case "$GOOS" in
linux)
for candidate in "$UNSTRIPPED" "$DEBUG_STRIPPED" "$STRIPPED"; do
python3 "$ROOT/scripts/build-stamp.py" "$candidate" >/dev/null || {
echo "prepare-release-candidates: build-stamp failed for $candidate" >&2
exit 2
}
done
;;
esac

UNSTRIPPED_PRE_SIGN_SHA="$(sha256_file "$UNSTRIPPED")"
DEBUG_STRIPPED_PRE_SIGN_SHA="$(sha256_file "$DEBUG_STRIPPED")"
STRIPPED_PRE_SIGN_SHA="$(sha256_file "$STRIPPED")"
Expand Down
20 changes: 12 additions & 8 deletions src/daemon/service.c
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
#include "daemon/ipc.h"
#endif

#include "foundation/build_stamp.h"
#include "foundation/sha256.h"

#include <errno.h>
Expand Down Expand Up @@ -370,8 +371,10 @@ bool cbm_daemon_build_fingerprint_native_file(uintptr_t native_file,
return false;
}

cbm_sha256_ctx context;
cbm_sha256_init(&context);
/* The fingerprint excludes the build-stamp payload (#2683); on an
* unstamped image this equals a plain SHA-256 of the bytes. */
cbm_build_stamp_hasher_t context;
cbm_build_stamp_hasher_init(&context);
unsigned char buffer[DAEMON_SERVICE_IO_CAP];
off_t offset = 0;
bool ok = true;
Expand All @@ -380,7 +383,7 @@ bool cbm_daemon_build_fingerprint_native_file(uintptr_t native_file,
size_t request = remaining < (off_t)sizeof(buffer) ? (size_t)remaining : sizeof(buffer);
ssize_t count = pread(fd, buffer, request, offset);
if (count > 0) {
cbm_sha256_update(&context, buffer, (size_t)count);
cbm_build_stamp_hasher_update(&context, buffer, (size_t)count);
offset += (off_t)count;
} else if (count == 0) {
ok = false;
Expand All @@ -398,7 +401,7 @@ bool cbm_daemon_build_fingerprint_native_file(uintptr_t native_file,
return false;
}
uint8_t digest[CBM_SHA256_DIGEST_LEN];
cbm_sha256_final(&context, digest);
cbm_build_stamp_hasher_final(&context, digest);
digest_to_hex(digest, out);
return true;
}
Expand Down Expand Up @@ -697,8 +700,9 @@ bool cbm_daemon_build_fingerprint_native_file(uintptr_t native_file,
(info.dwFileAttributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT)) == 0 &&
windows_same_file_identity(&original_info, &info) && GetFileSizeEx(file, &before) != 0 &&
before.QuadPart >= 0;
cbm_sha256_ctx context;
cbm_sha256_init(&context);
/* Same stamp-excluding digest as the POSIX variant (#2683). */
cbm_build_stamp_hasher_t context;
cbm_build_stamp_hasher_init(&context);
unsigned char buffer[DAEMON_SERVICE_IO_CAP];
uint64_t total = 0;
while (ok) {
Expand All @@ -708,7 +712,7 @@ bool cbm_daemon_build_fingerprint_native_file(uintptr_t native_file,
} else if (count == 0) {
break;
} else {
cbm_sha256_update(&context, buffer, count);
cbm_build_stamp_hasher_update(&context, buffer, count);
total += count;
}
}
Expand All @@ -725,7 +729,7 @@ bool cbm_daemon_build_fingerprint_native_file(uintptr_t native_file,
return false;
}
uint8_t digest[CBM_SHA256_DIGEST_LEN];
cbm_sha256_final(&context, digest);
cbm_build_stamp_hasher_final(&context, digest);
digest_to_hex(digest, out);
return true;
}
Expand Down
144 changes: 144 additions & 0 deletions src/foundation/build_stamp.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
/*
* build_stamp.c — see build_stamp.h.
*/
#include "foundation/build_stamp.h"

#include <string.h>

#if defined(__GNUC__) || defined(__clang__)
#define CBM_BUILD_STAMP_USED __attribute__((used))
#else
#define CBM_BUILD_STAMP_USED
#endif

/* The slot: magic followed by the payload. volatile keeps the compiler from
* folding reads of the (initially zero) payload into constants; the bytes the
* process reads are the ones the stamp step wrote into the file. */
CBM_BUILD_STAMP_USED static volatile const uint8_t
cbm_build_stamp_slot[CBM_BUILD_STAMP_MAGIC_LEN + CBM_BUILD_STAMP_PAYLOAD_LEN] = {
0x89, 'C', 'B', 'M', '-', 'B', 'U', 'I', 'L', 'D', 'S', 'T', 'A', 'M', 'P', 0x01,
/* payload: 32 zero bytes until stamped */
};

void cbm_build_stamp_magic(uint8_t out[CBM_BUILD_STAMP_MAGIC_LEN]) {
for (size_t i = 0; i < CBM_BUILD_STAMP_MAGIC_LEN; i++) {
out[i] = cbm_build_stamp_slot[i];
}
}

static const char k_hex_digits[] = "0123456789abcdef";

static void stamp_to_hex(const uint8_t bytes[CBM_BUILD_STAMP_PAYLOAD_LEN],
char out[CBM_BUILD_STAMP_HEX_SIZE]) {
for (size_t i = 0; i < CBM_BUILD_STAMP_PAYLOAD_LEN; i++) {
out[i * 2U] = k_hex_digits[(bytes[i] >> 4U) & 0x0FU];
out[i * 2U + 1U] = k_hex_digits[bytes[i] & 0x0FU];
}
out[CBM_BUILD_STAMP_PAYLOAD_LEN * 2U] = '\0';
}

bool cbm_build_stamp_self_fingerprint(char out[CBM_BUILD_STAMP_HEX_SIZE]) {
if (!out) {
return false;
}
out[0] = '\0';
uint8_t payload[CBM_BUILD_STAMP_PAYLOAD_LEN];
uint8_t any = 0;
for (size_t i = 0; i < CBM_BUILD_STAMP_PAYLOAD_LEN; i++) {
payload[i] = cbm_build_stamp_slot[CBM_BUILD_STAMP_MAGIC_LEN + i];
any |= payload[i];
}
if (any == 0) {
return false;
}
stamp_to_hex(payload, out);
return true;
}

void cbm_build_stamp_hasher_init(cbm_build_stamp_hasher_t *hasher) {
memset(hasher, 0, sizeof(*hasher));
cbm_sha256_init(&hasher->sha);
cbm_build_stamp_magic(hasher->magic);
}

static void stamp_note_match(cbm_build_stamp_hasher_t *hasher, uint64_t payload_at) {
hasher->matches++;
uint64_t end = payload_at + CBM_BUILD_STAMP_PAYLOAD_LEN;
if (end > hasher->zero_until) {
hasher->zero_until = end;
}
}

/* Zero the payload bytes of data[from..len) that fall before zero_until. */
static void stamp_zero_pending(const cbm_build_stamp_hasher_t *hasher, uint8_t *data, size_t len,
uint64_t base, size_t from) {
if (hasher->zero_until <= base + from) {
return;
}
uint64_t stop = hasher->zero_until - base;
size_t end = stop < (uint64_t)len ? (size_t)stop : len;
if (end > from) {
memset(data + from, 0, end - from);
}
}

void cbm_build_stamp_hasher_update(cbm_build_stamp_hasher_t *hasher, uint8_t *data, size_t len) {
if (!hasher || !data || len == 0) {
return;
}
const size_t magic_len = CBM_BUILD_STAMP_MAGIC_LEN;
const uint64_t base = hasher->offset;
/* Payload carried over from a match in an earlier call. */
stamp_zero_pending(hasher, data, len, base, 0);

/* Matches that start in the retained tail and end inside data. Bytes are
* read from the transformed stream, so zeroed payload never matches. */
for (size_t start = 0; start < hasher->tail_len; start++) {
size_t from_tail = hasher->tail_len - start;
if (magic_len - from_tail > len) {
continue;
}
if (memcmp(hasher->tail + start, hasher->magic, from_tail) == 0 &&
memcmp(data, hasher->magic + from_tail, magic_len - from_tail) == 0) {
size_t payload = magic_len - from_tail;
stamp_note_match(hasher, base + payload);
stamp_zero_pending(hasher, data, len, base, payload);
}
}

/* Matches that lie entirely inside data, in stream order. */
size_t pos = 0;
while (len - pos >= magic_len) {
const uint8_t *hit = memchr(data + pos, hasher->magic[0], len - pos - magic_len + 1U);
if (!hit) {
break;
}
size_t at = (size_t)(hit - data);
if (memcmp(hit, hasher->magic, magic_len) == 0) {
stamp_note_match(hasher, base + at + magic_len);
stamp_zero_pending(hasher, data, len, base, at + magic_len);
}
pos = at + 1U;
}

cbm_sha256_update(&hasher->sha, data, len);

/* Keep the last magic_len - 1 transformed bytes for the next call. */
const size_t keep = magic_len - 1U;
if (len >= keep) {
memcpy(hasher->tail, data + len - keep, keep);
hasher->tail_len = keep;
} else {
size_t total = hasher->tail_len + len;
size_t drop = total > keep ? total - keep : 0;
memmove(hasher->tail, hasher->tail + drop, hasher->tail_len - drop);
memcpy(hasher->tail + hasher->tail_len - drop, data, len);
hasher->tail_len = total - drop;
}
hasher->offset = base + len;
}

void cbm_build_stamp_hasher_final(cbm_build_stamp_hasher_t *hasher,
uint8_t digest[CBM_SHA256_DIGEST_LEN]) {
cbm_sha256_final(&hasher->sha, digest);
}
57 changes: 57 additions & 0 deletions src/foundation/build_stamp.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/*
* build_stamp.h — Build identity stamped into the executable after linking.
*
* The build fingerprint is the SHA-256 of the executable image with the
* 32-byte stamp payload treated as zeros. A post-link step
* (scripts/build-stamp.py, which never executes the image) computes that
* digest and writes it into the payload, so a process can read its own
* fingerprint from memory instead of hashing its ~300 MB image on every
* start (#2683).
*
* An unstamped image has an all-zero payload, so its fingerprint equals a
* plain SHA-256 of the file and the process falls back to hashing itself.
* The daemon still hashes images it has to verify (its own image at startup
* and peers running a different file), so a wrong stamp is refused there.
*/
#ifndef CBM_FOUNDATION_BUILD_STAMP_H
#define CBM_FOUNDATION_BUILD_STAMP_H

#include "foundation/sha256.h"

#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>

#define CBM_BUILD_STAMP_MAGIC_LEN 16U
#define CBM_BUILD_STAMP_PAYLOAD_LEN 32U
#define CBM_BUILD_STAMP_HEX_SIZE (CBM_BUILD_STAMP_PAYLOAD_LEN * 2U + 1U)

/* Streaming SHA-256 over an image in which the CBM_BUILD_STAMP_PAYLOAD_LEN
* bytes following every occurrence of the stamp magic are read as zeros. The
* transform is applied to the byte stream, so the digest does not depend on
* how the input is split into update() calls. update() zeroes payload bytes
* in the caller's buffer before hashing them. */
typedef struct {
cbm_sha256_ctx sha;
uint8_t magic[CBM_BUILD_STAMP_MAGIC_LEN];
uint8_t tail[CBM_BUILD_STAMP_MAGIC_LEN - 1U];
size_t tail_len;
uint64_t offset; /* stream offset of the next byte fed */
uint64_t zero_until; /* payload bytes before this offset are zeroed */
size_t matches; /* magic occurrences seen so far */
} cbm_build_stamp_hasher_t;

void cbm_build_stamp_hasher_init(cbm_build_stamp_hasher_t *hasher);
void cbm_build_stamp_hasher_update(cbm_build_stamp_hasher_t *hasher, uint8_t *data, size_t len);
void cbm_build_stamp_hasher_final(cbm_build_stamp_hasher_t *hasher,
uint8_t digest[CBM_SHA256_DIGEST_LEN]);

/* Copy the stamp magic out of this executable's own slot. The magic exists
* as a literal only in the slot initializer, so the image holds it once. */
void cbm_build_stamp_magic(uint8_t out[CBM_BUILD_STAMP_MAGIC_LEN]);

/* The fingerprint stamped into this executable, as lowercase hex. False when
* the payload is all zeros (an unstamped build). */
bool cbm_build_stamp_self_fingerprint(char out[CBM_BUILD_STAMP_HEX_SIZE]);

#endif /* CBM_FOUNDATION_BUILD_STAMP_H */
Loading
Loading