Commit graph

14 commits

Author SHA1 Message Date
14789cd1c8 fix: guard terminal width/height in all TUI renderers and harden edge cases
- Replace all direct client->width/height reads with local variables
  clamped to minimums (width>=10, height>=4) across tui_render_screen,
  tui_render_input, tui_render_command_output, and tui_render_help
- Fix tui_render_input underflow when width < 3 (avail = max(rw-3, 1))
- Show username in title bar instead of generic label
- Add /me action message support in exec_command_post for scripting parity
- Reject empty usernames when loading messages from log file
2026-04-19 18:58:51 +08:00
b1c1e5a894 fix: deadlock in whisper, use-after-free in callbacks, log rotation, tail parsing
- Whisper: copy target client ref out of room lock before calling
  client_send, preventing lock-ordering inversion deadlock
- Channel callbacks: call ssh_remove_channel_callbacks before releasing
  refs to prevent use-after-free if a callback fires during cleanup
- Log rotation: rotate messages.log to messages.log.1 when it exceeds
  10 MiB, preventing unbounded growth on public servers
- tail -nN: accept both "tail -n5" and "tail -n 5" forms, matching
  standard Unix tail behavior

Closes #36
2026-04-19 18:27:54 +08:00
200e5a2f28
Merge pull request #22 from m1ngsama/feat/expand-unit-tests
Add chat_room unit tests and integrate into CI
2026-04-19 17:39:25 +08:00
ecc45f285c test: add chat_room unit tests and integrate into build
- Add 11 unit tests for chat_room.c covering: create/destroy, message
  add/overflow, broadcast sequence, get_message bounds, client
  add/remove/capacity, and null argument handling
- Add unit-test target to root Makefile so `make test` runs unit tests
  before integration tests
- Add common.c to unit test link dependencies (needed for tnt_state_path)
- Guard _DARWIN_C_SOURCE define to prevent -Wmacro-redefined warning
2026-04-19 15:22:01 +08:00
8be6476367 fix: harden edge cases in message loading and network I/O
- Check ftell() return for errors (-1) in message_load to prevent
  corrupted backward scan on I/O failures
- Cap ssh_channel_write chunks to 32KB to prevent size_t-to-uint32_t
  narrowing on large buffers
- Log evicted active connection count in rate-limit table overflow
  warning for better diagnostics
2026-04-19 15:18:09 +08:00
0de13a6314 fix: add _DARWIN_C_SOURCE for timegm() on macOS CI
Some checks failed
CI / build-and-test (macos-latest) (push) Has been cancelled
CI / build-and-test (ubuntu-latest) (push) Has been cancelled
Deploy / test (push) Has been cancelled
Deploy / deploy (push) Has been cancelled
2026-04-15 10:15:32 +08:00
d745a8e1fe fix: address security vulnerabilities and design flaws from comprehensive audit
Critical fixes:
- C-1: Use atomic_bool for client->connected and redraw_pending to prevent
  data races between callback and main threads
- C-2: Add reference counting for channel callbacks to prevent use-after-free
  when callbacks fire during client cleanup
- C-3/M-7: Use ssh_channel_read_timeout (5s) for UTF-8 continuation bytes
  to prevent thread blocking and stream desynchronization

High-severity fixes:
- H-1: Replace non-thread-safe setenv/tzset with timegm() in parse_rfc3339_utc
- H-2: Change room_get_message to return by value copy instead of interior pointer
- H-3: Log warning when rate-limit table evicts active IP entry
- H-4: Replace strcmp with constant-time comparison for access token validation
- H-5: Check signature_state in auth_pubkey to reject unsigned key offers

Medium/low fixes:
- M-1: Replace all atoi() with strtol() for proper error detection
- M-3: Move calloc outside rwlock in tui_render_screen to avoid blocking writers
- M-8: Fix off-by-one in rate limit threshold (> to >=)
- M-9: Trim partial UTF-8 sequences after snprintf truncation in message_format
- L-1: Validate continuation byte mask (0xC0==0x80) in utf8_decode
- D-3: Remove vestigial client_t.fd field
- L-3: Remove unreachable pthread_attr_destroy after infinite loop
2026-04-15 10:13:17 +08:00
e473b26e0d refactor: stabilize SSH runtime and add exec interface 2026-03-10 18:52:20 +08:00
07fd7b1513
refactor: optimize rendering, log loading, and migrate to libssh callback API (#9)
This PR addresses critical performance bottlenecks, improves UX, and eliminates technical debt.

### Key Changes

**1. Performance Optimization:**
- **Startup**: Rewrote `message_load` to scan `messages.log` backwards from the end
  - Complexity reduced from O(FileSize) to O(MaxMessages)
  - Large log file startup: seconds → milliseconds
- **Rendering**: Optimized TUI rendering to use line clearing (`\033[K`) instead of full-screen clearing (`\033[2J`)
  - Eliminated visual flicker

**2. libssh API Migration:**
- Replaced deprecated message-based API with callback-based server implementation
- Removed `#pragma GCC diagnostic ignored "-Wdeprecated-declarations"`
- Ensures future libssh compatibility

**3. User Experience (Vim Mode):**
- Added `Ctrl+W` (Delete Word) and `Ctrl+U` (Delete Line) in Insert/Command modes
- Modified `Ctrl+C` behavior to safely switch modes instead of terminating connection
- Added support for `\n` as Enter key (fixing piped input issues)

**4. Project Structure:**
- Moved all test scripts to `tests/` directory
- Added `make test` target
- Updated CI/CD to run comprehensive test suite

### Verification
-  All tests passing (17/17)
-  CI passing on Ubuntu and macOS
-  AddressSanitizer clean
-  Valgrind clean (no memory leaks)
-  Zero compilation warnings

### Code Quality
**Rating:** 🟢 Good Taste
- Algorithm-driven optimization (not hacks)
- Simplified architecture (callback-based API)
- Zero breaking changes (all tests pass)
2026-02-07 23:17:55 +08:00
4a34a776c2 Merge branch 'fix/resource-management' into feat/security-audit-fixes 2026-01-22 14:07:10 +08:00
f65e8add64 fix(security): enhance resource management
- Convert message_load() file position array from fixed 1000 to dynamic:
  * Start with capacity of 1000, grow by 2x when needed
  * Use malloc/realloc for flexible memory management
  * Proper cleanup with free() after use
  * Graceful handling of memory allocation failures
- Enhance setup_host_key() error handling:
  * Validate key file size (reject 0 bytes and >10MB)
  * Automatically regenerate if key file is empty
  * Verify and fix insecure permissions (must be 0600)
  * Better error messages with file size reporting
- Improve client thread resource cleanup:
  * Use pthread_attr for explicit detached thread creation
  * Add pthread_mutex_destroy on thread creation failure
  * Proper cleanup order: mutex -> channel -> session -> memory
  * Add error logging with strerror() for thread failures

These changes address:
- Fixed 1000-line limit causing message truncation
- Corrupted/empty key file handling
- Permission race conditions
- Resource leaks on thread creation failure

Prevents:
- DoS via large log files
- Service startup failures from bad key files
- Memory/handle leaks under error conditions
2026-01-22 14:02:05 +08:00
4f3a07c5e2 fix(security): implement comprehensive input validation
- Add is_valid_username() function to prevent injection attacks
  * Reject shell metacharacters: |;&$`<>(){}[]'"\
  * Reject control characters (except tab)
  * Reject usernames starting with space, dot, or dash
- Apply username validation in read_username() with fallback to "anonymous"
- Add rate limiting via sleep(1) on validation failure
- Sanitize message content in message_save():
  * Replace pipe, newline, carriage return to prevent log injection
  * Ensure null termination of sanitized strings
- Enhance message_load() validation:
  * Check for oversized lines
  * Validate field lengths before copying
  * Validate timestamp reasonableness (not >1 day future, <10 years past)
  * Ensure null termination of all loaded strings

These changes address:
- Username injection vulnerabilities
- Message content injection in log files
- Log file format corruption attacks
- Malformed timestamp handling

Prevents:
- Command injection via usernames
- Log poisoning attacks
- DoS via oversized messages
2026-01-22 13:59:58 +08:00
1913a00f27 Optimize message history loading
Previous implementation:
- Allocated MAX_MESSAGES * 10 (1000 messages) temporarily
- Wasted ~100KB per server startup
- Could fail if log file grows very large

New implementation:
- Track file positions of last 1000 lines
- Seek to appropriate position before reading
- Only allocate MAX_MESSAGES (100 messages)
- Memory usage reduced by 90%

Benefits:
- Faster startup with large log files
- Lower memory footprint
- No risk of allocation failure
- Same functionality maintained

Uses fseek/ftell for efficient log file handling.
2025-12-01 16:30:00 +08:00
63274b92ba Initial commit 2025-07-01 09:00:00 +08:00