Skip to content

fix: Address multiple local memory and boundary bounds vulnerabilities inside parsing layers - #1

Closed
doomedraven wants to merge 12 commits into
capemonfrom
opt/security-fixes
Closed

fix: Address multiple local memory and boundary bounds vulnerabilities inside parsing layers#1
doomedraven wants to merge 12 commits into
capemonfrom
opt/security-fixes

Conversation

@doomedraven

Copy link
Copy Markdown
Owner

Fixes identified in the capemon_security_review: Resolves unsigned underflow allocations hitting snprintf routines, expands hardcoded local stack matrices breaking deep module hooking structures, seals RWX tracker bindings mapped across DLL spaces, and restores missing toolhelp context closing routines inside trampoline maps.

doomedraven and others added 12 commits August 19, 2026 12:36
…(SBO-Decoupling)

Implements completely concurrent and thread-local log serialization inside loq. Makes g_bson and g_istr thread-local variables using __declspec(thread), allowing multiple monitored threads to format their API arguments lock-free. Holds the global g_mutex strictly during the actual BSON buffer flush/cache operations, dropping lock-hold times from milliseconds to microseconds.
…2 Fix)

Surgically fixes the fatal crash bug caused by illegal static TLS usage (__declspec(thread)) inside the dynamically injected capemon.dll:
1. Replaces the unsupported static TLS variables g_bson and g_istr with safe, dynamic Windows Thread Local Storage (TLS) API (TlsAlloc, TlsGetValue, TlsSetValue, TlsFree).
2. Maps g_bson and g_istr through preprocessor macros to dynamic, auto-allocated thread contexts (thread_log_context_t) on-the-fly, retaining 100% compatibility with all 50+ logging helper functions.
3. Automatically frees thread-local log contexts during DLL_THREAD_DETACH inside DllMain to guarantee absolute zero memory leaks.
…zation

Addresses three critical defects in the concurrent logging implementation:

1. NULL Pointer Dereference Protection:
   - Added null check when calloc() fails in GetThreadLogContext()
   - Added null-safe accessor macros for g_bson and g_istr
   - Added early TLS validation in loq() before any logging operations
   - Prevents crashes when TLS allocation fails

2. Race Condition Fix in logtbl_explained:
   - Fixed broken double-checked locking with volatile cast
   - Added proper memory ordering: *(volatile char*)&logtbl_explained[index]
   - Replaced unsafe goto skip_explain with early return + cleanup
   - Ensures thread-safe initialization of log table explanations

3. Performance Optimization with __declspec(thread):
   - Added g_tls_ctx_cache using __declspec(thread) as described in PR
   - GetThreadLogContext() now returns cached value after first lookup
   - Eliminates repeated expensive TlsGetValue() calls on hot path
   - Cache cleared properly in TlsThreadCleanup()

The hybrid TLS approach (TLS API + __declspec(thread) cache) provides:
- Cross-DLL thread tracking compatibility
- Fast repeated access within same thread
- Proper cleanup on thread detach

All changes maintain 100% backward compatibility.
Test coverage:
- Concurrent logging from 16 threads (80,000 log operations)
- Rapid thread creation/destruction (TLS stress test)
- logtbl_explained race condition test (32 threads, same index)

Verifies all three critical fixes:
1. NULL pointer protection (TLS allocation failures)
2. Race condition fix (volatile + double-checked locking)
3. Performance optimization (__declspec(thread) cache)

Run with: cd tests && make test-tls-logging.exe && ./test-tls-logging.exe
…obuf)

Introduces a highly flexible, pluggable logging interface (g_active_serializer Strategy Pattern) supporting both BSON and Protocol Buffers dynamically:
1. Retains BSON as the 100% backward-compatible default serializer (preserving full compatibility for custom agents and result servers).
2. Adds high-performance, robust, and safe Protocol Buffers logging (via nanopb) which can be enabled dynamically at runtime using the config option "log-format = 1".
3. Fully resolves the critical UAF memory lifecycles bug on wide strings inside protobuf_wrapper.c by implementing a fast, zero-allocation, thread-local string and binary scratch-pad bump allocator.
4. Increases the nanopb serialization buffer size from 4KB to 64KB (allocated on static thread-local context structures) to safely prevent large payloads and decrypted config drops.
Test coverage:
- BSON serialization (default mode)
- Protobuf serialization (opt-in mode)
- Runtime serializer switching
- Thread-local serializer isolation (16 threads)
- Concurrent mixed serializers (8 threads, BSON + Protobuf)
- NULL safety in serializer access

Verifies:
1. Strategy pattern implementation
2. Thread-safe serializer switching
3. Independent per-thread serializer contexts
4. Graceful fallback on NULL
5. No interference between BSON and Protobuf modes

Run with: cd tests && make test-pluggable-serialization.exe && ./test-pluggable-serialization.exe
…efault_serializer and including log_serializer.h
…, missing handle closures, and exposed RWX tracking limits.
doomedraven added a commit that referenced this pull request Aug 31, 2026
Issue: Previous fix (skip SoftwareBreakpointCallback when GoBreakpointHandler returns TRUE) broke essential debugger infrastructure.

Analysis: SoftwareBreakpointCallback provides framework-level operations:
  - BreakpointsHit flag (re-entrancy guard)
  - StepCount++ (step limit enforcement)
  - ActionDispatcher (user-configured actions)
  - Behavior logging
  - Register change tracking
  - Instruction disassembly/handling
  - Return address breakpoint setup

Solution:
1. REVERTED: Conditional skip of SoftwareBreakpointCallback
   - Both handlers now execute unconditionally
   - GoBreakpointHandler provides Go-specific processing
   - SoftwareBreakpointCallback provides core debugger infrastructure

2. FIXED: Inline extern declaration
   - Moved GoBreakpointHandler extern from function body to file scope
   - Eliminates redundant re-declaration on every breakpoint
   - Follows C conventions for forward declarations

Note: Remaining issues require architectural refactoring:
  - Issue #1: Nested TLS.Read calls overwrite t_go_return_hook_address (needs stack-based tracking)
  - Issue #3: Orphaned return breakpoint on abnormal termination (needs cleanup guarantees)
doomedraven added a commit that referenced this pull request Aug 31, 2026
Issue #1: Nested crypto/tls.Read calls were overwriting single thread-local
t_go_return_hook_address, causing orphaned breakpoints and data loss.

Issue #3: Abnormal termination (exceptions) left breakpoints armed on dangling
addresses without cleanup.

Solution: Replace single thread-local variables with stack-based tracking:

1. Stack Structure:
   - GoTlsState: { returnAddress, readBuffer }
   - Stack depth: 16 levels (handles typical nesting)
   - Thread-local stack pointer for LIFO management

2. Call Entry (crypto/tls.Read hook):
   - Push {returnAddress, readBuffer} onto stack
   - Arm breakpoint at returnAddress
   - Stack overflow protection (silently skip if >16 nested)

3. Call Exit (return breakpoint):
   - Pop matching state from stack (LIFO correctness)
   - Capture TLS plaintext data using popped buffer
   - Disarm breakpoint
   - Exception handler ensures stack consistency even on crash

Benefits:
   - Correct handling of nested/recursive TLS.Read calls
   - Automatic cleanup on exception (stack pointer decremented in __except)
   - No orphaned breakpoints or stale state
   - Memory-safe: bounded stack, no dynamic allocation
@doomedraven
doomedraven deleted the opt/security-fixes branch August 31, 2026 14:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant