ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
discovery_keys.c
Go to the documentation of this file.
1
9
10/* Storage capacities in elements; text buffers include the terminating NUL. */
11#define CRYPTO_DISCOVERY_KEYS_BASE64_KEY_BUFFER_SIZE 128
12#define CRYPTO_DISCOVERY_KEYS_NEW_FINGERPRINT_BUFFER_SIZE 65
13#define CRYPTO_DISCOVERY_KEYS_QUESTION_BUFFER_SIZE 2048
14
15/* Existing buffer budgets in bytes, including NUL for text storage. */
16#define SSH_ED25519_WIRE_KEY_SIZE (sizeof(uint32_t) + 11 + sizeof(uint32_t) + ED25519_PUBLIC_KEY_SIZE)
17
20
23
25#include <ascii-chat/common.h>
27#include <ascii-chat/log/log.h>
28#include <libplatform/filesystem.h>
29#include <libplatform/question.h>
30#include <libplatform/system.h>
32#include <ascii-chat/util/url.h>
33
34#include <ctype.h>
35#include <errno.h>
36#include <sodium.h>
37#include <stdio.h>
38#include <stdlib.h>
39#include <string.h>
40#include <sys/stat.h>
41#include <sys/types.h>
42
43// ============================================================================
44// Helper Functions
45// ============================================================================
46
59static bool is_official_server(const char *acds_server) {
60 if (!acds_server) {
61 return false;
62 }
63
64 // Case-insensitive comparison
65 char server_lower[BUFFER_SIZE_SMALL];
66 SAFE_STRNCPY(server_lower, acds_server, sizeof(server_lower));
67 for (char *p = server_lower; *p; p++) {
68 *p = (char)tolower((unsigned char)*p);
69 }
70
71 // Check official production server
72 if (strcmp(server_lower, ACDS_OFFICIAL_SERVER) == 0) {
73 return true;
74 }
75
76 // In debug builds, also trust localhost for testing (IPv4 and IPv6)
77#ifndef NDEBUG
78 if (strcmp(server_lower, "localhost") == 0 || strcmp(server_lower, "127.0.0.1") == 0 || strcmp(server_lower, "::1") == 0) {
79 return true;
80 }
81#endif
82
83 return false;
84}
85
86// ============================================================================
87// HTTPS Download and Key Loading
88// ============================================================================
89
91 if (!url || !pubkey_out) {
92 return SET_ERRNO(ERROR_INVALID_PARAM, "NULL parameter");
93 }
94
95 log_debug("Downloading ACDS key from %s", url);
96
97 // Use existing parse_public_key infrastructure which handles HTTPS URLs
98 public_key_t key;
99 asciichat_error_t result = parse_public_key(url, &key);
100 if (result != ASCIICHAT_OK) {
101 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to download and parse ACDS key from %s", url);
102 }
103
104 memcpy(pubkey_out, key.key, ED25519_PUBLIC_KEY_SIZE);
105 log_debug("Successfully downloaded and parsed ACDS key from %s", url);
106 return ASCIICHAT_OK;
107}
108
110 if (!file_path || !pubkey_out) {
111 return SET_ERRNO(ERROR_INVALID_PARAM, "NULL parameter");
112 }
113
114 log_debug("Loading ACDS key from file: %s", file_path);
115
116 // Use existing parse_public_key infrastructure which handles file paths
117 public_key_t key;
119 if (result != ASCIICHAT_OK) {
120 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to load ACDS key from file: %s", file_path);
121 }
122
123 memcpy(pubkey_out, key.key, ED25519_PUBLIC_KEY_SIZE);
124 log_debug("Successfully loaded ACDS key from file: %s", file_path);
125 return ASCIICHAT_OK;
126}
127
128// ============================================================================
129// Key Caching
130// ============================================================================
131
132asciichat_error_t discovery_keys_get_cache_path(const char *acds_server, char *path_out, size_t path_size) {
133 if (!acds_server || !path_out || path_size == 0) {
134 return SET_ERRNO(ERROR_INVALID_PARAM, "NULL parameter");
135 }
136
137 char *config_dir = get_config_dir();
138 if (!config_dir) {
139 return SET_ERRNO(ERROR_CONFIG, "Failed to get config directory");
140 }
141
142 // Path: ~/.config/ascii-chat/acds_keys/<hostname>/key.pub
143 safe_snprintf(path_out, path_size, "%s" ACDS_KEYS_CACHE_DIR PATH_SEPARATOR_STR "%s" PATH_SEPARATOR_STR "key.pub", config_dir, acds_server);
144 SAFE_FREE(config_dir);
145
146 return ASCIICHAT_OK;
147}
148
150 if (!acds_server || !pubkey_out) {
151 return SET_ERRNO(ERROR_INVALID_PARAM, "NULL parameter");
152 }
153
154 char cache_path[PLATFORM_MAX_PATH_LENGTH];
155 asciichat_error_t result = discovery_keys_get_cache_path(acds_server, cache_path, sizeof(cache_path));
156 if (result != ASCIICHAT_OK) {
157 return result;
158 }
159
160 // Check if cached key exists
161 if (!platform_is_regular_file(cache_path)) {
162 return SET_ERRNO(ERROR_FILE_NOT_FOUND, "No cached key for ACDS server: %s", acds_server);
163 }
164
165 // Load cached key using existing infrastructure
166 return discovery_keys_load_file(cache_path, pubkey_out);
167}
168
170 if (!acds_server || !pubkey) {
171 return SET_ERRNO(ERROR_INVALID_PARAM, "NULL parameter");
172 }
173
174 char cache_path[PLATFORM_MAX_PATH_LENGTH];
175 asciichat_error_t result = discovery_keys_get_cache_path(acds_server, cache_path, sizeof(cache_path));
176 if (result != ASCIICHAT_OK) {
177 return result;
178 }
179
180 // Create cache directory if it doesn't exist
181 char dir_path[PLATFORM_MAX_PATH_LENGTH];
182 safe_snprintf(dir_path, sizeof(dir_path), "%s", cache_path);
183
184 // Find the last path separator (handle both / and \ for cross-platform compatibility)
185 char *last_sep = strrchr(dir_path, '\\');
186 if (!last_sep) {
187 last_sep = strrchr(dir_path, '/');
188 }
189
190 if (last_sep) {
191 *last_sep = '\0';
192 if (!platform_is_directory(dir_path)) {
193 result = platform_mkdir_recursive(dir_path, 0700);
194 if (result != ASCIICHAT_OK) {
195 return SET_ERRNO(ERROR_FILE_OPERATION, "Failed to create ACDS key cache directory: %s", dir_path);
196 }
197 }
198 }
199
200 // Save key in OpenSSH public key format
201 FILE *f = platform_fopen("file_stream", cache_path, "w");
202 if (!f) {
203 return SET_ERRNO_SYS(ERROR_FILE_OPERATION, "Failed to create cache file: %s", cache_path);
204 }
205
206 // OpenSSH encodes a length-prefixed algorithm name followed by the key string.
207 uint8_t wire_key[SSH_ED25519_WIRE_KEY_SIZE] = {0, 0, 0, 11, 's', 's', 'h', '-', 'e', 'd', '2', '5', '5', '1', '9', 0, 0, 0, 32};
208 memcpy(wire_key + 19, pubkey, ED25519_PUBLIC_KEY_SIZE);
210 sodium_bin2base64(base64_key, sizeof(base64_key), wire_key, sizeof(wire_key), sodium_base64_VARIANT_ORIGINAL);
211
212 fprintf(f, "ssh-ed25519 %s acds-cached-key\n", base64_key);
213 fclose(f);
214
215 log_debug("Cached ACDS key for server: %s", acds_server);
216 return ASCIICHAT_OK;
217}
218
220 if (!acds_server) {
221 return SET_ERRNO(ERROR_INVALID_PARAM, "NULL parameter");
222 }
223
224 char cache_path[PLATFORM_MAX_PATH_LENGTH];
225 asciichat_error_t result = discovery_keys_get_cache_path(acds_server, cache_path, sizeof(cache_path));
226 if (result != ASCIICHAT_OK) {
227 return result;
228 }
229
230 if (platform_is_regular_file(cache_path)) {
231 if (remove(cache_path) != 0) {
232 return SET_ERRNO_SYS(ERROR_FILE_OPERATION, "Failed to delete cached key: %s", cache_path);
233 }
234 log_debug("Cleared cached ACDS key for server: %s", acds_server);
235 }
236
237 return ASCIICHAT_OK;
238}
239
240// ============================================================================
241// User Verification for Key Changes
242// ============================================================================
243
245 if (!acds_server || !old_pubkey || !new_pubkey) {
246 return SET_ERRNO(ERROR_INVALID_PARAM, "NULL parameter");
247 }
248
249 char old_fingerprint[HEX_STRING_SIZE_32], new_fingerprint[CRYPTO_DISCOVERY_KEYS_NEW_FINGERPRINT_BUFFER_SIZE];
250 compute_key_fingerprint(old_pubkey, old_fingerprint);
251 compute_key_fingerprint(new_pubkey, new_fingerprint);
252
253 // Ask user to confirm
255 safe_snprintf(question, sizeof(question),
256 "ACDS SERVER KEY HAS CHANGED\nServer: %s\n\nOld SHA256: %s\nNew SHA256: %s\n\n"
257 "This may indicate key rotation or a man-in-the-middle attack.\n"
258 "Verify the new fingerprint with the operator before accepting.\n\nAccept new ACDS server key",
259 acds_server, old_fingerprint, new_fingerprint);
260 bool accepted = ui_notice_confirm_kind(UI_PROMPT_DISCOVERY_KEY_CHANGE, UI_NOTICE_DANGER, question, 120);
261 if (!accepted) {
262 return SET_ERRNO(ERROR_CRYPTO_VERIFICATION, "User rejected ACDS key change for: %s", acds_server);
263 }
264
265 log_info("User accepted ACDS key change for: %s", acds_server);
266 return ASCIICHAT_OK;
267}
268
269// ============================================================================
270// Main Verification Function
271// ============================================================================
272
273asciichat_error_t discovery_keys_verify(const char *acds_server, const char *key_spec, uint8_t pubkey_out[ED25519_PUBLIC_KEY_SIZE]) {
274 if (!acds_server || !pubkey_out) {
275 return SET_ERRNO(ERROR_INVALID_PARAM, "NULL parameter");
276 }
277
279 asciichat_error_t result;
280 bool is_official = is_official_server(acds_server);
281
282 // ===========================================================================
283 // Step 1: Obtain the public key
284 // ===========================================================================
285
286 if (!key_spec && is_official) {
287 // Automatic trust for official server: try SSH key first, then GPG
288 log_info("Attempting automatic HTTPS key trust for official ACDS server");
289
290 public_key_t key;
292 if (result != ASCIICHAT_OK) {
293 log_debug("SSH key download failed, trying GPG key");
295 }
296
297 if (result != ASCIICHAT_OK) {
298 return SET_ERRNO(ERROR_NETWORK, "Failed to download key from official ACDS server");
299 }
300
301 memcpy(new_pubkey, key.key, ED25519_PUBLIC_KEY_SIZE);
302
303 } else if (!key_spec) {
304 // No key_spec and not official server = error
306 "Third-party ACDS servers require explicit --discovery-service-key configuration."
307 "Only %s has automatic trust.",
309
310 } else {
311 // Use parse_public_key for all other cases (handles HTTPS, files, github:, gitlab:, etc.)
312 public_key_t key;
313 result = parse_public_key(key_spec, &key);
314 if (result != ASCIICHAT_OK) {
315 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to load/download ACDS key from: %s", key_spec);
316 }
317
318 memcpy(new_pubkey, key.key, ED25519_PUBLIC_KEY_SIZE);
319 }
320
321 // ===========================================================================
322 // Step 2: Check cache and handle key changes
323 // ===========================================================================
324
325 uint8_t cached_pubkey[ED25519_PUBLIC_KEY_SIZE];
326 result = discovery_keys_load_cached(acds_server, cached_pubkey);
327
328 if (result == ASCIICHAT_OK) {
329 // Cached key exists - compare
330 if (memcmp(cached_pubkey, new_pubkey, ED25519_PUBLIC_KEY_SIZE) != 0) {
331 // Key changed - require user verification
332 result = discovery_keys_verify_change(acds_server, cached_pubkey, new_pubkey);
333 if (result != ASCIICHAT_OK) {
334 return result; // User rejected or error
335 }
336
337 // User accepted - update cache
338 result = discovery_keys_save_cached(acds_server, new_pubkey);
339 if (result != ASCIICHAT_OK) {
340 log_warn("Failed to update cached key, continuing anyway");
341 }
342 } else {
343 log_debug("ACDS key matches cached key for: %s", acds_server);
344 }
345
346 } else {
347 // No cached key - save it for next time
348 log_info("First connection to ACDS server: %s, caching key", acds_server);
349 result = discovery_keys_save_cached(acds_server, new_pubkey);
350 if (result != ASCIICHAT_OK) {
351 log_warn("Failed to cache key, continuing anyway");
352 }
353 }
354
355 // ===========================================================================
356 // Step 3: Return verified key
357 // ===========================================================================
358
359 memcpy(pubkey_out, new_pubkey, ED25519_PUBLIC_KEY_SIZE);
360 log_debug("ACDS key verification successful for: %s", acds_server);
361 return ASCIICHAT_OK;
362}
Synchronized per-thread pending error stacks and value snapshots. SET_ERRNO pushes,...
#define SET_ERRNO(code,...)
#define SET_ERRNO_SYS(code,...)
#define CRYPTO_DISCOVERY_KEYS_BASE64_KEY_BUFFER_SIZE
asciichat_error_t discovery_keys_clear_cache(const char *acds_server)
Clear cached key for ACDS server.
#define CRYPTO_DISCOVERY_KEYS_QUESTION_BUFFER_SIZE
asciichat_error_t discovery_keys_load_cached(const char *acds_server, uint8_t pubkey_out[32])
Check if cached key exists and load it.
asciichat_error_t discovery_keys_verify(const char *acds_server, const char *key_spec, uint8_t pubkey_out[32])
Verify and load ACDS server public key.
asciichat_error_t discovery_keys_download_https(const char *url, uint8_t pubkey_out[32])
Download key from HTTPS URL.
asciichat_error_t discovery_keys_verify_change(const char *acds_server, const uint8_t old_pubkey[32], const uint8_t new_pubkey[32])
Verify key change with user.
asciichat_error_t discovery_keys_save_cached(const char *acds_server, const uint8_t pubkey[32])
Save key to cache.
asciichat_error_t discovery_keys_load_file(const char *file_path, uint8_t pubkey_out[32])
Load key from local file.
asciichat_error_t discovery_keys_get_cache_path(const char *acds_server, char *path_out, size_t path_size)
Get cached key path for ACDS server.
#define CRYPTO_DISCOVERY_KEYS_NEW_FINGERPRINT_BUFFER_SIZE
#define SSH_ED25519_WIRE_KEY_SIZE
Discovery Server Public Key Trust Management.
#define ACDS_OFFICIAL_SERVER
Official ACDS server hostname (automatic HTTPS key trust).
#define ACDS_OFFICIAL_KEY_SSH_URL
Default HTTPS URLs for official ACDS keys.
#define ACDS_KEYS_CACHE_DIR
Key cache directory (relative to config dir).
#define ACDS_OFFICIAL_KEY_GPG_URL
Dedicated worker for all pending errno stacks and handled history. Signal handlers may only request a...
int platform_mkdir_recursive(const char *path, int mode)
Definition filesystem.c:36
FILE * platform_fopen(const char *name, const char *filename, const char *mode)
Definition filesystem.c:18
#define BUFFER_SIZE_SMALL
Small buffer size (256 bytes).
#define SAFE_STRNCPY(dst, src, size)
#define SAFE_FREE(ptr)
#define PLATFORM_MAX_PATH_LENGTH
unsigned char uint8_t
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_CRYPTO_KEY
Definition error_codes.h:98
@ ERROR_FILE_NOT_FOUND
@ ERROR_NETWORK
Definition error_codes.h:76
@ ERROR_CRYPTO_VERIFICATION
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_CONFIG
Definition error_codes.h:56
@ ERROR_FILE_OPERATION
@ 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
#define log_warn(...)
Log a WARN message.
Definition log/log.h:615
#define log_info(...)
Log an INFO message.
Definition log/log.h:602
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:589
char * get_config_dir(void)
Get configuration directory path with XDG_CONFIG_HOME support.
Definition path.c:279
⚙️ Common definitions, error codes, macros, and types shared throughout the application
void compute_key_fingerprint(const uint8_t key[ED25519_PUBLIC_KEY_SIZE], char fingerprint[CRYPTO_HEX_KEY_SIZE_NULL])
Known hosts management for MITM attack prevention.
📝 Logging API with multiple log levels and terminal output control
char file_path[PLATFORM_MAX_PATH_LENGTH]
Definition mmap.c:42
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
📂 Path Manipulation Utilities
#define ED25519_PUBLIC_KEY_SIZE
Ed25519 public key size in bytes.
Definition sizes.h:37
#define HEX_STRING_SIZE_32
Hex string size for 32-byte values (64 hex chars + null terminator).
Definition sizes.h:158
🔤 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
🌐 Production-Grade URL Validation and Parsing
int platform_is_regular_file(const char *path)
Definition util.c:136