Skip to content

Commit b2a592f

Browse files
authored
Merge pull request DeusData#941 from DeusData/sec/hardening-2026-07
Hardening pass: bounds, containment, and input validation across MCP/CLI/UI
2 parents 5554f8a + 839463d commit b2a592f

17 files changed

Lines changed: 565 additions & 70 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -476,6 +476,7 @@ codebase-memory-mcp config reset auto_index # reset to default
476476

477477
| Variable | Default | Description |
478478
|----------|---------|-------------|
479+
| `CBM_ALLOWED_ROOT` | *(unset)* | Restrict `index_repository` to paths within this directory. When set, a `repo_path` that resolves (after symlink / `..` resolution) outside this root is refused; unset imposes no restriction. Useful when the server may be driven by an untrusted caller, e.g. agentic or multi-tenant deployments. |
479480
| `CBM_CACHE_DIR` | `~/.cache/codebase-memory-mcp` | Override the database storage directory. All project indexes and config are stored here. |
480481
| `CBM_DIAGNOSTICS` | `false` | Set to `1` or `true` to enable periodic diagnostics output to `/tmp/cbm-diagnostics-<pid>.json`. |
481482
| `CBM_DOWNLOAD_URL` | *(GitHub releases)* | Override the download URL for updates. Used for testing or self-hosted deployments. |

‎docs/CONFIGURATION.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,7 @@ These environment variables affect runtime behavior:
110110

111111
| Variable | Default | Description |
112112
|---|---|---|
113+
| `CBM_ALLOWED_ROOT` | *(unset)* | Restrict `index_repository` to paths within this directory. When set, a `repo_path` that resolves (after symlink / `..` resolution) outside this root is refused; unset imposes no restriction. Useful when the server may be driven by an untrusted caller (agentic or multi-tenant deployments). |
113114
| `CBM_CACHE_DIR` | `~/.cache/codebase-memory-mcp` | Override the cache directory used for indexes, `_config.db`, and UI `config.json`. |
114115
| `CBM_DIAGNOSTICS` | `false` | Enable periodic diagnostics output to `/tmp/cbm-diagnostics-<pid>.json`. |
115116
| `CBM_DOWNLOAD_URL` | GitHub releases | Override the update download URL. |

‎internal/cbm/zstd_store.c‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
#include "zstd_store.h"
66

77
#include <stddef.h>
8+
#include <stdint.h>
89

910
int cbm_zstd_compress(const char *src, int srcLen, char *dst, int dstCap, int level) {
1011
size_t rc = ZSTD_compress(dst, (size_t)dstCap, src, (size_t)srcLen, level);
@@ -14,12 +15,20 @@ int cbm_zstd_compress(const char *src, int srcLen, char *dst, int dstCap, int le
1415
return (int)rc;
1516
}
1617

17-
int cbm_zstd_decompress(const char *src, int srcLen, char *dst, int dstCap) {
18-
size_t rc = ZSTD_decompress(dst, (size_t)dstCap, src, (size_t)srcLen);
18+
int64_t cbm_zstd_decompress(const char *src, size_t srcLen, char *dst, size_t dstCap) {
19+
size_t rc = ZSTD_decompress(dst, dstCap, src, srcLen);
1920
if (ZSTD_isError(rc)) {
2021
return 0;
2122
}
22-
return (int)rc;
23+
return (int64_t)rc;
24+
}
25+
26+
size_t cbm_zstd_frame_content_size(const char *src, size_t srcLen) {
27+
unsigned long long n = ZSTD_getFrameContentSize(src, srcLen);
28+
if (n == ZSTD_CONTENTSIZE_UNKNOWN || n == ZSTD_CONTENTSIZE_ERROR) {
29+
return 0;
30+
}
31+
return (size_t)n;
2332
}
2433

2534
size_t cbm_zstd_compress_bound(int inputSize) {

‎internal/cbm/zstd_store.h‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,22 @@
22
#define CBM_ZSTD_STORE_H
33

44
#include <stddef.h>
5+
#include <stdint.h>
56

67
// Zstd compression at specified level (1=fast .. 22=best).
78
// Returns compressed size on success, 0 on error.
89
int cbm_zstd_compress(const char *src, int srcLen, char *dst, int dstCap, int level);
910

10-
// Zstd decompression.
11-
// Returns decompressed size on success, 0 on error.
12-
int cbm_zstd_decompress(const char *src, int srcLen, char *dst, int dstCap);
11+
// Zstd decompression. srcLen/dstCap are size_t so a >2 GiB destination capacity
12+
// is never truncated (a large DB artifact, or a crafted one, would otherwise
13+
// wrap through int and desync the real buffer size from the decoder capacity).
14+
// Returns decompressed size on success (>0), 0 on error.
15+
int64_t cbm_zstd_decompress(const char *src, size_t srcLen, char *dst, size_t dstCap);
16+
17+
// Declared decompressed content size of a zstd frame (from its header), or 0
18+
// when unknown/unreadable. Lets the caller size the destination from the frame
19+
// itself instead of trusting a separate, attacker-controllable size field.
20+
size_t cbm_zstd_frame_content_size(const char *src, size_t srcLen);
1321

1422
// Maximum compressed size bound for given input size.
1523
size_t cbm_zstd_compress_bound(int inputSize);

‎src/cli/cli.c‎

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2968,15 +2968,16 @@ static bool prompt_yn(const char *question) {
29682968
/* Minimum line length in checksums.txt: CBM_SZ_64 hex + 2 spaces + 1 char filename */
29692969
#define CHECKSUM_LINE_MIN (SHA256_HEX_LEN + 2)
29702970

2971-
/* Compute SHA-CBM_SZ_256 of a file using platform tools (sha256sum/shasum).
2972-
* Writes CBM_SZ_64-char hex digest + NUL to out. Returns 0 on success. */
2973-
static int sha256_file(const char *path, char *out, size_t out_size) {
2971+
/* Compute the SHA-256 of a file using platform tools (sha256sum/shasum).
2972+
* Writes a 64-char hex digest + NUL to out. Returns 0 on success. Not static:
2973+
* exercised directly by the self-update checksum regression test. */
2974+
int cbm_cli_sha256_file(const char *path, char *out, size_t out_size) {
29742975
if (out_size < SHA256_BUF_SIZE) {
29752976
return CLI_ERR;
29762977
}
29772978
char cmd[CLI_BUF_1K];
29782979
#ifdef __APPLE__
2979-
snprintf(cmd, sizeof(cmd), "shasum -a CBM_SZ_256 '%s' 2>/dev/null", path);
2980+
snprintf(cmd, sizeof(cmd), "shasum -a 256 '%s' 2>/dev/null", path);
29802981
#else
29812982
snprintf(cmd, sizeof(cmd), "sha256sum '%s' 2>/dev/null", path);
29822983
#endif
@@ -3107,8 +3108,8 @@ static int verify_download_checksum(const char *archive_path, const char *archiv
31073108
}
31083109

31093110
char actual[SHA256_BUF_SIZE] = {0};
3110-
if (sha256_file(archive_path, actual, sizeof(actual)) != 0) {
3111-
(void)fprintf(stderr, "warning: sha256sum/shasum not available — skipping verification\n");
3111+
if (cbm_cli_sha256_file(archive_path, actual, sizeof(actual)) != 0) {
3112+
(void)fprintf(stderr, "error: could not compute checksum (sha256 tool unavailable)\n");
31123113
return CLI_ERR;
31133114
}
31143115

@@ -4250,8 +4251,12 @@ static int download_verify_install(const char *url, const char *ext, const char
42504251
const char *portable = (strcmp(os, "linux") == 0) ? "-portable" : "";
42514252
snprintf(archive_name, sizeof(archive_name), "codebase-memory-mcp-%s%s-%s%s.%s",
42524253
want_ui ? "ui-" : "", os, arch, portable, ext);
4254+
/* Fail closed: install only a positively-verified download. A mismatch,
4255+
* a missing checksum entry, or an unavailable hash tool (crc != 0) all
4256+
* abort rather than install an unverified binary. */
42534257
int crc = verify_download_checksum(tmp_archive, archive_name);
4254-
if (crc == CLI_TRUE) {
4258+
if (crc != 0) {
4259+
(void)fprintf(stderr, "error: refusing to install an unverified download\n");
42554260
cbm_unlink(tmp_archive);
42564261
return CLI_TRUE;
42574262
}

‎src/cypher/cypher.c‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1652,6 +1652,16 @@ static int parse_return_or_with(parser_t *p, cbm_return_clause_t **out, bool is_
16521652

16531653
} while (check(p, TOK_COMMA));
16541654

1655+
/* Projection is materialized per row into fixed-width stack arrays sized at
1656+
* CBM_SZ_32 columns (execute_return_simple and its siblings). Bound the
1657+
* parsed item count to that width so an over-wide RETURN is rejected here
1658+
* instead of writing past those arrays downstream. */
1659+
if (r->count > CBM_SZ_32) {
1660+
free(r->items);
1661+
free(r);
1662+
return CBM_NOT_FOUND;
1663+
}
1664+
16551665
tail:
16561666
/* Optional ORDER BY */
16571667
if (match(p, TOK_ORDER)) {

‎src/discover/discover.c‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -606,9 +606,20 @@ static int wide_stat(const char *path, struct stat *st) {
606606
#endif
607607
}
608608

609-
/* Stat a path, skipping symlinks. Returns 0 on success, -1 to skip. */
609+
/* Stat a path, skipping symlinks (POSIX) and junctions / reparse points
610+
* (Windows). Returns 0 on success, -1 to skip. Skipping reparse points keeps
611+
* discovery from walking through a junction that points outside the project
612+
* root, mirroring the POSIX S_ISLNK skip. */
610613
static int safe_stat(const char *abs_path, struct stat *st) {
611614
#ifdef _WIN32
615+
wchar_t *wpath = cbm_utf8_to_wide(abs_path);
616+
if (wpath) {
617+
DWORD attr = GetFileAttributesW(wpath);
618+
free(wpath);
619+
if (attr != INVALID_FILE_ATTRIBUTES && (attr & FILE_ATTRIBUTE_REPARSE_POINT)) {
620+
return CBM_NOT_FOUND;
621+
}
622+
}
612623
return wide_stat(abs_path, st);
613624
#else
614625
if (lstat(abs_path, st) != 0) {

‎src/mcp/mcp.c‎

Lines changed: 63 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -3842,6 +3842,8 @@ char *cbm_mcp_index_run_supervised_path(const char *root_path) {
38423842
return index_run_supervised_path(NULL, root_path);
38433843
}
38443844

3845+
bool cbm_path_within_root(const char *root_path, const char *abs_path); /* defined below */
3846+
38453847
static char *handle_index_repository(cbm_mcp_server_t *srv, const char *args) {
38463848
/* Supervisor gate: run the index in a crash/hang-isolating worker subprocess
38473849
* unless this process IS the worker or the kill switch (CBM_INDEX_SUPERVISOR=0)
@@ -3866,6 +3868,20 @@ static char *handle_index_repository(cbm_mcp_server_t *srv, const char *args) {
38663868

38673869
repo_path = canonicalize_repo_path_if_exists(repo_path);
38683870

3871+
/* Optional workspace boundary: when CBM_ALLOWED_ROOT is set (agentic /
3872+
* multi-tenant deployments where repo_path may be influenced by an
3873+
* untrusted caller), refuse to index a path that resolves outside it.
3874+
* Unset by default, so the standard "index the path I gave you" behaviour
3875+
* is unchanged. */
3876+
const char *allowed_root = getenv("CBM_ALLOWED_ROOT");
3877+
if (allowed_root && allowed_root[0] && repo_path &&
3878+
!cbm_path_within_root(allowed_root, repo_path)) {
3879+
free(mode_str);
3880+
free(name_override);
3881+
free(repo_path);
3882+
return cbm_mcp_text_result("repo_path is outside the allowed root", true);
3883+
}
3884+
38693885
if (mode_str && strcmp(mode_str, "cross-repo-intelligence") == 0) {
38703886
free(mode_str);
38713887
free(name_override);
@@ -4080,19 +4096,19 @@ static yyjson_doc *enrich_node_properties(yyjson_mut_doc *doc, yyjson_mut_val *o
40804096
/* Resolve an absolute path from root_path + file_path, verify containment,
40814097
* and read source lines. Sets *out_abs_path (caller frees). Returns source
40824098
* string (caller frees) or NULL if path is invalid/unreadable. */
4083-
static char *resolve_snippet_source(const char *root_path, const char *file_path, int start,
4084-
int end, char **out_abs_path) {
4085-
*out_abs_path = NULL;
4086-
if (!root_path || !file_path) {
4087-
return NULL;
4099+
/* True only when abs_path, after realpath/_fullpath resolution (which collapses
4100+
* `..` and resolves symlinks/junctions), stays within root_path. This is the
4101+
* single containment guard every MCP file-read sink must pass before reading a
4102+
* file into a tool response: both the snippet path (resolve_snippet_source) and
4103+
* the search path (attach_result_source) route through it, so a result whose
4104+
* indexed path escapes the project root — via a `..` segment, or a symlink /
4105+
* Windows junction picked up during discovery — is never read back out. */
4106+
bool cbm_path_within_root(const char *root_path, const char *abs_path) {
4107+
if (!root_path || !abs_path) {
4108+
return false;
40884109
}
4089-
size_t apsz = strlen(root_path) + strlen(file_path) + MCP_SEPARATOR;
4090-
char *abs_path = malloc(apsz);
4091-
snprintf(abs_path, apsz, "%s/%s", root_path, file_path);
4092-
40934110
char real_root[CBM_SZ_4K];
40944111
char real_file[CBM_SZ_4K];
4095-
bool path_ok = false;
40964112
#ifdef _WIN32
40974113
if (_fullpath(real_root, root_path, sizeof(real_root)) &&
40984114
_fullpath(real_file, abs_path, sizeof(real_file))) {
@@ -4104,11 +4120,24 @@ static char *resolve_snippet_source(const char *root_path, const char *file_path
41044120
size_t root_len = strlen(real_root);
41054121
if (strncmp(real_file, real_root, root_len) == 0 &&
41064122
(real_file[root_len] == '/' || real_file[root_len] == '\0')) {
4107-
path_ok = true;
4123+
return true;
41084124
}
41094125
}
4126+
return false;
4127+
}
4128+
4129+
static char *resolve_snippet_source(const char *root_path, const char *file_path, int start,
4130+
int end, char **out_abs_path) {
4131+
*out_abs_path = NULL;
4132+
if (!root_path || !file_path) {
4133+
return NULL;
4134+
}
4135+
size_t apsz = strlen(root_path) + strlen(file_path) + MCP_SEPARATOR;
4136+
char *abs_path = malloc(apsz);
4137+
snprintf(abs_path, apsz, "%s/%s", root_path, file_path);
4138+
41104139
*out_abs_path = abs_path;
4111-
if (path_ok) {
4140+
if (cbm_path_within_root(root_path, abs_path)) {
41124141
return read_file_lines(abs_path, start, end);
41134142
}
41144143
return NULL;
@@ -4570,6 +4599,14 @@ static void attach_result_source(yyjson_mut_doc *doc, yyjson_mut_val *item, sear
45704599
char abs_path[CBM_SZ_1K];
45714600
snprintf(abs_path, sizeof(abs_path), "%s/%s", root_path, r->file);
45724601

4602+
/* Containment: a search result whose indexed path resolves outside the
4603+
* project root (a `..` segment, or a symlink/junction that discovery
4604+
* followed) must not be read back into the response. Same guard the
4605+
* snippet path already uses. */
4606+
if (!cbm_path_within_root(root_path, abs_path)) {
4607+
return;
4608+
}
4609+
45734610
if (mode == MODE_FULL) {
45744611
char *source = read_file_lines(abs_path, r->start_line, r->end_line);
45754612
if (source) {
@@ -4938,6 +4975,14 @@ static bool write_scoped_filelist(cbm_mcp_server_t *srv, const char *project, co
49384975
int written = 0;
49394976
if (fl) {
49404977
for (int fi = 0; fi < indexed_count; fi++) {
4978+
/* A source path never legitimately contains a newline or carriage
4979+
* return. Those bytes are exactly the record separator on the
4980+
* Windows filelist (and would split naive line readers elsewhere),
4981+
* so a crafted indexed path with an embedded newline could inject
4982+
* an extra entry into the scan set. Skip such paths entirely. */
4983+
if (strpbrk(indexed_files[fi], "\r\n") != NULL) {
4984+
continue;
4985+
}
49414986
if (has_path_filter && path_regex) {
49424987
#ifdef _WIN32
49434988
cbm_normalize_path_sep(indexed_files[fi]);
@@ -5352,8 +5397,12 @@ static char *handle_detect_changes(cbm_mcp_server_t *srv, const char *args) {
53525397
base_branch = heap_strdup("main");
53535398
}
53545399

5355-
/* Reject shell metacharacters in user-supplied branch name */
5356-
if (!cbm_validate_shell_arg(base_branch)) {
5400+
/* Reject shell metacharacters, and a leading '-', in the user-supplied
5401+
* branch name. base_branch is spliced into `git diff --name-only
5402+
* "<base>"...HEAD`; a value starting with '-' would be read by git as an
5403+
* option rather than a ref (e.g. `--output=<path>` writes the diff to an
5404+
* arbitrary file). A real git ref never begins with '-'. */
5405+
if (!cbm_validate_shell_arg(base_branch) || base_branch[0] == '-') {
53575406
free(project);
53585407
free(base_branch);
53595408
free(scope);

‎src/pipeline/artifact.c‎

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,13 @@ enum {
1515
};
1616
#define ART_BYTES_PER_MB ((size_t)1024 * 1024)
1717

18+
/* Generous ceiling on an imported artifact's decompressed size. Real indexes
19+
* (a full Linux-kernel DB is ~14 GB) fit comfortably; a frame that declares
20+
* more than this is rejected before any allocation so a crafted content size
21+
* can neither trigger a runaway allocation nor be used to desync the decoder
22+
* capacity from the destination buffer. */
23+
#define ART_MAX_DECOMPRESSED_BYTES ((size_t)64 * 1024 * ART_BYTES_PER_MB)
24+
1825
#include "pipeline/artifact.h"
1926
#include "store/store.h"
2027
#include "foundation/platform.h"
@@ -614,16 +621,29 @@ int cbm_artifact_import(const char *repo_path, const char *cache_db_path) {
614621
}
615622

616623
/* Decompress */
617-
char *decompressed = malloc(original_size);
624+
/* Size the destination from the zstd frame's own content-size header, not
625+
* from the separately-stored (attacker-controllable) original_size field.
626+
* The allocation and the decoder capacity are then the SAME size_t value,
627+
* so a crafted size can never make the capacity exceed the real buffer
628+
* (the int-truncation that used to do exactly that is gone with the size_t
629+
* signature). Require the metadata field to agree, and cap the total. */
630+
size_t frame_size = cbm_zstd_frame_content_size(compressed, clen);
631+
if (frame_size == 0 || frame_size > ART_MAX_DECOMPRESSED_BYTES || frame_size != original_size) {
632+
free(compressed);
633+
cbm_log_error("artifact.import", "err", "bad_decompressed_size");
634+
return CBM_NOT_FOUND;
635+
}
636+
637+
char *decompressed = malloc(frame_size);
618638
if (!decompressed) {
619639
free(compressed);
620640
return CBM_NOT_FOUND;
621641
}
622642

623-
int dlen = cbm_zstd_decompress(compressed, (int)clen, decompressed, (int)original_size);
643+
int64_t dlen = cbm_zstd_decompress(compressed, clen, decompressed, frame_size);
624644
free(compressed);
625645

626-
if (dlen <= 0) {
646+
if (dlen <= 0 || (size_t)dlen != frame_size) {
627647
free(decompressed);
628648
cbm_log_error("artifact.import", "err", "zstd_decompress");
629649
return CBM_NOT_FOUND;

0 commit comments

Comments
 (0)