ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
known_hosts.c
Go to the documentation of this file.
1
6
7/* Storage capacities in elements; text buffers include the terminating NUL. */
8#define CRYPTO_KNOWN_HOSTS_ESCAPED_IP_WITH_PORT_BUFFER_SIZE 128
9#define CRYPTO_KNOWN_HOSTS_QUESTION_BUFFER_SIZE 2048
10
16
17#include <stdio.h>
18#include <string.h>
19#include <stdlib.h>
20#include <errno.h>
21#include <fcntl.h>
22
24#include <ascii-chat/crypto/crypto.h> // Includes <sodium.h>, CRYPTO_* constants
25#include <ascii-chat/common.h> // For BUFFER_SIZE_* constants
26#include <ascii-chat/asciichat_errno.h> // For asciichat_errno system
28#include <ascii-chat/crypto/regex.h> // For crypto_regex_match_known_hosts()
29#include <ascii-chat/util/ip.h>
30#include <libplatform/system.h> // For FILE_PERM_* constants
31#include <libplatform/terminal.h> // For platform_isatty()
32#include <libplatform/filesystem.h>
33#include <libplatform/question.h> // For platform_prompt_yes_no
34#include <options/options.h> // For opt_snapshot_mode
37#include <recast/defer.h>
38
39// Global variable to cache the expanded known_hosts path
40static char *g_known_hosts_path_cache = NULL;
41
57const char *get_known_hosts_path(void) {
58 // Return cached path if already determined
59 if (!g_known_hosts_path_cache) {
60 char *config_dir = get_config_dir();
61 if (!config_dir) {
62 log_error("Failed to determine configuration directory for known_hosts");
63 return NULL;
64 }
65 defer(SAFE_FREE(config_dir));
66
67 // Build path: config_dir + "known_hosts"
68 size_t config_len = strlen(config_dir);
69 size_t total_len = config_len + strlen("known_hosts") + 1;
70 char *path = SAFE_MALLOC(total_len, char *);
71 if (!path) {
72 log_error("Failed to allocate memory for known_hosts path");
73 return NULL;
74 }
75
76 safe_snprintf(path, total_len, "%sknown_hosts", config_dir);
77 g_known_hosts_path_cache = path;
78 log_debug("KNOWN_HOSTS: Using path %s", g_known_hosts_path_cache);
79 }
80 return g_known_hosts_path_cache;
81}
82
83// Format: IP:port x25519 <hex> [comment]
84// IPv4 example: 192.0.2.1:8080 x25519 1234abcd... ascii-chat
85// IPv6 example: [2001:db8::1]:8080 x25519 1234abcd... ascii-chat
86asciichat_error_t check_known_host(const char *server_ip, uint16_t port, const uint8_t server_key[ED25519_PUBLIC_KEY_SIZE]) {
87 return check_known_host_with_key(server_ip, port, server_key, NULL, NULL);
88}
89
91 bool *has_expected_key) {
92 if (has_expected_key)
93 *has_expected_key = false;
94 // Validate parameters first
95 if (!server_ip || !server_key) {
96 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: server_ip=%p, server_key=%p", server_ip, server_key);
97 }
98
99 // Format IP:port with proper bracket notation for IPv6
100 char ip_with_port[BUFFER_SIZE_MEDIUM];
101 if (format_ip_with_port(server_ip, port, ip_with_port, sizeof(ip_with_port)) != ASCIICHAT_OK) {
102 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid IP format: %s", server_ip);
103 }
104
105 // Add space after IP:port for prefix matching
106 char expected_prefix[BUFFER_SIZE_MEDIUM];
107 safe_snprintf(expected_prefix, sizeof(expected_prefix), "%s ", ip_with_port);
108
109 // Use platform abstraction to find all known_hosts files across standard locations
110 // Append semantics: search ALL files for matching entries (user + system)
111 config_file_list_t known_hosts_files = {0};
112 asciichat_error_t search_result = platform_find_config_file("known_hosts", &known_hosts_files);
113
114 if (search_result != ASCIICHAT_OK) {
115 // Platform search failed - non-fatal, treat as unknown host
116 log_debug("KNOWN_HOSTS: Failed to search for known_hosts files: %d", search_result);
117 return ASCIICHAT_OK;
118 }
119 defer(config_file_list_destroy(&known_hosts_files));
120
121 // If no files found, this is an unknown host (first connection)
122 if (known_hosts_files.count == 0) {
123 return ASCIICHAT_OK;
124 }
125
126 // Search through ALL known_hosts files for matching entry (append semantics)
127 bool found_entries = false;
128 for (size_t file_idx = 0; file_idx < known_hosts_files.count; file_idx++) {
129 const char *path = known_hosts_files.files[file_idx].path;
130
131 int fd = platform_open("known_hosts_file", path, PLATFORM_O_RDONLY, FILE_PERM_PRIVATE);
132 if (fd < 0) {
133 log_debug("KNOWN_HOSTS: Cannot open file: %s", path);
134 continue; // Skip files that can't be opened
135 }
136
137 FILE *f = platform_fdopen("known_hosts_stream", fd, "r");
138 if (!f) {
139 platform_close(fd);
140 log_debug("KNOWN_HOSTS: Failed to fdopen: %s", path);
141 continue;
142 }
143 defer(SAFE_FCLOSE(f));
144
145 char line[BUFFER_SIZE_XLARGE];
146
147 // Search this file for matching IP:port entries
148 while (fgets(line, sizeof(line), f)) {
149 if (line[0] == '#')
150 continue; // Comment
151
152 // Use regex to parse and extract known_hosts line components
153 char *parsed_ip_port = NULL, *parsed_key_type = NULL, *parsed_hex_key = NULL, *parsed_comment = NULL;
154 if (!crypto_regex_match_known_hosts(line, &parsed_ip_port, &parsed_key_type, &parsed_hex_key, &parsed_comment)) {
155 continue; // Line doesn't match known_hosts format
156 }
157 defer(SAFE_FREE(parsed_comment));
158 defer(SAFE_FREE(parsed_hex_key));
159 defer(SAFE_FREE(parsed_key_type));
160 defer(SAFE_FREE(parsed_ip_port));
161
162 // Check if IP:port matches what we're looking for (with IPv6 normalization)
163 if (!compare_ip_port_strings(parsed_ip_port, ip_with_port)) {
164 continue; // Different IP:port
165 }
166
167 found_entries = true;
168
169 if (strcmp(parsed_key_type, NO_IDENTITY_MARKER) == 0) {
170 // No-identity entry but server has identity - continue searching
171 log_debug("SECURITY_DEBUG: Found no-identity entry, but server has identity key");
172 continue;
173 }
174
175 // Parse identity key from hex string
176 if (!parsed_hex_key) {
177 // No hex key found - invalid entry
178 continue;
179 }
180
181 public_key_t stored_key;
182 if (parse_public_key(parsed_hex_key, &stored_key) != 0) {
183 continue; // Invalid key format
184 }
185
186 // Check if server key is all zeros (no-identity server)
187 bool server_key_is_zero = true;
188 for (int i = 0; i < ED25519_PUBLIC_KEY_SIZE; i++) {
189 if (server_key[i] != 0) {
190 server_key_is_zero = false;
191 break;
192 }
193 }
194
195 // Check if stored key is all zeros
196 bool stored_key_is_zero = true;
197 for (int i = 0; i < ED25519_PUBLIC_KEY_SIZE; i++) {
198 if (stored_key.key[i] != 0) {
199 stored_key_is_zero = false;
200 break;
201 }
202 }
203
204 if (expected_key && has_expected_key && !*has_expected_key && !stored_key_is_zero) {
205 memcpy(expected_key, stored_key.key, ED25519_PUBLIC_KEY_SIZE);
206 *has_expected_key = true;
207 }
208
209 // Both zero = no-identity connection (weaker security)
210 if (server_key_is_zero && stored_key_is_zero) {
211 NOTICE(WARNING, "UNVERIFIED SERVER IDENTITY", "SECURITY: Connecting to no-identity server at known IP:port");
212 return 1; // Match found
213 }
214
215 // Compare keys (constant-time)
216 if (sodium_memcmp(server_key, stored_key.key, ED25519_PUBLIC_KEY_SIZE) == 0) {
217 log_info("SECURITY: Server key matches known_hosts - connection verified");
218 return 1; // Match found!
219 }
220
221 // Key mismatch - continue searching after releasing this entry.
222 }
223 }
224
225 // Check if we found any entries at all
226 if (found_entries) {
227 // We found entries for this IP:port but none matched the server key
228 // This is a MITM warning!
229 log_error("SECURITY: Server key does NOT match any known_hosts entries!");
230 log_error("SECURITY: This indicates a possible man-in-the-middle attack!");
232 }
233
234 // No entries found for this IP:port - first connection
235 return ASCIICHAT_OK;
236}
237
238// Check known_hosts for servers without identity key (no-identity entries)
239// Returns: 1 = previously accepted known host (no-identity entry found),
240// ASCIICHAT_OK = unknown host (first connection),
241// ERROR_CRYPTO_VERIFICATION = server changed from identity to no-identity
243 const char *path = get_known_hosts_path();
244 int fd = platform_open("known_hosts_file", path, PLATFORM_O_RDONLY, FILE_PERM_PRIVATE);
245 if (fd < 0) {
246 // File doesn't exist - this is an unknown host that needs verification
247 log_warn("Known hosts file does not exist: %s", path);
248 return ASCIICHAT_OK; // Return 0 to indicate unknown host (first connection)
249 }
250
251 FILE *f = platform_fdopen("known_hosts_stream", fd, "r");
252 defer(SAFE_FCLOSE(f));
253 if (!f) {
254 // Failed to open file descriptor as FILE*
255 platform_close(fd);
256 log_warn("Failed to open known hosts file: %s", path);
257 return ASCIICHAT_OK; // Return 0 to indicate unknown host (first connection)
258 }
259
260 char line[BUFFER_SIZE_XLARGE];
261 char expected_prefix[BUFFER_SIZE_MEDIUM];
262
263 // Format IP:port with proper bracket notation for IPv6
264 char ip_with_port[BUFFER_SIZE_MEDIUM];
265 if (format_ip_with_port(server_ip, port, ip_with_port, sizeof(ip_with_port)) != ASCIICHAT_OK) {
266
267 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid IP format: %s", server_ip);
268 }
269
270 // Add space after IP:port for prefix matching
271 safe_snprintf(expected_prefix, sizeof(expected_prefix), "%s ", ip_with_port);
272
273 while (fgets(line, sizeof(line), f)) {
274 if (line[0] == '#')
275 continue; // Comment
276
277 // Use regex to parse and extract known_hosts line components
278 char *parsed_ip_port = NULL, *parsed_key_type = NULL, *parsed_hex_key = NULL, *parsed_comment = NULL;
279 if (!crypto_regex_match_known_hosts(line, &parsed_ip_port, &parsed_key_type, &parsed_hex_key, &parsed_comment)) {
280 continue; // Line doesn't match known_hosts format
281 }
282 defer(SAFE_FREE(parsed_comment));
283 defer(SAFE_FREE(parsed_hex_key));
284 defer(SAFE_FREE(parsed_key_type));
285 defer(SAFE_FREE(parsed_ip_port));
286
287 // Check if IP:port matches what we're looking for (with IPv6 normalization)
288 if (!compare_ip_port_strings(parsed_ip_port, ip_with_port)) {
289 continue; // Different IP:port
290 }
291
292 // Found matching IP:port - check key type
293 if (strcmp(parsed_key_type, "no-identity") == 0) {
294 // This is a server without identity key that was previously accepted by the user
295 // No warnings or user confirmation needed - user already accepted this server
296 return 1; // Known host (no-identity entry) - secure connection
297 }
298
299 // If we found a normal identity key entry, this is a mismatch
300 // Server previously had identity key but now has none
301 NOTICE(DANGER, "SERVER IDENTITY REMOVED", "Server previously had identity key but now has none - potential security issue");
302 return ERROR_CRYPTO_VERIFICATION; // Mismatch - server changed from identity to no-identity
303 }
304
305 return ASCIICHAT_OK; // Not found = first connection
306}
307
313static asciichat_error_t mkdir_recursive(const char *path) {
314 if (!path || !*path) {
315 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid path");
316 }
317
318 // Make a mutable copy of the path
319 size_t len = strlen(path);
320 char *tmp = SAFE_MALLOC(len + 1, char *);
321 defer(SAFE_FREE(tmp));
322 if (!tmp) {
323 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate memory for path");
324 }
325 memcpy(tmp, path, len + 1);
326
327 // Handle absolute paths (skip leading / or drive letter on Windows)
328 char *p = tmp;
329#ifdef _WIN32
330 // Skip drive letter (e.g., "C:")
331 if (len >= 2 && tmp[1] == ':') {
332 p += 2;
333 }
334#endif
335 // Skip leading separators (handle both / and \ on all platforms)
336 while (*p == '/' || *p == '\\') {
337 p++;
338 }
339
340 // Create directories one level at a time
341 for (; *p; p++) {
342 if (*p == '/' || *p == '\\') {
343 *p = '\0'; // Temporarily truncate
344
345 // Try to create this directory level using platform abstraction
346 asciichat_error_t mkdir_result = platform_mkdir(tmp, DIR_PERM_PRIVATE);
347 if (mkdir_result != ASCIICHAT_OK) {
348 return mkdir_result;
349 }
350
351 *p = PATH_DELIM; // Restore path separator (use platform-specific separator)
352 }
353 }
354
355 // Create the final directory using platform abstraction
356 asciichat_error_t mkdir_result = platform_mkdir(tmp, DIR_PERM_PRIVATE);
357 if (mkdir_result != ASCIICHAT_OK) {
358 return mkdir_result;
359 }
360
361 return ASCIICHAT_OK;
362}
363
364asciichat_error_t add_known_host(const char *server_ip, uint16_t port, const uint8_t server_key[ED25519_PUBLIC_KEY_SIZE]) {
365 // Validate parameters first
366 if (!server_ip || !server_key) {
367 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: server_ip=%p, server_key=%p", server_ip, server_key);
368 }
369
370 // Check for empty string (must be after NULL check)
371 size_t ip_len = strlen(server_ip);
372 if (ip_len == 0) {
373 return SET_ERRNO(ERROR_INVALID_PARAM, "Empty hostname/IP");
374 }
375
376 const char *path = get_known_hosts_path();
377 if (!path || path[0] == '\0') {
378 SET_ERRNO(ERROR_CONFIG, "Failed to get known hosts file path");
379 return ERROR_CONFIG;
380 }
381
382 // Create parent directories recursively (like mkdir -p)
383 size_t path_len = strlen(path);
384 if (path_len == 0) {
385 SET_ERRNO(ERROR_CONFIG, "Empty known hosts file path");
386 return ERROR_CONFIG;
387 }
388 char *dir = SAFE_MALLOC(path_len + 1, char *);
389 defer(SAFE_FREE(dir));
390 if (!dir) {
391 SET_ERRNO(ERROR_MEMORY, "Failed to allocate memory for directory path");
392 return ERROR_MEMORY;
393 }
394 memcpy(dir, path, path_len + 1);
395
396 // Find the last path separator
397 char *last_sep = strrchr(dir, PATH_DELIM);
398
399 if (last_sep) {
400 *last_sep = '\0'; // Truncate to get directory path
401 asciichat_error_t result = mkdir_recursive(dir);
402 if (result != ASCIICHAT_OK) {
403 return result; // Error already set by mkdir_recursive
404 }
405 }
406
407 // Create the file if it doesn't exist, then append to it
408 log_debug("KNOWN_HOSTS: Opening file for append: %s", path);
409 // Use "a" mode for append-only (simpler and works better with chmod)
410 FILE *f = platform_fopen("file_stream", path, "a");
411 defer(SAFE_FCLOSE(f));
412 if (!f) {
413 return SET_ERRNO_SYS(ERROR_CONFIG, "Failed to create/open known hosts file: %s", path);
414 }
415 // Set secure permissions (0600) - only owner can read/write
416 // Note: chmod may fail if file was just created by fopen, but that's okay
417 (void)platform_chmod(path, FILE_PERM_PRIVATE);
418
419 // Format IP:port with proper bracket notation for IPv6
420 char ip_with_port[BUFFER_SIZE_MEDIUM];
421 if (format_ip_with_port(server_ip, port, ip_with_port, sizeof(ip_with_port)) != ASCIICHAT_OK) {
422 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid IP format: %s", server_ip);
423 }
424
425 // Convert key to hex for storage
426 char hex[CRYPTO_HEX_KEY_SIZE_NULL] = {0}; // Initialize to zeros for safety
427 bool is_placeholder = true;
428 // Build hex string byte by byte to avoid buffer overflow issues
429 for (int i = 0; i < ED25519_PUBLIC_KEY_SIZE; i++) {
430 // Convert each byte to 2 hex digits directly
431 uint8_t byte = server_key[i];
432 hex[i * 2] = "0123456789abcdef"[byte >> 4]; // High nibble
433 hex[i * 2 + 1] = "0123456789abcdef"[byte & 0xf]; // Low nibble
434 if (byte != 0) {
435 is_placeholder = false;
436 }
437 }
438 hex[CRYPTO_HEX_KEY_SIZE] = '\0'; // Ensure null termination (64 hex digits + null terminator)
439
440 // Write to file and check for errors
441 int fprintf_result;
442 if (is_placeholder) {
443 // Server has no identity key - store as placeholder
444 fprintf_result = safe_fprintf(f, "%s %s 0000000000000000000000000000000000000000000000000000000000000000 %s\n", ip_with_port, NO_IDENTITY_MARKER, ASCII_CHAT_APP_NAME);
445 } else {
446 // Server has identity key - store normally
447 fprintf_result = safe_fprintf(f, "%s %s %s %s\n", ip_with_port, X25519_KEY_TYPE, hex, ASCII_CHAT_APP_NAME);
448 }
449
450 // Check if fprintf failed
451 if (fprintf_result < 0) {
452 NOTICE(DANGER, "TRUSTED HOST KEY COULD NOT BE SAVED", "Failed to write to known_hosts file: %s\nHost trust has not been persisted.", path);
453 return SET_ERRNO_SYS(ERROR_CONFIG, "CRITICAL SECURITY ERROR: Failed to write to known_hosts file: %s", path);
454 }
455
456 // Flush to ensure data is written
457 if (fflush(f) != 0) {
458 NOTICE(DANGER, "TRUSTED HOST KEY COULD NOT BE SAVED", "Failed to flush known_hosts file: %s\nHost trust has not been persisted.", path);
459 return SET_ERRNO_SYS(ERROR_CONFIG, "CRITICAL SECURITY ERROR: Failed to flush known_hosts file: %s", path);
460 }
461
462 log_debug("KNOWN_HOSTS: Successfully added host to known_hosts file: %s", path);
463
464 return ASCIICHAT_OK;
465}
466
467asciichat_error_t remove_known_host(const char *server_ip, uint16_t port) {
468 // Validate parameters first
469 if (!server_ip) {
470 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameter: server_ip=%p", server_ip);
471 }
472
473 const char *path = get_known_hosts_path();
474 int fd = platform_open("known_hosts_file", path, PLATFORM_O_RDONLY, FILE_PERM_PRIVATE);
475 if (fd < 0) {
476 // File doesn't exist - nothing to remove, return success
477 return ASCIICHAT_OK;
478 }
479 FILE *f = platform_fdopen("known_hosts_stream", fd, "r");
480 defer(SAFE_FCLOSE(f));
481 if (!f) {
482 platform_close(fd);
483 SET_ERRNO_SYS(ERROR_CONFIG, "Failed to open known hosts file: %s", path);
484 return ERROR_CONFIG;
485 }
486
487 // Format IP:port with proper bracket notation for IPv6
488 char ip_with_port[BUFFER_SIZE_MEDIUM];
489 if (format_ip_with_port(server_ip, port, ip_with_port, sizeof(ip_with_port)) != ASCIICHAT_OK) {
490
491 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid IP format: %s", server_ip);
492 }
493
494 // Read all lines into memory
495 char **lines = NULL;
496 size_t num_lines = 0;
497 defer({
498 if (lines) {
499 for (size_t i = 0; i < num_lines; i++) {
500 SAFE_FREE(lines[i]);
501 }
502 }
503 SAFE_FREE(lines);
504 });
505 char line[BUFFER_SIZE_XLARGE];
506
507 char expected_prefix[BUFFER_SIZE_MEDIUM];
508 safe_snprintf(expected_prefix, sizeof(expected_prefix), "%s ", ip_with_port);
509
510 while (fgets(line, sizeof(line), f)) {
511 // Skip lines that match this IP:port
512 if (strncmp(line, expected_prefix, strlen(expected_prefix)) != 0) {
513 // Keep this line
514 char **new_lines = SAFE_REALLOC((void *)lines, (num_lines + 1) * sizeof(char *), char **);
515 if (new_lines) {
516 lines = new_lines;
517 lines[num_lines] = platform_strdup(line);
518 if (lines[num_lines] == NULL) {
519 return SET_ERRNO(ERROR_MEMORY, "Failed to duplicate line from known_hosts file");
520 }
521 num_lines++;
522 }
523 }
524 }
525 // Close first file before opening for write
526 if (f) {
527 fclose(f);
528 f = NULL; // Prevent double-close by defer
529 }
530
531 // Write back the filtered lines
532 fd = platform_open("known_hosts_file_write", path, PLATFORM_O_WRONLY | PLATFORM_O_CREAT | PLATFORM_O_TRUNC, FILE_PERM_PRIVATE);
533 f = platform_fdopen("known_hosts_write_stream", fd, "w");
534 if (!f) {
535 // Cleanup on error - fdopen failed, so fd is still open but f is NULL
536 // Individual line strings will be freed by defer cleanup
537 platform_close(fd); // Close fd directly since fdopen failed
538 return SET_ERRNO_SYS(ERROR_CONFIG, "Failed to open known hosts file: %s", path);
539 }
540
541 for (size_t i = 0; i < num_lines; i++) {
542 (void)fputs(lines[i], f);
543 }
544 // All cleanup (lines, individual strings, file handle) handled by defer statements
545
546 log_debug("KNOWN_HOSTS: Successfully removed host from known_hosts file: %s", path);
547 return ASCIICHAT_OK;
548}
549
550// Compute SHA256 fingerprint of key for display
553 if (key_fingerprint_digest(key, hash) != ASCIICHAT_OK) {
554 fingerprint[0] = '\0';
555 return;
556 }
557
558 // Build hex string byte by byte to avoid buffer overflow issues
559 for (int i = 0; i < HMAC_SHA256_SIZE; i++) {
560 uint8_t byte = hash[i];
561 fingerprint[i * 2] = "0123456789abcdef"[byte >> 4]; // High nibble
562 fingerprint[i * 2 + 1] = "0123456789abcdef"[byte & 0xf]; // Low nibble
563 }
564 fingerprint[CRYPTO_HEX_KEY_SIZE] = '\0';
565}
566
567// Interactive prompt for unknown host - returns true if user wants to add, false to abort
568bool prompt_unknown_host(const char *server_ip, uint16_t port, const uint8_t server_key[ED25519_PUBLIC_KEY_SIZE]) {
569 char fingerprint[CRYPTO_HEX_KEY_SIZE_NULL];
570 compute_key_fingerprint(server_key, fingerprint);
571
572 // Format IP:port with proper bracket notation for IPv6
573 char ip_with_port[BUFFER_SIZE_MEDIUM];
574 if (format_ip_with_port(server_ip, port, ip_with_port, sizeof(ip_with_port)) != ASCIICHAT_OK) {
575 // Fallback to basic format if error
576 safe_snprintf(ip_with_port, sizeof(ip_with_port), "%s:%u", server_ip, port);
577 }
578
579 // Check if we're running interactively (stdin is a terminal and not in snapshot mode)
580 const char *env_skip_known_hosts_checking = platform_getenv("ASCII_CHAT_INSECURE_NO_HOST_IDENTITY_CHECK");
581 if (env_skip_known_hosts_checking && strcmp(env_skip_known_hosts_checking, STR_ONE) == 0) {
582 NOTICE(DANGER, "HOST VERIFICATION DISABLED", "Skipping known_hosts checking. This is a security vulnerability.");
583 return true;
584 }
585#ifndef NDEBUG
586 // In debug builds, also skip for Claude Code (LLM automation can't do interactive prompts)
587 const char *env_claudecode = platform_getenv("CLAUDECODE");
588 if (env_claudecode && strlen(env_claudecode) > 0) {
589 NOTICE(DANGER, "HOST VERIFICATION DISABLED", "Skipping known_hosts checking (CLAUDECODE set in debug build).");
590 return true;
591 }
592#endif
593 if (!terminal_can_prompt_user(!GET_OPTION(snapshot_mode))) {
594 // SECURITY: Non-interactive mode - REJECT unknown hosts to prevent MITM attacks
595 SET_ERRNO(ERROR_CRYPTO, "SECURITY: Cannot verify unknown host in non-interactive mode");
596 NOTICE(DANGER, "HOST VERIFICATION FAILED",
597 "ERROR: Cannot verify unknown host in non-interactive mode without environment variable bypass.\n"
598 "This connection may be a man-in-the-middle attack!\n"
599 "\n"
600 "To connect to this host:\n"
601 " 1. Run the client interactively (from a terminal with TTY)\n"
602 " 2. Verify the fingerprint: SHA256:%s\n"
603 " 3. Accept the host when prompted\n"
604 " 4. The host will be added to: %s\n"
605 "\n"
606 "Connection aborted for security.\n"
607 "To bypass this check, set the environment variable ASCII_CHAT_INSECURE_NO_HOST_IDENTITY_CHECK to 1",
608 fingerprint, get_known_hosts_path());
609 return false; // REJECT unknown hosts in non-interactive mode
610 }
611
612 public_key_t public_key = {.type = KEY_TYPE_ED25519};
613 memcpy(public_key.key, server_key, sizeof(public_key.key));
614 char identity[KEY_IDENTITY_BUFFER_SIZE] = "";
615 // Keep the trust question and input visible in a normal 24-row terminal.
616 if (platform_isatty(STDERR_FILENO) && ui_controller_size().rows < 38)
617 (void)key_identity_format(&public_key, false, false, 80, identity, sizeof(identity));
618 else
619 (void)key_identity_format_terminal(&public_key, identity, sizeof(identity));
620 char question[KEY_IDENTITY_BUFFER_SIZE + 512];
621 safe_snprintf(question, sizeof(question),
622 "REMOTE HOST IDENTIFICATION NOT KNOWN!\n\n"
623 "The authenticity of host '%s' cannot be established.\n"
624 "%s\n"
625 "Are you sure you want to continue connecting",
626 ip_with_port, identity);
627 if (ui_notice_confirm_kind(UI_PROMPT_TRUST_HOST, UI_NOTICE_DANGER, question, 120)) {
628 log_warn("Warning: Permanently added '%s' to the list of known hosts.", ip_with_port);
629 return true;
630 }
631
632 log_warn("Connection aborted by user.");
633 return false;
634}
635
636// Display MITM warning with key comparison and prompt user for confirmation
637// Returns true if user accepts the risk and wants to continue, false otherwise
638bool display_mitm_warning(const char *server_ip, uint16_t port, const uint8_t expected_key[ED25519_PUBLIC_KEY_SIZE], const uint8_t received_key[ED25519_PUBLIC_KEY_SIZE]) {
639 public_key_t public_key = {.type = KEY_TYPE_ED25519};
640 char expected_identity[KEY_IDENTITY_BUFFER_SIZE] = "No stored public identity available.\n";
641 char received_identity[KEY_IDENTITY_BUFFER_SIZE] = "";
642 if (expected_key) {
643 memcpy(public_key.key, expected_key, ED25519_PUBLIC_KEY_SIZE);
644 (void)key_identity_format_terminal(&public_key, expected_identity, sizeof(expected_identity));
645 }
646 memcpy(public_key.key, received_key, ED25519_PUBLIC_KEY_SIZE);
647 (void)key_identity_format_terminal(&public_key, received_identity, sizeof(received_identity));
648
649 const char *known_hosts_path = get_known_hosts_path();
650
651 // Format IP:port with proper bracket notation for IPv6
652 char ip_with_port[BUFFER_SIZE_MEDIUM];
653 if (format_ip_with_port(server_ip, port, ip_with_port, sizeof(ip_with_port)) != ASCIICHAT_OK) {
654 // Fallback to basic format if error
655 safe_snprintf(ip_with_port, sizeof(ip_with_port), "%s:%u", server_ip, port);
656 }
657
659 escape_ascii(ip_with_port, "[]", escaped_ip_with_port, 128);
660 NOTICE(DANGER, "REMOTE HOST IDENTIFICATION HAS CHANGED",
661 "\n"
662 "\n"
663 "IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!\n"
664 "Someone could be eavesdropping on you right now (man-in-the-middle attack)!\n"
665 "It is also possible that the host key has just been changed.\n"
666 "\n"
667 "The fingerprint for the Ed25519 key sent by the remote host is:\n"
668 "%s\n"
669 "\n"
670 "Stored identity (first candidate):\n"
671 "%s\n"
672 "\n"
673 "Please contact your system administrator.\n"
674 "\n"
675 "Add correct host key in %s to get rid of this message.\n"
676 "Offending key for IP address %s was found at:\n"
677 "%s\n"
678 "\n"
679 "To update the key, run:\n"
680 " # Linux/macOS:\n"
681 " sed -i '' '/%s /d' ~/.ascii-chat/known_hosts\n"
682 " # or run this instead:\n"
683 " cat ~/.ascii-chat/known_hosts | grep -v '%s ' > /tmp/x; cp /tmp/x ~/.ascii-chat/known_hosts\n"
684 " # Windows PowerShell:\n"
685 " (Get-Content ~/.ascii-chat/known_hosts) | Where-Object { $_ -notmatch '^%s ' } | Set-Content "
686 "~/.ascii-chat/known_hosts\n"
687 " # Or manually edit ~/.ascii-chat/known_hosts to remove lines starting with '%s '\n"
688 "\n"
689 "Host key verification failed.\n"
690 "\n",
691 received_identity, expected_identity, known_hosts_path, ip_with_port, known_hosts_path, ip_with_port, escaped_ip_with_port, ip_with_port, ip_with_port);
692
693 return false;
694}
695
706static bool is_localhost_address(const char *ip_string) {
707 if (!ip_string) {
708 return false;
709 }
710
711 // Use robust IP utility functions that properly validate
712 // IPv4: Checks entire 127.0.0.0/8 range with proper validation
713 // IPv6: Handles ::1, [::1], and expanded forms like 0:0:0:0:0:0:0:1
714 return is_localhost_ipv4(ip_string) || is_localhost_ipv6(ip_string);
715}
716
728static bool is_automated_mode(void) {
729 // Check for Claude Code automation
730 const char *claudecode = SAFE_GETENV("CLAUDECODE");
731 if (claudecode && strlen(claudecode) > 0) {
732 return true;
733 }
734
735 // Check for insecure bypass environment variable
736 const char *insecure_bypass = SAFE_GETENV("ASCII_CHAT_INSECURE_NO_HOST_IDENTITY_CHECK");
737 if (insecure_bypass && strcmp(insecure_bypass, "1") == 0) {
738 return true;
739 }
740
741 // Check if user prompts are possible (TTY + not snapshot + not automated)
742 if (!terminal_can_prompt_user(!GET_OPTION(snapshot_mode))) {
743 return true; // Skip interactive prompts in non-interactive environments
744 }
745
746 return false;
747}
748
749// Interactive prompt for unknown host without identity key
750// Returns true if user wants to continue, false to abort
751bool prompt_unknown_host_no_identity(const char *server_ip, uint16_t port) {
752 // Format IP:port with proper bracket notation for IPv6
753 char ip_with_port[BUFFER_SIZE_MEDIUM];
754 if (format_ip_with_port(server_ip, port, ip_with_port, sizeof(ip_with_port)) != ASCIICHAT_OK) {
755 // Fallback to basic format if error
756 safe_snprintf(ip_with_port, sizeof(ip_with_port), "%s:%u", server_ip, port);
757 }
758
759 // LOCALHOST OPTIMIZATION: Skip authentication prompt for localhost addresses
760 // Localhost is inherently trusted (same machine, no network exposure)
761 // This matches SSH behavior (ssh-keyscan doesn't prompt for localhost)
762 if (is_localhost_address(server_ip)) {
763 log_debug("SECURITY: Localhost address %s detected - skipping unknown host prompt (localhost is inherently trusted)", ip_with_port);
764 return true; // Silently trust localhost
765 }
766
767 // Check if running in automated/non-interactive environment
768 // In debug builds, Claude Code automation can't interact with prompts
769 if (is_automated_mode()) {
770 SET_ERRNO(ERROR_CRYPTO, "SECURITY: Cannot verify server without identity key in non-interactive/automated mode");
771 NOTICE(DANGER, "SERVER IDENTITY MISSING",
772 "ERROR: Cannot verify server without identity key in non-interactive/automated mode.\n"
773 "ERROR: This connection is vulnerable to man-in-the-middle attacks!\n"
774 "\n"
775 "To connect to this host:\n"
776 " 1. Run the client interactively (from a terminal with TTY)\n"
777 " 2. Verify you trust this server despite no identity key\n"
778 " 3. Accept the risk when prompted\n"
779 " OR better: Ask server admin to use --key for proper authentication\n"
780 "\n"
781 "Connection aborted for security.\n"
782 "\n");
783 return false;
784 }
785
787 safe_snprintf(question, sizeof(question),
788 "Host '%s' has no identity key.\n"
789 "This connection is vulnerable to man-in-the-middle attacks.\n"
790 "Anyone intercepting it could read your data.\n\n"
791 "Use --key on the server and --server-key on the client to verify identity.\n\n"
792 "Are you sure you want to continue connecting",
793 ip_with_port);
794 if (ui_notice_confirm_kind(UI_PROMPT_UNVERIFIED_HOST, UI_NOTICE_DANGER, question, 120)) {
795 NOTICE(DANGER, "UNVERIFIED CONNECTION",
796 "Warning: Proceeding with unverified connection.\n"
797 "Your data may be intercepted by attackers!\n"
798 "\n");
799 return true;
800 }
801
802 log_plain("Connection aborted by user.");
803 return false;
804}
805
806// Cleanup function to free the cached known_hosts path
808 if (g_known_hosts_path_cache) {
809 SAFE_FREE(g_known_hosts_path_cache);
810 g_known_hosts_path_cache = NULL;
811 }
812}
Synchronized per-thread pending error stacks and value snapshots. SET_ERRNO pushes,...
#define SET_ERRNO(code,...)
#define SET_ERRNO_SYS(code,...)
Dedicated worker for all pending errno stacks and handled history. Signal handlers may only request a...
int platform_find_config_file(const char *filename, config_file_list_t *list_out)
Definition filesystem.c:42
int platform_open(const char *name, const char *pathname, int flags,...)
Definition filesystem.c:65
int platform_close(int fd)
Definition filesystem.c:91
FILE * platform_fopen(const char *name, const char *filename, const char *mode)
Definition filesystem.c:18
void config_file_list_destroy(config_file_list_t *list)
Definition filesystem.c:52
#define BUFFER_SIZE_XLARGE
Extra large buffer size (2048 bytes).
#define BUFFER_SIZE_MEDIUM
Medium buffer size (512 bytes).
#define SAFE_REALLOC(ptr, size, cast)
unsigned short uint16_t
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
#define SAFE_GETENV(name)
unsigned char uint8_t
#define SAFE_FCLOSE(fp)
#define ASCII_CHAT_APP_NAME
Application name for key comments ("ascii-chat").
#define CRYPTO_HEX_KEY_SIZE
Hex string size for 32-byte key (64 hex characters).
const char * get_known_hosts_path(void)
Get the path to the known_hosts file.
Definition known_hosts.c:57
#define NO_IDENTITY_MARKER
No-identity entry marker ("no-identity").
bool prompt_unknown_host_no_identity(const char *server_ip, uint16_t port)
Interactive prompt for unknown host without identity key - returns true if user wants to continue,...
#define CRYPTO_HEX_KEY_SIZE_NULL
Hex string size for 32-byte key with null terminator (65 bytes).
asciichat_error_t check_known_host_no_identity(const char *server_ip, uint16_t port)
Check known_hosts for servers without identity key (no-identity entries).
void known_hosts_destroy(void)
Cleanup function to free cached known_hosts path.
#define X25519_KEY_TYPE
X25519 key type string ("x25519").
asciichat_error_t remove_known_host(const char *server_ip, uint16_t port)
Remove server from known_hosts.
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_CRYPTO_VERIFICATION
@ ERROR_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_CONFIG
Definition error_codes.h:56
@ ERROR_CRYPTO
Definition error_codes.h:97
@ ERROR_INVALID_PARAM
uint8_t key[CRYPTO_PUBLIC_KEY_SIZE]
Definition key_types.h:78
asciichat_error_t parse_public_key(const char *input, public_key_t *key_out)
Parse SSH/GPG public key from any format (returns first key only).
Definition keys.c:36
@ KEY_TYPE_ED25519
Definition key_types.h:58
#define log_warn(...)
Log a WARN message.
Definition log/log.h:615
#define log_error(...)
Log an ERROR message.
Definition log/log.h:628
#define log_info(...)
Log an INFO message.
Definition log/log.h:602
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:589
#define log_plain(...)
Plain logging - writes to both log file and stderr without timestamps or log levels.
Definition log/log.h:659
#define GET_OPTION(field)
Definition options.h:1333
#define STR_ONE
String literal: "1" (one).
asciichat_error_t format_ip_with_port(const char *ip, uint16_t port, char *output, size_t output_size)
Format IP address with port number.
Definition ip.c:175
int is_localhost_ipv6(const char *ip)
Check if IPv6 address is localhost.
Definition ip.c:1230
int is_localhost_ipv4(const char *ip)
Check if IPv4 address is localhost.
Definition ip.c:1209
char * get_config_dir(void)
Get configuration directory path with XDG_CONFIG_HOME support.
Definition path.c:279
void escape_ascii(const char *str, const char *escape_char, char *out_buffer, size_t out_buffer_size)
Escape ASCII characters in a string.
int compare_ip_port_strings(const char *ip_port1, const char *ip_port2)
Compare two "IP:port" strings with IPv6 normalization.
Definition ip.c:1043
⚙️ Common definitions, error codes, macros, and types shared throughout the application
🌍 IP Address Parsing and Formatting Utilities
asciichat_error_t key_fingerprint_digest(const uint8_t public_key[ED25519_PUBLIC_KEY_SIZE], uint8_t digest[KEYMASK_DIGEST_SIZE])
Definition keymask.c:11
bool prompt_unknown_host(const char *server_ip, uint16_t port, const uint8_t server_key[ED25519_PUBLIC_KEY_SIZE])
bool display_mitm_warning(const char *server_ip, uint16_t port, const uint8_t expected_key[ED25519_PUBLIC_KEY_SIZE], const uint8_t received_key[ED25519_PUBLIC_KEY_SIZE])
void compute_key_fingerprint(const uint8_t key[ED25519_PUBLIC_KEY_SIZE], char fingerprint[CRYPTO_HEX_KEY_SIZE_NULL])
#define CRYPTO_KNOWN_HOSTS_ESCAPED_IP_WITH_PORT_BUFFER_SIZE
Definition known_hosts.c:8
asciichat_error_t check_known_host_with_key(const char *server_ip, uint16_t port, const uint8_t server_key[ED25519_PUBLIC_KEY_SIZE], uint8_t expected_key[ED25519_PUBLIC_KEY_SIZE], bool *has_expected_key)
Definition known_hosts.c:90
#define CRYPTO_KNOWN_HOSTS_QUESTION_BUFFER_SIZE
Definition known_hosts.c:9
asciichat_error_t add_known_host(const char *server_ip, uint16_t port, const uint8_t server_key[ED25519_PUBLIC_KEY_SIZE])
asciichat_error_t check_known_host(const char *server_ip, uint16_t port, const uint8_t server_key[ED25519_PUBLIC_KEY_SIZE])
Definition known_hosts.c:86
Known hosts management for MITM attack prevention.
asciichat_error_t key_identity_format_terminal(const public_key_t *key, char *out, size_t size)
asciichat_error_t key_identity_format(const public_key_t *key, bool art, bool unicode, int cols, char *out, size_t size)
bool ui_notice_confirm_kind(ui_prompt_kind_t kind, ui_notice_severity_t severity, const char *text, unsigned timeout_seconds)
Definition notice.c:479
#define NOTICE(severity, title,...)
Definition notice.h:56
@ UI_NOTICE_DANGER
Definition notice.h:13
⚙️ Unified options parsing system for ascii-chat with builder pattern and lock-free access
📂 Path Manipulation Utilities
bool crypto_regex_match_known_hosts(const char *line, char **ip_port_out, char **key_type_out, char **hex_key_out, char **comment_out)
Definition regex.c:132
PCRE2-based regex patterns for cryptographic parsing.
#define HMAC_SHA256_SIZE
HMAC-SHA256 output size in bytes.
Definition sizes.h:47
#define ED25519_PUBLIC_KEY_SIZE
Ed25519 public key size in bytes.
Definition sizes.h:37
char * platform_strdup(const char *s)
bool terminal_can_prompt_user(bool user_setting)
🔤 String Manipulation and Shell Escaping Utilities
The normalized public identity used by ascii-chat's crypto and key-management code.
Definition key_types.h:76
const char * platform_getenv(const char *name)
Definition system.c:45
terminal_size_t ui_controller_size(void)
int platform_isatty(int fd)
Definition util.c:70