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 File Reference

📜 SSH known_hosts file parser for host key verification and trust management More...

Go to the source code of this file.

Macros

#define CRYPTO_KNOWN_HOSTS_ESCAPED_IP_WITH_PORT_BUFFER_SIZE   128
#define CRYPTO_KNOWN_HOSTS_QUESTION_BUFFER_SIZE   2048

Functions

asciichat_error_t check_known_host (const char *server_ip, uint16_t port, const uint8_t server_key[ED25519_PUBLIC_KEY_SIZE])
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)
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).
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 remove_known_host (const char *server_ip, uint16_t port)
 Remove server from known_hosts.
void compute_key_fingerprint (const uint8_t key[ED25519_PUBLIC_KEY_SIZE], char fingerprint[CRYPTO_HEX_KEY_SIZE_NULL])
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])
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, false to abort.
void known_hosts_destroy (void)
 Cleanup function to free cached known_hosts path.
Known Hosts Management
const char * get_known_hosts_path (void)
 Get the path to the known_hosts file.

Detailed Description

📜 SSH known_hosts file parser for host key verification and trust management

Definition in file known_hosts.c.

Macro Definition Documentation

◆ CRYPTO_KNOWN_HOSTS_ESCAPED_IP_WITH_PORT_BUFFER_SIZE

#define CRYPTO_KNOWN_HOSTS_ESCAPED_IP_WITH_PORT_BUFFER_SIZE   128

Definition at line 8 of file known_hosts.c.

Referenced by display_mitm_warning().

◆ CRYPTO_KNOWN_HOSTS_QUESTION_BUFFER_SIZE

#define CRYPTO_KNOWN_HOSTS_QUESTION_BUFFER_SIZE   2048

Definition at line 9 of file known_hosts.c.

Referenced by prompt_unknown_host_no_identity().

Function Documentation

◆ add_known_host()

asciichat_error_t add_known_host ( const char * server_ip,
uint16_t port,
const uint8_t server_key[ED25519_PUBLIC_KEY_SIZE] )

Definition at line 364 of file known_hosts.c.

364 {
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}
#define SET_ERRNO(code,...)
#define SET_ERRNO_SYS(code,...)
FILE * platform_fopen(const char *name, const char *filename, const char *mode)
Definition filesystem.c:18
#define BUFFER_SIZE_MEDIUM
Medium buffer size (512 bytes).
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
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").
#define CRYPTO_HEX_KEY_SIZE_NULL
Hex string size for 32-byte key with null terminator (65 bytes).
#define X25519_KEY_TYPE
X25519 key type string ("x25519").
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_CONFIG
Definition error_codes.h:56
@ ERROR_INVALID_PARAM
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:589
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
#define NOTICE(severity, title,...)
Definition notice.h:56
#define ED25519_PUBLIC_KEY_SIZE
Ed25519 public key size in bytes.
Definition sizes.h:37

References ASCII_CHAT_APP_NAME, ASCIICHAT_OK, BUFFER_SIZE_MEDIUM, CRYPTO_HEX_KEY_SIZE, CRYPTO_HEX_KEY_SIZE_NULL, ED25519_PUBLIC_KEY_SIZE, ERROR_CONFIG, ERROR_INVALID_PARAM, ERROR_MEMORY, format_ip_with_port(), get_known_hosts_path(), log_debug, NO_IDENTITY_MARKER, NOTICE, platform_fopen(), SAFE_FCLOSE, SAFE_FREE, SAFE_MALLOC, SET_ERRNO, SET_ERRNO_SYS, and X25519_KEY_TYPE.

Referenced by crypto_handshake_client_key_exchange().

◆ check_known_host()

asciichat_error_t check_known_host ( const char * server_ip,
uint16_t port,
const uint8_t server_key[ED25519_PUBLIC_KEY_SIZE] )

Definition at line 86 of file known_hosts.c.

86 {
87 return check_known_host_with_key(server_ip, port, server_key, NULL, NULL);
88}
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

References check_known_host_with_key(), and ED25519_PUBLIC_KEY_SIZE.

◆ check_known_host_with_key()

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 at line 90 of file known_hosts.c.

91 {
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}
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
void config_file_list_destroy(config_file_list_t *list)
Definition filesystem.c:52
#define BUFFER_SIZE_XLARGE
Extra large buffer size (2048 bytes).
@ ERROR_CRYPTO_VERIFICATION
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
#define log_error(...)
Log an ERROR message.
Definition log/log.h:628
#define log_info(...)
Log an INFO message.
Definition log/log.h:602
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
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
The normalized public identity used by ascii-chat's crypto and key-management code.
Definition key_types.h:76

References ASCIICHAT_OK, BUFFER_SIZE_MEDIUM, BUFFER_SIZE_XLARGE, compare_ip_port_strings(), config_file_list_destroy(), crypto_regex_match_known_hosts(), ED25519_PUBLIC_KEY_SIZE, ERROR_CRYPTO_VERIFICATION, ERROR_INVALID_PARAM, format_ip_with_port(), public_key_t::key, log_debug, log_error, log_info, NO_IDENTITY_MARKER, NOTICE, parse_public_key(), platform_close(), platform_find_config_file(), platform_open(), SAFE_FCLOSE, SAFE_FREE, and SET_ERRNO.

Referenced by check_known_host(), and crypto_handshake_client_key_exchange().

◆ compute_key_fingerprint()

void compute_key_fingerprint ( const uint8_t key[ED25519_PUBLIC_KEY_SIZE],
char fingerprint[CRYPTO_HEX_KEY_SIZE_NULL] )

Definition at line 551 of file known_hosts.c.

551 {
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}
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
#define HMAC_SHA256_SIZE
HMAC-SHA256 output size in bytes.
Definition sizes.h:47

References ASCIICHAT_OK, CRYPTO_HEX_KEY_SIZE, CRYPTO_HEX_KEY_SIZE_NULL, ED25519_PUBLIC_KEY_SIZE, HMAC_SHA256_SIZE, and key_fingerprint_digest().

Referenced by discovery_keys_verify_change(), and prompt_unknown_host().

◆ display_mitm_warning()

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] )

Definition at line 638 of file known_hosts.c.

638 {
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}
@ KEY_TYPE_ED25519
Definition key_types.h:58
void escape_ascii(const char *str, const char *escape_char, char *out_buffer, size_t out_buffer_size)
Escape ASCII characters in a string.
#define CRYPTO_KNOWN_HOSTS_ESCAPED_IP_WITH_PORT_BUFFER_SIZE
Definition known_hosts.c:8
asciichat_error_t key_identity_format_terminal(const public_key_t *key, char *out, size_t size)

References ASCIICHAT_OK, BUFFER_SIZE_MEDIUM, CRYPTO_KNOWN_HOSTS_ESCAPED_IP_WITH_PORT_BUFFER_SIZE, ED25519_PUBLIC_KEY_SIZE, escape_ascii(), format_ip_with_port(), get_known_hosts_path(), public_key_t::key, KEY_IDENTITY_BUFFER_SIZE, key_identity_format_terminal(), KEY_TYPE_ED25519, and NOTICE.

Referenced by crypto_handshake_client_key_exchange().

◆ prompt_unknown_host()

bool prompt_unknown_host ( const char * server_ip,
uint16_t port,
const uint8_t server_key[ED25519_PUBLIC_KEY_SIZE] )

Definition at line 568 of file known_hosts.c.

568 {
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}
@ ERROR_CRYPTO
Definition error_codes.h:97
#define log_warn(...)
Log a WARN message.
Definition log/log.h:615
#define GET_OPTION(field)
Definition options.h:1333
#define STR_ONE
String literal: "1" (one).
void compute_key_fingerprint(const uint8_t key[ED25519_PUBLIC_KEY_SIZE], char fingerprint[CRYPTO_HEX_KEY_SIZE_NULL])
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
@ UI_NOTICE_DANGER
Definition notice.h:13
bool terminal_can_prompt_user(bool user_setting)
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

References ASCIICHAT_OK, BUFFER_SIZE_MEDIUM, compute_key_fingerprint(), CRYPTO_HEX_KEY_SIZE_NULL, ED25519_PUBLIC_KEY_SIZE, ERROR_CRYPTO, format_ip_with_port(), get_known_hosts_path(), GET_OPTION, public_key_t::key, KEY_IDENTITY_BUFFER_SIZE, key_identity_format(), key_identity_format_terminal(), KEY_TYPE_ED25519, log_warn, NOTICE, platform_getenv(), platform_isatty(), SET_ERRNO, STR_ONE, terminal_can_prompt_user(), ui_controller_size(), ui_notice_confirm_kind(), and UI_NOTICE_DANGER.

Referenced by crypto_handshake_client_key_exchange().