ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
ssh_keys.c
Go to the documentation of this file.
1
6
7/* Storage capacities in elements; text buffers include the terminating NUL. */
8#define CRYPTO_SSH_SSH_KEYS_CIPHERNAME_BUFFER_SIZE 32
9#define CRYPTO_SSH_SSH_KEYS_KDFNAME_BUFFER_SIZE 32
10
11/* Existing buffer budgets in bytes, including NUL for text storage. */
12#define SSH_PASSWORD_INPUT_BUFFER_SIZE 1024
13
14/* Existing buffer budgets in bytes, including NUL for text storage. */
15#define SSH_BCRYPT_SALT_SIZE 16
16
17#include <recast/defer.h>
20
21#include <ascii-chat/crypto/crypto.h> // Includes <sodium.h>
23#include <libplatform/filesystem.h>
25#include <ascii-chat/common.h>
32#include <ascii-chat/crypto/gpg/gpg.h> // For GPG agent signing support
33#include <ascii-chat-deps/bearssl/inc/bearssl.h>
34#include <ascii-chat-deps/libsodium-bcrypt-pbkdf/include/sodium_bcrypt_pbkdf.h>
35#include <string.h>
36#include <stdio.h>
37#include <stdlib.h>
38#include <time.h>
39
40#ifndef _WIN32
41#include <sys/wait.h>
42#include <unistd.h>
43#endif
44#include <sys/stat.h>
45
46// =============================================================================
47// Helper Functions
48// =============================================================================
49
50// Forward declarations
51static asciichat_error_t base64_decode_ssh_key(const char *base64, size_t base64_len, uint8_t **blob_out, size_t *blob_len);
52#ifndef EMSCRIPTEN_BUILD
53static asciichat_error_t decrypt_openssh_private_key(const uint8_t *encrypted_blob, size_t blob_len, const char *passphrase, const uint8_t *salt, size_t salt_len, uint32_t rounds,
54 const char *cipher_name, uint8_t **decrypted_out, size_t *decrypted_len);
55
73static asciichat_error_t decrypt_openssh_private_key(const uint8_t *encrypted_blob, size_t blob_len, const char *passphrase, const uint8_t *salt, size_t salt_len, uint32_t rounds,
74 const char *cipher_name, uint8_t **decrypted_out, size_t *decrypted_len) {
75 // OpenSSH uses: key_len + iv_len derived from bcrypt_pbkdf
76 // For AES-256: key=32 bytes, iv=16 bytes = 48 bytes total
77 const size_t key_size = 32;
78 const size_t iv_size = 16;
79 const size_t derived_size = key_size + iv_size;
80
81 SAFE_MALLOC_DEFER_FREE(derived, derived_size, uint8_t *);
82 if (!derived) {
83 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate memory for key derivation");
84 }
85 defer(sodium_memzero(derived, derived_size));
86
87 // Use libsodium-bcrypt-pbkdf (OpenBSD implementation)
88 if (sodium_bcrypt_pbkdf(passphrase, strlen(passphrase), salt, salt_len, derived, derived_size, rounds) != 0) {
89 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to derive decryption key with sodium_bcrypt_pbkdf");
90 }
91
92 const uint8_t *key = derived;
93 const uint8_t *derived_iv = derived + key_size;
94
95 // Decrypt using BearSSL
96 SAFE_MALLOC_DEFER_FREE(decrypted, blob_len, uint8_t *);
97 if (!decrypted) {
98 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate memory for decryption");
99 }
100
101 if (strcmp(cipher_name, "aes256-ctr") == 0) {
102 // AES-256-CTR decryption using BearSSL
103 // OpenSSH derives a full 16-byte IV from bcrypt_pbkdf
104 // BearSSL expects: 12-byte nonce + 4-byte counter (big-endian uint32)
105 // We split the 16-byte IV: first 12 bytes as nonce, last 4 bytes as initial counter
106 br_aes_ct_ctr_keys aes_ctx;
107 br_aes_ct_ctr_init(&aes_ctx, key, key_size);
108
109 // Extract initial counter value from bytes 12-15 of derived IV (big-endian)
110 uint32_t initial_counter = ((uint32_t)derived_iv[12] << 24) | ((uint32_t)derived_iv[13] << 16) | ((uint32_t)derived_iv[14] << 8) | ((uint32_t)derived_iv[15]);
111
112 // Decrypt in-place
113 memcpy(decrypted, encrypted_blob, blob_len);
114 br_aes_ct_ctr_run(&aes_ctx, derived_iv, initial_counter, decrypted, blob_len);
115 } else if (strcmp(cipher_name, "aes256-cbc") == 0) {
116 // AES-256-CBC decryption using BearSSL
117 br_aes_ct_cbcdec_keys aes_ctx;
118 br_aes_ct_cbcdec_init(&aes_ctx, key, key_size);
119
120 // Copy IV to working buffer
121 uint8_t working_iv[AES_IV_SIZE];
122 memcpy(working_iv, derived_iv, sizeof(working_iv));
123
124 // Decrypt in-place
125 memcpy(decrypted, encrypted_blob, blob_len);
126 br_aes_ct_cbcdec_run(&aes_ctx, working_iv, decrypted, blob_len);
127 } else {
128 return SET_ERRNO(ERROR_CRYPTO_KEY, "Unsupported cipher: %s", cipher_name);
129 }
130
131 *decrypted_out = decrypted;
132 decrypted = NULL;
133 *decrypted_len = blob_len;
134
135 return ASCIICHAT_OK;
136}
137#endif
138
139// Base64 decode SSH key blob
140static asciichat_error_t base64_decode_ssh_key(const char *base64, size_t base64_len, uint8_t **blob_out, size_t *blob_len) {
141 if (!base64 || !blob_out || !blob_len) {
142 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters for base64 decode");
143 }
144
145 // Allocate max possible size
146 *blob_out = SAFE_MALLOC(base64_len, uint8_t *);
147
148 const char *end;
149 int result = sodium_base642bin(*blob_out, base64_len, base64, base64_len,
150 NULL, // ignore chars
151 blob_len, &end, sodium_base64_VARIANT_ORIGINAL);
152
153 if (result != 0) {
154 SAFE_FREE(*blob_out);
155 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to decode base64 SSH key data");
156 }
157
158 return ASCIICHAT_OK;
159}
160
161// =============================================================================
162// SSH Key Parsing Implementation
163// =============================================================================
164
166 if (!line || !ed25519_pk) {
167 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: line=%p, ed25519_pk=%p", line, ed25519_pk);
168 }
169
170 // Use regex to parse and extract SSH public key components
171 char *base64_key = NULL, *comment = NULL;
172 if (!crypto_regex_match_public_key(line, &base64_key, &comment)) {
173 return SET_ERRNO(ERROR_CRYPTO_KEY, "SSH key line does not match expected format");
174 }
175
176 defer(SAFE_FREE(base64_key));
177 defer(SAFE_FREE(comment));
178
179 // Base64 decode
180 uint8_t *blob;
181 size_t blob_len;
182 if (base64_decode_ssh_key(base64_key, strlen(base64_key), &blob, &blob_len) != 0) {
183 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to decode SSH key base64 data");
184 }
185
186 defer(SAFE_FREE(blob));
187
188 // Parse SSH key blob structure:
189 // [4 bytes: length of "ssh-ed25519"]
190 // [11 bytes: "ssh-ed25519"]
191 // [4 bytes: length of public key (32)]
192 // [32 bytes: Ed25519 public key]
193
194 if (blob_len < SSH_KEY_HEADER_SIZE) {
195 return SET_ERRNO(ERROR_CRYPTO_KEY, "SSH key blob too small: %zu bytes (expected at least %d)", blob_len, SSH_KEY_HEADER_SIZE);
196 }
197
198 // Extract Ed25519 public key (last 32 bytes)
199 memcpy(ed25519_pk, blob + blob_len - ED25519_PUBLIC_KEY_SIZE, ED25519_PUBLIC_KEY_SIZE);
200
201 return ASCIICHAT_OK;
202}
203
230
231static void ssh_private_key_clear_password(ssh_private_key_parse_t *state) {
232 if (state->password) {
233 sodium_memzero(state->password, strlen(state->password));
234 SAFE_FREE(state->password);
235 }
236}
237
238static void ssh_private_key_cleanup(ssh_private_key_parse_t *state) {
239 ssh_private_key_clear_password(state);
240 if (state->decrypted_blob) {
241 sodium_memzero(state->decrypted_blob, state->decrypted_blob_len);
243 }
244 SAFE_FREE(state->key_blob);
245 SAFE_FREE(state->file_content);
246}
247
248#ifndef EMSCRIPTEN_BUILD
249static bool ssh_private_key_from_agent(const char *key_path, private_key_t *key_out) {
250 // First, check if we can get the key from ssh-agent (password-free)
251 // This requires reading the public key from the .pub file
252 char pub_key_path[BUFFER_SIZE_LARGE];
253 safe_snprintf(pub_key_path, sizeof(pub_key_path), "%s.pub", key_path);
254
255 FILE *pub_f = platform_fopen("file_stream", pub_key_path, "r");
256 if (pub_f) {
257 defer(SAFE_FCLOSE(pub_f));
258 char pub_line[BUFFER_SIZE_LARGE];
259 if (fgets(pub_line, sizeof(pub_line), pub_f)) {
260 public_key_t pub_key = {0};
261 pub_key.type = KEY_TYPE_ED25519;
262
263 if (parse_ssh_ed25519_line(pub_line, pub_key.key) == ASCIICHAT_OK) {
264 // Check if this key is in ssh-agent
265 if (ssh_agent_has_key(&pub_key)) {
266 log_dev("Key found in ssh-agent - using cached key (no password required)");
267 // Key is in agent, we can use it
268 memset(key_out, 0, sizeof(*key_out));
269 key_out->type = KEY_TYPE_ED25519;
270 key_out->use_ssh_agent = true;
271 memcpy(key_out->key.ed25519 + 32, pub_key.key, CRYPTO_PUBLIC_KEY_SIZE); // Copy public key to second half
272 memcpy(key_out->public_key, pub_key.key, ED25519_PUBLIC_KEY_SIZE); // Also store in public_key field
273 // Note: We don't have the private key seed, but ssh-agent will sign for us
274 return true;
275 } else {
276 log_debug("Key not found in ssh-agent - will decrypt from file");
277 }
278 }
279 }
280 }
281 return false;
282}
283
284#endif
285
286static asciichat_error_t ssh_private_key_read_file(ssh_private_key_parse_t *state, const char *key_path) {
287 // Validate the SSH key file first
288 asciichat_error_t validation_result = validate_ssh_key_file(key_path);
289 if (validation_result != ASCIICHAT_OK) {
290 return validation_result;
291 }
292
293 // Read the private key file
294 FILE *f = platform_fopen("file_stream", key_path, "r");
295 if (!f) {
296 return SET_ERRNO(ERROR_CRYPTO_KEY, "Cannot read private key file: %s", key_path);
297 }
298
299 defer(SAFE_FCLOSE(f));
300
301 // Read the entire file
302 state->file_content = NULL;
303 size_t file_size = 0;
304 char buffer[BUFFER_SIZE_XXLARGE];
305 size_t bytes_read;
306
307 while ((bytes_read = fread(buffer, 1, sizeof(buffer), f)) > 0) {
308 state->file_content = SAFE_REALLOC(state->file_content, file_size + bytes_read + 1, char *);
309 if (!state->file_content) {
310 return SET_ERRNO(ERROR_CRYPTO_KEY, "Out of memory reading private key file");
311 }
312 memcpy(state->file_content + file_size, buffer, bytes_read);
313 file_size += bytes_read;
314 }
315
316 if (file_size == 0) {
317 ssh_private_key_cleanup(state);
318 return SET_ERRNO(ERROR_CRYPTO_KEY, "Private key file is empty: %s", key_path);
319 }
320
321 state->file_content[file_size] = '\0';
322 return ASCIICHAT_OK;
323}
324
325static asciichat_error_t ssh_private_key_decode_pem(ssh_private_key_parse_t *state, const char *key_path) {
326 // Use regex to extract base64 data from OpenSSH PEM format
327 char *pem_base64_data = NULL;
328 if (!crypto_regex_extract_pem_base64(state->file_content, &pem_base64_data)) {
329 ssh_private_key_cleanup(state);
330 return SET_ERRNO(ERROR_CRYPTO_KEY, "Invalid OpenSSH private key format: %s", key_path);
331 }
332
333 // Remove any whitespace/newlines from the base64 data
334 char *clean_base64 = SAFE_MALLOC(strlen(pem_base64_data) + 1, char *);
335 char *clean_ptr = clean_base64;
336 for (const char *p = pem_base64_data; *p; p++) {
337 if (*p != '\n' && *p != '\r' && *p != ' ' && *p != '\t') {
338 *clean_ptr++ = *p;
339 }
340 }
341 *clean_ptr = '\0';
342 SAFE_FREE(pem_base64_data);
343
344 // Decode the base64 data
345
346 asciichat_error_t decode_result = base64_decode_ssh_key(clean_base64, strlen(clean_base64), &state->key_blob, &state->key_blob_len);
347 SAFE_FREE(clean_base64);
348
349 if (decode_result != ASCIICHAT_OK) {
350 ssh_private_key_cleanup(state);
351 return decode_result;
352 }
353 return ASCIICHAT_OK;
354}
355
356static asciichat_error_t ssh_private_key_read_header(ssh_private_key_parse_t *state, const char *key_path) {
357 // Parse the OpenSSH private key structure
358 // Format: [4 bytes: magic] [4 bytes: ciphername length] [ciphername] [4 bytes: kdfname length] [kdfname]
359 // [4 bytes: kdfoptions length] [kdfoptions] [4 bytes: num keys] [4 bytes: pubkey length] [pubkey]
360 // [4 bytes: privkey length] [privkey]
361
362 if (state->key_blob_len < 15) {
363 ssh_private_key_cleanup(state);
364 return SET_ERRNO(ERROR_CRYPTO_KEY, "OpenSSH private key blob too small: %s", key_path);
365 }
366
367 // Check magic number (should be "openssh-key-v1\0")
368 if (memcmp(state->key_blob, "openssh-key-v1\0", 15) != 0) {
369 ssh_private_key_cleanup(state);
370 return SET_ERRNO(ERROR_CRYPTO_KEY, "Invalid OpenSSH private key magic: %s", key_path);
371 }
372
373 state->offset = 15; // Skip magic
374
375 // Read ciphername
376 if (state->offset + 4 > state->key_blob_len) {
377 ssh_private_key_cleanup(state);
378 return SET_ERRNO(ERROR_CRYPTO_KEY, "OpenSSH private key truncated at ciphername: %s", key_path);
379 }
380
381 state->ciphername_len = read_u32_be(&state->key_blob[state->offset]);
382 state->offset += 4;
383
384 if (state->offset + state->ciphername_len > state->key_blob_len) {
385 ssh_private_key_cleanup(state);
386 return SET_ERRNO(ERROR_CRYPTO_KEY, "OpenSSH private key truncated at ciphername data: %s", key_path);
387 }
388
389 // Store the position of ciphername for later use
390 state->ciphername_pos = state->offset;
391
392 // Check if key is encrypted
393 state->is_encrypted = !(state->ciphername_len == 4 && memcmp(state->key_blob + state->offset, "none", 4) == 0);
394
395 state->offset += state->ciphername_len;
396
397 // Skip kdfname and kdfoptions (we don't support encryption)
398 if (state->offset + 4 > state->key_blob_len) {
399 ssh_private_key_cleanup(state);
400 return SET_ERRNO(ERROR_CRYPTO_KEY, "OpenSSH private key truncated at kdfname: %s", key_path);
401 }
402
403 state->kdfname_len = read_u32_be(&state->key_blob[state->offset]);
404 state->offset += 4;
405
406 // Store the position of kdfname for later use
407 state->kdfname_pos = state->offset;
408
409 if (state->kdfname_len > state->key_blob_len - state->offset) {
410 ssh_private_key_cleanup(state);
411 return SET_ERRNO(ERROR_CRYPTO_KEY, "OpenSSH private key truncated at kdfname data: %s", key_path);
412 }
413
414 state->offset += state->kdfname_len;
415
416 if (state->offset + 4 > state->key_blob_len) {
417 ssh_private_key_cleanup(state);
418 return SET_ERRNO(ERROR_CRYPTO_KEY, "OpenSSH private key truncated at kdfoptions: %s", key_path);
419 }
420
421 state->kdfoptions_len = read_u32_be(&state->key_blob[state->offset]);
422 state->offset += 4;
423 if (state->kdfoptions_len > state->key_blob_len - state->offset) {
424 ssh_private_key_cleanup(state);
425 return SET_ERRNO(ERROR_CRYPTO_KEY, "OpenSSH private key truncated at kdfoptions data: %s", key_path);
426 }
427 state->offset += state->kdfoptions_len;
428 return ASCIICHAT_OK;
429}
430
431#ifndef EMSCRIPTEN_BUILD
432static asciichat_error_t ssh_private_key_read_encryption(ssh_private_key_parse_t *state, const char *key_path) {
433 // Parse the cipher name from the stored position
434
435 if (state->ciphername_len > 0 && state->ciphername_len < sizeof(state->ciphername)) {
436 memcpy(state->ciphername, state->key_blob + state->ciphername_pos, state->ciphername_len);
437 }
438
439 // Parse the KDF name from the stored position
440 char kdfname[CRYPTO_SSH_SSH_KEYS_KDFNAME_BUFFER_SIZE] = {0};
441 if (state->kdfname_len > 0 && state->kdfname_len < sizeof(kdfname)) {
442 memcpy(kdfname, state->key_blob + state->kdfname_pos, state->kdfname_len);
443 }
444
445 log_debug("Cipher: %s, KDF: %s", state->ciphername, kdfname);
446
447 // Check if we support this encryption method
448 if (strcmp(state->ciphername, "aes256-ctr") != 0 && strcmp(state->ciphername, "aes256-cbc") != 0) {
449 ssh_private_key_cleanup(state);
451 "Unsupported cipher '%s' for encrypted SSH key: %s\n"
452 "Supported ciphers: aes256-ctr, aes256-cbc",
453 state->ciphername, key_path);
454 }
455
456 if (strcmp(kdfname, "bcrypt") != 0) {
457 ssh_private_key_cleanup(state);
459 "Unsupported KDF '%s' for encrypted SSH key: %s\n"
460 "Only bcrypt KDF is supported",
461 kdfname, key_path);
462 }
463
464 // Parse KDF options (bcrypt salt and rounds)
465 if (state->kdfoptions_len < 8) {
466 ssh_private_key_cleanup(state);
467 return SET_ERRNO(ERROR_CRYPTO_KEY, "Invalid KDF options length: %s", key_path);
468 }
469
470 // Parse KDF options: [salt_length:4][salt:N][rounds:4]
471 size_t kdf_opt_offset = state->offset - state->kdfoptions_len;
472
473 // Read salt length
474 if (kdf_opt_offset + 4 > state->key_blob_len) {
475 ssh_private_key_cleanup(state);
476 return SET_ERRNO(ERROR_CRYPTO_KEY, "KDF options truncated at salt length: %s", key_path);
477 }
478 state->salt_len = read_u32_be(&state->key_blob[kdf_opt_offset]);
479 kdf_opt_offset += 4;
480
481 // Read salt
482 if (state->salt_len != 16) {
483 ssh_private_key_cleanup(state);
484 return SET_ERRNO(ERROR_CRYPTO_KEY, "Unexpected bcrypt salt length %u (expected 16): %s", state->salt_len, key_path);
485 }
486 if (kdf_opt_offset + state->salt_len > state->key_blob_len) {
487 ssh_private_key_cleanup(state);
488 return SET_ERRNO(ERROR_CRYPTO_KEY, "KDF options truncated at salt data: %s", key_path);
489 }
490
491 memcpy(state->bcrypt_salt, state->key_blob + kdf_opt_offset, state->salt_len);
492 kdf_opt_offset += state->salt_len;
493
494 // Read rounds
495 if (kdf_opt_offset + 4 > state->key_blob_len) {
496 ssh_private_key_cleanup(state);
497 return SET_ERRNO(ERROR_CRYPTO_KEY, "KDF options truncated at rounds: %s", key_path);
498 }
499 state->bcrypt_rounds = read_u32_be(&state->key_blob[kdf_opt_offset]);
500 return ASCIICHAT_OK;
501}
502
503static asciichat_error_t ssh_private_key_read_password(ssh_private_key_parse_t *state, const char *key_path) {
504 // Check for password in environment variable first
505 const char *env_password = platform_getenv("ASCII_CHAT_KEY_PASSWORD");
506 state->password = NULL;
507 if (env_password && strlen(env_password) > 0) {
508 // Use password from environment variable
509 state->password = platform_strdup(env_password);
510 if (!state->password) {
511 ssh_private_key_cleanup(state);
512 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate memory for password");
513 }
514 } else {
515 // Prompt for password interactively - allocate buffer for input
517 if (!state->password) {
518 ssh_private_key_cleanup(state);
519 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate memory for password");
520 }
521 if (prompt_password_simple_kind("Encrypted SSH key - enter passphrase", state->password, SSH_PASSWORD_INPUT_BUFFER_SIZE, UI_PROMPT_SSH_PASSPHRASE) != 0) {
522 ssh_private_key_cleanup(state);
523 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to read passphrase for encrypted key: %s", key_path);
524 }
525 }
526 return ASCIICHAT_OK;
527}
528
529static asciichat_error_t ssh_private_key_decrypt(ssh_private_key_parse_t *state, const char *key_path) {
530 // Native OpenSSH key decryption using bcrypt_pbkdf + BearSSL AES
531
532 // Skip past the unencrypted public key section to get to encrypted private keys
533 // Format: [num_keys:4][pubkey_len:4][pubkey:N]...[encrypted_len:4][encrypted:N]
534
535 // Read num_keys
536 if (state->offset + 4 > state->key_blob_len) {
537 ssh_private_key_cleanup(state);
538 return SET_ERRNO(ERROR_CRYPTO_KEY, "Encrypted key truncated at num_keys: %s", key_path);
539 }
540 uint32_t num_keys = read_u32_be(&state->key_blob[state->offset]);
541 state->offset += 4;
542 log_debug("num_keys=%u", num_keys);
543
544 // Skip all public keys
545 for (uint32_t i = 0; i < num_keys; i++) {
546 if (state->offset + 4 > state->key_blob_len) {
547 ssh_private_key_cleanup(state);
548 return SET_ERRNO(ERROR_CRYPTO_KEY, "Encrypted key truncated at pubkey %u length: %s", i, key_path);
549 }
550 uint32_t pubkey_len = read_u32_be(&state->key_blob[state->offset]);
551 state->offset += 4;
552 log_debug("Skipping public key %u: %u bytes", i, pubkey_len);
553
554 if (state->offset + pubkey_len > state->key_blob_len) {
555 ssh_private_key_cleanup(state);
556 return SET_ERRNO(ERROR_CRYPTO_KEY, "Encrypted key truncated at pubkey %u data: %s", i, key_path);
557 }
558 state->offset += pubkey_len;
559 }
560
561 // Read encrypted private keys length
562 if (state->offset + 4 > state->key_blob_len) {
563 ssh_private_key_cleanup(state);
564 return SET_ERRNO(ERROR_CRYPTO_KEY, "Encrypted key truncated at encrypted_len: %s", key_path);
565 }
566 uint32_t encrypted_len = read_u32_be(&state->key_blob[state->offset]);
567 state->offset += 4;
568
569 // Now offset points to the actual encrypted data
570 size_t encrypted_data_start = state->offset;
571 size_t encrypted_data_len = encrypted_len;
572
573 if (encrypted_data_len > state->key_blob_len - encrypted_data_start) {
574 ssh_private_key_cleanup(state);
575 return SET_ERRNO(ERROR_CRYPTO_KEY, "Encrypted private key data truncated: %s", key_path);
576 }
577
578 if (encrypted_data_len < 16) {
579 ssh_private_key_cleanup(state);
580 return SET_ERRNO(ERROR_CRYPTO_KEY, "Encrypted data too small: %s", key_path);
581 }
582
583 // Extract encrypted blob (includes everything from offset onwards)
584 const uint8_t *encrypted_blob = state->key_blob + encrypted_data_start;
585
586 // Call native decryption function
587 state->decrypted_blob = NULL;
588 state->decrypted_blob_len = 0;
589
590 // Note: decrypt_openssh_private_key derives IV from bcrypt_pbkdf, not from encrypted data
591 asciichat_error_t decrypt_result = decrypt_openssh_private_key(encrypted_blob, encrypted_data_len, state->password, state->bcrypt_salt, state->salt_len, state->bcrypt_rounds, state->ciphername,
592 &state->decrypted_blob, &state->decrypted_blob_len);
593
594 // Clean up password immediately after use
595 ssh_private_key_clear_password(state);
596
597 if (decrypt_result != ASCIICHAT_OK) {
598 ssh_private_key_cleanup(state);
599 return decrypt_result;
600 }
601 return ASCIICHAT_OK;
602}
603
604static asciichat_error_t ssh_private_key_read_decrypted_type(ssh_private_key_parse_t *state, const char *key_path) {
605 // Parse the decrypted private key structure
606 // OpenSSH format (decrypted):
607 // [checkint1:4][checkint2:4][keytype:string][pubkey:string][privkey:string][comment:string][padding:N]
608
609 if (state->decrypted_blob_len < 8) {
610 ssh_private_key_cleanup(state);
611 return SET_ERRNO(ERROR_CRYPTO_KEY, "Decrypted data too small (no checkints): %s", key_path);
612 }
613
614 // Verify checkints (first 8 bytes should be two identical 32-bit values)
615 uint32_t checkint1 = read_u32_be(&state->decrypted_blob[0]);
616 uint32_t checkint2 = read_u32_be(&state->decrypted_blob[4]);
617 if (checkint1 != checkint2) {
618 ssh_private_key_cleanup(state);
620 "Incorrect passphrase or corrupted key (checkint mismatch): %s\n"
621 "Expected matching checkints, got 0x%08x != 0x%08x",
622 key_path, checkint1, checkint2);
623 }
624
625 // Parse the decrypted private key structure manually
626 // Format after checkints: [keytype:string][pubkey:string][privkey:string][comment:string][padding:N]
627 state->dec_offset = 8; // Skip checkints
628
629 // Read keytype length
630 if (state->dec_offset + 4 > state->decrypted_blob_len) {
631 ssh_private_key_cleanup(state);
632 return SET_ERRNO(ERROR_CRYPTO_KEY, "Decrypted key truncated at keytype length: %s", key_path);
633 }
634 uint32_t keytype_len = read_u32_be(&state->decrypted_blob[state->dec_offset]);
635 state->dec_offset += 4;
636
637 // Read keytype
638 if (state->dec_offset + keytype_len > state->decrypted_blob_len) {
639 ssh_private_key_cleanup(state);
640 return SET_ERRNO(ERROR_CRYPTO_KEY, "Decrypted key truncated at keytype data: %s", key_path);
641 }
642 char keytype[BUFFER_SIZE_SMALL / 4] = {0}; // SSH key type strings are short
643 if (keytype_len > 0 && keytype_len < sizeof(keytype)) {
644 memcpy(keytype, state->decrypted_blob + state->dec_offset, keytype_len);
645 }
646 state->dec_offset += keytype_len;
647
648 // Check if it's Ed25519
649 if (strcmp(keytype, "ssh-ed25519") != 0) {
650 ssh_private_key_cleanup(state);
651 return SET_ERRNO(ERROR_CRYPTO_KEY, "Unsupported key type after decryption: '%s'", keytype);
652 }
653 return ASCIICHAT_OK;
654}
655
656static asciichat_error_t ssh_private_key_read_decrypted_material(ssh_private_key_parse_t *state, const char *key_path, private_key_t *key_out) {
657 // Read public key length
658 if (state->dec_offset + 4 > state->decrypted_blob_len) {
659 ssh_private_key_cleanup(state);
660 return SET_ERRNO(ERROR_CRYPTO_KEY, "Decrypted key truncated at pubkey length: %s", key_path);
661 }
662 uint32_t pubkey_data_len = read_u32_be(&state->decrypted_blob[state->dec_offset]);
663 state->dec_offset += 4;
664
665 // Read public key (32 bytes for Ed25519)
666 if (pubkey_data_len != 32) {
667 ssh_private_key_cleanup(state);
668 return SET_ERRNO(ERROR_CRYPTO_KEY, "Invalid Ed25519 public key length: %u (expected 32)", pubkey_data_len);
669 }
670 if (state->dec_offset + pubkey_data_len > state->decrypted_blob_len) {
671 ssh_private_key_cleanup(state);
672 return SET_ERRNO(ERROR_CRYPTO_KEY, "Decrypted key truncated at pubkey data: %s", key_path);
673 }
675 memcpy(ed25519_pk, state->decrypted_blob + state->dec_offset, ED25519_PUBLIC_KEY_SIZE);
676 state->dec_offset += 32;
677
678 // Read private key length
679 if (state->dec_offset + 4 > state->decrypted_blob_len) {
680 ssh_private_key_cleanup(state);
681 return SET_ERRNO(ERROR_CRYPTO_KEY, "Decrypted key truncated at privkey length: %s", key_path);
682 }
683 uint32_t privkey_data_len = read_u32_be(&state->decrypted_blob[state->dec_offset]);
684 state->dec_offset += 4;
685
686 // Read private key (64 bytes for Ed25519: 32-byte seed + 32-byte public key)
687 if (privkey_data_len != 64) {
688 ssh_private_key_cleanup(state);
689 return SET_ERRNO(ERROR_CRYPTO_KEY, "Invalid Ed25519 private key length: %u (expected 64)", privkey_data_len);
690 }
691 if (state->dec_offset + privkey_data_len > state->decrypted_blob_len) {
692 ssh_private_key_cleanup(state);
693 return SET_ERRNO(ERROR_CRYPTO_KEY, "Decrypted key truncated at privkey data: %s", key_path);
694 }
696 memcpy(ed25519_sk, state->decrypted_blob + state->dec_offset, ED25519_PRIVATE_KEY_SIZE);
697 state->dec_offset += 64;
698
699 // Populate key_out (ed25519_sk contains: 32-byte seed + 32-byte public key)
700 memset(key_out, 0, sizeof(*key_out));
701 key_out->type = KEY_TYPE_ED25519;
702 memcpy(key_out->key.ed25519, ed25519_sk, ED25519_SEED_SIZE); // Seed (first 32 bytes)
703 memcpy(key_out->key.ed25519 + 32, ed25519_sk + 32, ED25519_SEED_SIZE); // Public key (next 32 bytes)
704 memcpy(key_out->public_key, ed25519_pk, sizeof(ed25519_pk));
705 SAFE_STRNCPY(key_out->key_comment, "ssh-ed25519", sizeof(key_out->key_comment) - 1);
706 sodium_memzero(ed25519_sk, sizeof(ed25519_sk));
707
708 // Clean up decrypted data (sensitive!)
709 ssh_private_key_cleanup(state);
710
711 log_debug("Successfully parsed decrypted Ed25519 key");
712 return ASCIICHAT_OK;
713}
714
715static void ssh_private_key_cache_in_agent(const char *key_path, const private_key_t *key_out) {
716 // Attempt to add the decrypted key to ssh-agent for future password-free use
717 log_debug("Attempting to add decrypted key to ssh-agent");
718 asciichat_error_t agent_result = ssh_agent_add_key(key_out, key_path);
719 if (agent_result == ASCIICHAT_OK) {
720 log_debug("Successfully added key to ssh-agent - password will not be required on next run");
721 } else {
722 // Non-fatal: key is already decrypted and loaded, just won't be cached in agent
723 log_warn("Failed to add key to ssh-agent (non-fatal): %s", asciichat_error_format(NULL, agent_result));
724 log_warn("You can manually add it with: ssh-add %s", key_path);
725 }
726}
727
728static asciichat_error_t ssh_private_key_parse_encrypted(ssh_private_key_parse_t *state, const char *key_path, private_key_t *key_out) {
729 asciichat_error_t result = ssh_private_key_read_encryption(state, key_path);
730 if (result != ASCIICHAT_OK)
731 return result;
732 result = ssh_private_key_read_password(state, key_path);
733 if (result != ASCIICHAT_OK)
734 return result;
735 result = ssh_private_key_decrypt(state, key_path);
736 if (result != ASCIICHAT_OK)
737 return result;
738 result = ssh_private_key_read_decrypted_type(state, key_path);
739 if (result != ASCIICHAT_OK)
740 return result;
741 result = ssh_private_key_read_decrypted_material(state, key_path, key_out);
742 if (result != ASCIICHAT_OK)
743 return result;
744 ssh_private_key_cache_in_agent(key_path, key_out);
745 return ASCIICHAT_OK;
746}
747#endif
748
749static asciichat_error_t ssh_private_key_read_public(ssh_private_key_parse_t *state, const char *key_path) {
750 // Read number of keys
751 if (state->offset + 4 > state->key_blob_len) {
752 ssh_private_key_cleanup(state);
753 return SET_ERRNO(ERROR_CRYPTO_KEY, "OpenSSH private key truncated at num keys: %s", key_path);
754 }
755
756 uint32_t num_keys = read_u32_be(&state->key_blob[state->offset]);
757 state->offset += 4;
758
759 log_debug("num_keys=%u, offset=%zu, key_blob_len=%zu", num_keys, state->offset, state->key_blob_len);
760 log_debug("Raw bytes at offset %zu: %02x %02x %02x %02x", state->offset, state->key_blob[state->offset], state->key_blob[state->offset + 1], state->key_blob[state->offset + 2],
761 state->key_blob[state->offset + 3]);
762 log_debug("After num_keys, offset=%zu", state->offset);
763
764 if (num_keys != 1) {
765 ssh_private_key_cleanup(state);
766 return SET_ERRNO(ERROR_CRYPTO_KEY, "OpenSSH private key contains %u keys (expected 1): %s", num_keys, key_path);
767 }
768
769 // Read public key
770 if (state->offset + 4 > state->key_blob_len) {
771 ssh_private_key_cleanup(state);
772 return SET_ERRNO(ERROR_CRYPTO_KEY, "OpenSSH private key truncated at pubkey length: %s", key_path);
773 }
774
775 log_debug("About to read pubkey_len at offset=%zu, bytes: %02x %02x %02x %02x", state->offset, state->key_blob[state->offset], state->key_blob[state->offset + 1], state->key_blob[state->offset + 2],
776 state->key_blob[state->offset + 3]);
777
778 uint32_t pubkey_len = read_u32_be(&state->key_blob[state->offset]);
779 state->offset += 4;
780
781 log_debug("pubkey_len=%u, offset=%zu", pubkey_len, state->offset);
782
783 if (state->offset + pubkey_len > state->key_blob_len) {
784 ssh_private_key_cleanup(state);
785 return SET_ERRNO(ERROR_CRYPTO_KEY, "OpenSSH private key truncated at pubkey data: %s", key_path);
786 }
787
788 // Parse the public key to extract the Ed25519 public key for validation
789 if (pubkey_len < 4) {
790 ssh_private_key_cleanup(state);
791 return SET_ERRNO(ERROR_CRYPTO_KEY, "OpenSSH public key too small: %s", key_path);
792 }
793
794 uint32_t key_type_len = read_u32_be(&state->key_blob[state->offset]);
795 state->offset += 4;
796
797 // Check if it's an Ed25519 key
798 if (key_type_len != 11 || memcmp(state->key_blob + state->offset, "ssh-ed25519", 11) != 0) {
799 ssh_private_key_cleanup(state);
800 return SET_ERRNO(ERROR_CRYPTO_KEY, "OpenSSH private key is not Ed25519: %s", key_path);
801 }
802
803 state->offset += key_type_len; // Skip the key type string
804 log_debug("After skipping key type, offset=%zu", state->offset);
805
806 // Read the public key length
807 if (state->offset + 4 > state->key_blob_len) {
808 ssh_private_key_cleanup(state);
809 return SET_ERRNO(ERROR_CRYPTO_KEY, "OpenSSH private key truncated at public key length: %s", key_path);
810 }
811
812 uint32_t pubkey_data_len = read_u32_be(&state->key_blob[state->offset]);
813 state->offset += 4;
814 log_debug("Public key data length: %u, offset=%zu", pubkey_data_len, state->offset);
815
816 log_debug("Public key data length: %u (expected 32 for Ed25519)", pubkey_data_len);
817
818 // For Ed25519, the public key should be 32 bytes, but let's be more flexible
819 if (pubkey_data_len < 32) {
820 ssh_private_key_cleanup(state);
821 return SET_ERRNO(ERROR_CRYPTO_KEY, "OpenSSH public key data too small (%u bytes, expected at least 32): %s", pubkey_data_len, key_path);
822 }
823
824 // Read Ed25519 public key (first 32 bytes) for validation
825 if (state->offset + 32 > state->key_blob_len) {
826 ssh_private_key_cleanup(state);
827 return SET_ERRNO(ERROR_CRYPTO_KEY, "OpenSSH private key truncated at public key: %s", key_path);
828 }
829
830 memcpy(state->ed25519_pubkey, state->key_blob + state->offset, ED25519_PUBLIC_KEY_SIZE);
831 state->offset += pubkey_data_len; // Skip the entire public key data
832
833 // Skip the rest of the public key data to get to the private key
834 // We've already parsed: 4 (key_type_len) + 11 (ssh-ed25519) + 4 (pubkey_data_len) + 32 (key) = 51 bytes
835 // So we need to skip the remaining pubkey_len - 51 bytes
836 // Check for underflow before subtraction
837 if (pubkey_len >= 51) {
838 size_t remaining_pubkey = pubkey_len - 51;
839 if (remaining_pubkey > 0) {
840 state->offset += remaining_pubkey;
841 }
842 }
843 return ASCIICHAT_OK;
844}
845
846static asciichat_error_t ssh_private_key_read_private_header(ssh_private_key_parse_t *state, const char *key_path) {
847 // Read private key
848 if (state->offset + 4 > state->key_blob_len) {
849 ssh_private_key_cleanup(state);
850 return SET_ERRNO(ERROR_CRYPTO_KEY, "OpenSSH private key truncated at privkey length: %s", key_path);
851 }
852
853 uint32_t privkey_len = read_u32_be(&state->key_blob[state->offset]);
854 state->offset += 4;
855
856 if (state->offset + privkey_len > state->key_blob_len) {
857 ssh_private_key_cleanup(state);
858 return SET_ERRNO(ERROR_CRYPTO_KEY, "OpenSSH private key truncated at privkey data: %s", key_path);
859 }
860
861 // Parse the private key structure
862 // Format: [4 bytes: checkint1] [4 bytes: checkint2] [4 bytes: key type length] [key type]
863 // [4 bytes: public key length] [public key] [4 bytes: private key length] [private key]
864 // [4 bytes: comment length] [comment]
865
866 if (privkey_len < 8) {
867 ssh_private_key_cleanup(state);
868 return SET_ERRNO(ERROR_CRYPTO_KEY, "OpenSSH private key data too small: %s", key_path);
869 }
870
871 // Verify checkints (should be equal)
872 uint32_t checkint1 = read_u32_be(&state->key_blob[state->offset]);
873 uint32_t checkint2 = read_u32_be(&state->key_blob[state->offset + 4]);
874 state->offset += 8;
875
876 if (checkint1 != checkint2) {
877 ssh_private_key_cleanup(state);
878 return SET_ERRNO(ERROR_CRYPTO_KEY, "OpenSSH private key checkints don't match: %s", key_path);
879 }
880
881 // Skip key type
882 if (state->offset + 4 > state->key_blob_len) {
883 ssh_private_key_cleanup(state);
884 return SET_ERRNO(ERROR_CRYPTO_KEY, "OpenSSH private key truncated at key type length: %s", key_path);
885 }
886
887 uint32_t key_type_len_priv = read_u32_be(&state->key_blob[state->offset]);
888 // Check for integer overflow before adding to offset
889 if (key_type_len_priv > state->key_blob_len || state->offset + 4 + key_type_len_priv > state->key_blob_len) {
890 ssh_private_key_cleanup(state);
891 return SET_ERRNO(ERROR_CRYPTO_KEY, "OpenSSH private key type length overflow: %u", key_type_len_priv);
892 }
893 state->offset += 4 + key_type_len_priv;
894
895 // Skip public key
896 if (state->offset + 4 > state->key_blob_len) {
897 ssh_private_key_cleanup(state);
898 return SET_ERRNO(ERROR_CRYPTO_KEY, "OpenSSH private key truncated at pubkey length: %s", key_path);
899 }
900
901 uint32_t pubkey_len_priv = read_u32_be(&state->key_blob[state->offset]);
902 // Check for integer overflow before adding to offset
903 if (pubkey_len_priv > state->key_blob_len || state->offset + 4 + pubkey_len_priv > state->key_blob_len) {
904 ssh_private_key_cleanup(state);
905 return SET_ERRNO(ERROR_CRYPTO_KEY, "OpenSSH private key public key length overflow: %u", pubkey_len_priv);
906 }
907 state->offset += 4 + pubkey_len_priv;
908
909 return ASCIICHAT_OK;
910}
911
912static asciichat_error_t ssh_private_key_read_private(ssh_private_key_parse_t *state, const char *key_path, private_key_t *key_out) {
913 // Read private key
914 if (state->offset + 4 > state->key_blob_len) {
915 ssh_private_key_cleanup(state);
916 return SET_ERRNO(ERROR_CRYPTO_KEY, "OpenSSH private key truncated at privkey length: %s", key_path);
917 }
918
919 uint32_t privkey_data_len = read_u32_be(&state->key_blob[state->offset]);
920 state->offset += 4;
921
922 if (state->offset + privkey_data_len > state->key_blob_len) {
923 ssh_private_key_cleanup(state);
924 return SET_ERRNO(ERROR_CRYPTO_KEY, "OpenSSH private key truncated at privkey data: %s", key_path);
925 }
926
927 // The private key data should be at least 64 bytes (32 bytes private key + 32 bytes public key)
928 // But OpenSSH format may have additional data
929 if (privkey_data_len < 64) {
930 ssh_private_key_cleanup(state);
931 return SET_ERRNO(ERROR_CRYPTO_KEY, "OpenSSH private key data length is %u (expected at least 64): %s", privkey_data_len, key_path);
932 }
933
934 // Extract the Ed25519 private key (first 32 bytes)
935 uint8_t ed25519_privkey[ED25519_SEED_SIZE];
936 memcpy(ed25519_privkey, state->key_blob + state->offset, sizeof(ed25519_privkey));
937
938 // Verify the public key matches
939 // The public key in the privkey section is raw Ed25519, while the one in pubkey section is SSH format
940 // We need to compare the raw public key from privkey with the raw public key extracted from pubkey
941 // Use constant-time comparison for cryptographic material
942 if (sodium_memcmp(state->key_blob + state->offset + 32, state->ed25519_pubkey, 32) != 0) {
943 ssh_private_key_cleanup(state);
944 return SET_ERRNO(ERROR_CRYPTO_KEY, "OpenSSH private key public key mismatch: %s", key_path);
945 }
946
947 // Initialize the private key structure
948 memset(key_out, 0, sizeof(private_key_t));
949 key_out->type = KEY_TYPE_ED25519;
950
951 // Store the actual private key (seed + public key = 64 bytes)
952 // Ed25519 private key format: [32 bytes seed][32 bytes public key]
953 memcpy(key_out->key.ed25519, ed25519_privkey, CRYPTO_PUBLIC_KEY_SIZE); // Store the seed (first 32 bytes)
954 memcpy(key_out->key.ed25519 + 32, state->ed25519_pubkey,
955 ED25519_PUBLIC_KEY_SIZE); // Store the public key (next 32 bytes)
956
957 // Also store the public key in the public_key field for easy access
958 memcpy(key_out->public_key, state->ed25519_pubkey, ED25519_PUBLIC_KEY_SIZE);
959
960 // Set a comment
961 SAFE_STRNCPY(key_out->key_comment, "ssh-ed25519", sizeof(key_out->key_comment) - 1);
962
963 ssh_private_key_cleanup(state);
964 return ASCIICHAT_OK;
965}
966
968 if (!key_path || !key_out) {
969 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: key_path=%p, key_out=%p", key_path, key_out);
970 }
971#ifndef EMSCRIPTEN_BUILD
972 if (ssh_private_key_from_agent(key_path, key_out))
973 return ASCIICHAT_OK;
974#endif
975
976 // Each stage retains the existing failure cleanup; later stages run only on success.
977 ssh_private_key_parse_t state = {0};
978 asciichat_error_t result = ssh_private_key_read_file(&state, key_path);
979 if (result != ASCIICHAT_OK)
980 return result;
981 result = ssh_private_key_decode_pem(&state, key_path);
982 if (result != ASCIICHAT_OK)
983 return result;
984 result = ssh_private_key_read_header(&state, key_path);
985 if (result != ASCIICHAT_OK)
986 return result;
987
988 if (state.is_encrypted) {
989#ifdef EMSCRIPTEN_BUILD
990 SAFE_FREE(state.key_blob);
991 SAFE_FREE(state.file_content);
992 return SET_ERRNO(ERROR_NOT_SUPPORTED, "Passphrase-protected SSH keys are not supported in the browser");
993#else
994 return ssh_private_key_parse_encrypted(&state, key_path, key_out);
995#endif
996 }
997
998 result = ssh_private_key_read_public(&state, key_path);
999 if (result != ASCIICHAT_OK)
1000 return result;
1001 result = ssh_private_key_read_private_header(&state, key_path);
1002 if (result != ASCIICHAT_OK)
1003 return result;
1004 return ssh_private_key_read_private(&state, key_path, key_out);
1005}
1006
1008 if (!key_path) {
1009 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: key_path=%p", key_path);
1010 }
1011
1012 char *normalized_path = NULL;
1013 defer(SAFE_FREE(normalized_path));
1014#ifdef EMSCRIPTEN_BUILD
1015 // Browser callers stage imported key text at this private virtual-FS path;
1016 // native path expansion and whitelist checks do not apply to that sandbox.
1017 static const char wasm_key_prefix[] = "/tmp/ascii-chat-key-";
1018 if (strncmp(key_path, wasm_key_prefix, sizeof(wasm_key_prefix) - 1) != 0) {
1019 return SET_ERRNO(ERROR_CRYPTO_KEY, "Invalid browser SSH key path");
1020 }
1021 const char *validated_path = key_path;
1022#else
1023 if (!path_looks_like_path(key_path)) {
1024 return SET_ERRNO(ERROR_CRYPTO_KEY, "Invalid SSH key path: %s", key_path);
1025 }
1026
1027 asciichat_error_t path_result = path_validate_user_path(key_path, PATH_ROLE_KEY_PRIVATE, &normalized_path);
1028 if (path_result != ASCIICHAT_OK) {
1029 return path_result;
1030 }
1031 const char *validated_path = normalized_path;
1032#endif
1033
1034 // Check if file exists and is readable
1035 FILE *test_file = platform_fopen("file_stream", validated_path, "rb");
1036 if (test_file == NULL) {
1037 return SET_ERRNO(ERROR_CRYPTO_KEY, "Cannot read key file: %s", key_path);
1038 }
1039
1040 // Check if this is an SSH key file or GPG armored key by looking for the header
1041 char header[BUFFER_SIZE_SMALL];
1042 bool is_valid_key_file = false;
1043 size_t header_len = fread(header, 1, sizeof(header) - 1, test_file);
1044 if (header_len > 0) {
1045 header[header_len] = '\0';
1046 if (strstr(header, "BEGIN OPENSSH PRIVATE KEY") != NULL || strstr(header, "BEGIN RSA PRIVATE KEY") != NULL || strstr(header, "BEGIN EC PRIVATE KEY") != NULL ||
1047 strstr(header, "BEGIN PGP PRIVATE KEY") != NULL || strstr(header, "BEGIN PGP SECRET KEY") != NULL) {
1048 is_valid_key_file = true;
1049 } else {
1050 uint8_t first_packet = (uint8_t)header[0];
1051 unsigned int packet_tag = (first_packet & 0x80u) ? ((first_packet & 0x40u) ? (first_packet & 0x3fu) : ((first_packet >> 2) & 0x0fu)) : 0u;
1052 is_valid_key_file = packet_tag == 5u;
1053 }
1054 }
1055 (void)fclose(test_file);
1056
1057 if (!is_valid_key_file) {
1058 return SET_ERRNO(ERROR_CRYPTO_KEY, "File is not a valid SSH or GPG key: %s", key_path);
1059 }
1060
1061 // Check permissions for SSH key files (should be 600 or 400)
1062#ifndef _WIN32
1063 struct stat st;
1064 if (stat(validated_path, &st) == 0) {
1065 if ((st.st_mode & SSH_KEY_PERMISSIONS_MASK) != 0) {
1066 NOTICE(DANGER, "UNSAFE PRIVATE KEY PERMISSIONS", "SSH key file %s has overly permissive permissions: %o.\nRun chmod 600 on this key file before retrying.", key_path, st.st_mode & 0777);
1067 return SET_ERRNO(ERROR_CRYPTO_KEY, "SSH key file has overly permissive permissions: %s", key_path);
1068 }
1069 }
1070#endif
1071
1072 return ASCIICHAT_OK;
1073}
1074
1075// =============================================================================
1076// Key Conversion Functions
1077// =============================================================================
1078
1080 if (!ed25519_pk || !x25519_pk) {
1081 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: ed25519_pk=%p, x25519_pk=%p", ed25519_pk, x25519_pk);
1082 }
1083
1084 // Convert Ed25519 public key to X25519 public key
1085 if (crypto_sign_ed25519_pk_to_curve25519(x25519_pk, ed25519_pk) != 0) {
1086 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to convert Ed25519 public key to X25519");
1087 }
1088
1089 return ASCIICHAT_OK;
1090}
1091
1093 if (!ed25519_sk || !x25519_sk) {
1094 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: ed25519_sk=%p, x25519_sk=%p", ed25519_sk, x25519_sk);
1095 }
1096
1097 // Convert Ed25519 private key to X25519 private key
1098 if (crypto_sign_ed25519_sk_to_curve25519(x25519_sk, ed25519_sk) != 0) {
1099 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to convert Ed25519 private key to X25519");
1100 }
1101
1102 return ASCIICHAT_OK;
1103}
1104
1105// =============================================================================
1106// SSH Key Operations
1107// =============================================================================
1108
1109asciichat_error_t ed25519_sign_message(const private_key_t *key, const uint8_t *message, size_t message_len, uint8_t signature[ED25519_SIGNATURE_SIZE]) {
1110 if (!key || !message || !signature) {
1111 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: key=%p, message=%p, signature=%p", key, message, signature);
1112 }
1113
1114 if (key->type != KEY_TYPE_ED25519) {
1115 return SET_ERRNO(ERROR_CRYPTO_KEY, "Key is not an Ed25519 key");
1116 }
1117
1118#ifndef EMSCRIPTEN_BUILD
1119 // If using GPG agent, delegate signing to GPG agent
1120 if (key->use_gpg_agent) {
1121 log_debug("Using GPG agent for Ed25519 signing (keygrip: %.40s)", key->gpg_keygrip);
1122
1123 // Connect to GPG agent
1124 int agent_sock = gpg_agent_connect();
1125 log_debug("GPG agent connection result: %d", agent_sock);
1126
1127 if (agent_sock < 0) {
1128 log_debug("GPG agent not available, falling back to gpg --detach-sign for signing");
1129
1130 // Extract GPG key ID from key comment ("GPG key <key_id>")
1131 const char *key_id_prefix = "GPG key ";
1132 const char *key_id = NULL;
1133 if (strncmp(key->key_comment, key_id_prefix, strlen(key_id_prefix)) == 0) {
1134 key_id = key->key_comment + strlen(key_id_prefix);
1135 }
1136
1137 log_debug("Extracted GPG key ID: %s (len=%zu)", key_id ? key_id : "NULL", key_id ? strlen(key_id) : 0);
1138
1139 if (!key_id || strlen(key_id) != 16) {
1140 return SET_ERRNO(ERROR_CRYPTO, "Cannot extract GPG key ID from comment for fallback signing");
1141 }
1142
1143 // Use gpg --detach-sign fallback
1144 log_debug("Calling gpg_sign_detached_ed25519 with key %s", key_id);
1145 int result = gpg_sign_detached_ed25519(key_id, message, message_len, signature);
1146 log_debug("gpg_sign_detached_ed25519 result: %d", result);
1147
1148 if (result != 0) {
1149 return SET_ERRNO(ERROR_CRYPTO, "GPG fallback signing failed (both agent and gpg command failed)");
1150 }
1151
1152 log_debug("Successfully signed message with gpg --detach-sign fallback (64 bytes)");
1153 return ASCIICHAT_OK;
1154 }
1155
1156 log_debug("Using GPG agent for signing");
1157
1158 // Sign the message using GPG agent
1159 size_t sig_len = 0;
1160 int result = gpg_agent_sign(agent_sock, key->gpg_keygrip, message, message_len, signature, &sig_len);
1161
1162 // Disconnect from agent
1163 gpg_agent_disconnect(agent_sock);
1164
1165 if (result != 0) {
1166 return SET_ERRNO(ERROR_CRYPTO, "GPG agent signing failed");
1167 }
1168
1169 if (sig_len != 64) {
1170 return SET_ERRNO(ERROR_CRYPTO, "GPG agent returned invalid signature length: %zu (expected 64)", sig_len);
1171 }
1172
1173 log_debug("Successfully signed message with GPG agent (64 bytes)");
1174 return ASCIICHAT_OK;
1175 }
1176
1177 // If using SSH agent, delegate signing to SSH agent
1178 if (key->use_ssh_agent) {
1179 log_debug("Using SSH agent for Ed25519 signing");
1180
1181 // Create a public_key_t from the stored public key
1182 public_key_t pub_key = {0};
1183 pub_key.type = KEY_TYPE_ED25519;
1184 memcpy(pub_key.key, key->public_key, ED25519_PUBLIC_KEY_SIZE);
1185
1186 // Sign using SSH agent
1187 asciichat_error_t result = ssh_agent_sign(&pub_key, message, message_len, signature);
1188 if (result != ASCIICHAT_OK) {
1189 return result; // Error already set by ssh_agent_sign
1190 }
1191
1192 log_debug("Successfully signed message with SSH agent (64 bytes)");
1193 return ASCIICHAT_OK;
1194 }
1195#else
1196 if (key->use_gpg_agent || key->use_ssh_agent) {
1197 return SET_ERRNO(ERROR_NOT_SUPPORTED, "External SSH and GPG agents are not available in the browser");
1198 }
1199#endif
1200
1201 // Sign the message with Ed25519 (in-memory key)
1202 if (crypto_sign_detached(signature, NULL, message, message_len, key->key.ed25519) != 0) {
1203 return SET_ERRNO(ERROR_CRYPTO, "Failed to sign message with Ed25519");
1204 }
1205
1206 return ASCIICHAT_OK;
1207}
1208
1209asciichat_error_t ed25519_verify_signature(const uint8_t public_key[ED25519_PUBLIC_KEY_SIZE], const uint8_t *message, size_t message_len, const uint8_t signature[ED25519_SIGNATURE_SIZE],
1210 const char *gpg_key_id) {
1211 if (!public_key || !message || !signature) {
1212 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: public_key=%p, message=%p, signature=%p", public_key, message, signature);
1213 }
1214
1215 // Try standard Ed25519 verification first
1216 if (crypto_sign_verify_detached(signature, message, message_len, public_key) == 0) {
1217 return ASCIICHAT_OK;
1218 }
1219
1220#ifndef EMSCRIPTEN_BUILD
1221 // If standard verification fails, try GPG fallback (for GPG-signed messages)
1222 // Use provided gpg_key_id if available, otherwise check environment variable (for tests)
1223 const char *key_id_to_use = gpg_key_id;
1224 size_t key_id_len = key_id_to_use ? strlen(key_id_to_use) : 0;
1225 // Accept 8, 16, or 40 character GPG key IDs (short, long, or full fingerprint)
1226 bool valid_key_id = (key_id_len == 8 || key_id_len == 16 || key_id_len == 40);
1227
1228 if (!valid_key_id) {
1229 key_id_to_use = platform_getenv("TEST_GPG_KEY_ID");
1230 key_id_len = key_id_to_use ? strlen(key_id_to_use) : 0;
1231 valid_key_id = (key_id_len == 8 || key_id_len == 16 || key_id_len == 40);
1232 }
1233
1234 if (valid_key_id) {
1235 log_debug("Standard Ed25519 verification failed, trying GPG fallback with key %s", key_id_to_use);
1236 int gpg_result = gpg_verify_detached_ed25519(key_id_to_use, message, message_len, signature);
1237 if (gpg_result == 0) {
1238 log_debug("GPG verification succeeded");
1239 return ASCIICHAT_OK;
1240 }
1241 log_debug("GPG verification also failed");
1242 }
1243#endif
1244
1245 return SET_ERRNO(ERROR_CRYPTO, "Ed25519 signature verification failed (tried both libsodium and GPG)");
1246}
const char * asciichat_error_format(const char *message, asciichat_error_t code)
Synchronized per-thread pending error stacks and value snapshots. SET_ERRNO pushes,...
#define SET_ERRNO(code,...)
🔢 Byte-Level Access and Arithmetic Utilities
FILE * platform_fopen(const char *name, const char *filename, const char *mode)
Definition filesystem.c:18
GPG operations - main header.
#define BUFFER_SIZE_LARGE
Large buffer size (1024 bytes).
#define BUFFER_SIZE_XXLARGE
Extra extra large buffer size (4096 bytes).
#define BUFFER_SIZE_SMALL
Small buffer size (256 bytes).
#define SAFE_REALLOC(ptr, size, cast)
unsigned int uint32_t
#define SAFE_STRNCPY(dst, src, size)
#define SAFE_FREE(ptr)
#define SAFE_MALLOC_DEFER_FREE(name, size, cast)
#define SAFE_MALLOC(size, cast)
#define SAFE_CALLOC(count, size, cast)
unsigned char uint8_t
#define SAFE_FCLOSE(fp)
int gpg_verify_detached_ed25519(const char *key_id, const uint8_t *message, size_t message_len, const uint8_t signature[ED25519_SIGNATURE_SIZE])
Verify Ed25519 signature using GPG binary.
bool ssh_agent_has_key(const public_key_t *public_key)
Check if a public key is already in ssh-agent.
Definition ssh_agent.c:54
int gpg_agent_connect(void)
Connect to gpg-agent.
Definition agent.c:103
int gpg_agent_sign(int handle_as_int, const char *keygrip, const uint8_t *message, size_t message_len, uint8_t *signature_out, size_t *signature_len_out)
Sign a message using GPG agent.
Definition agent.c:161
int gpg_sign_detached_ed25519(const char *key_id, const uint8_t *message, size_t message_len, uint8_t signature_out[ED25519_SIGNATURE_SIZE])
Sign message with GPG and extract raw Ed25519 signature.
Definition signing.c:144
#define SSH_KEY_HEADER_SIZE
asciichat_error_t ssh_agent_add_key(const private_key_t *private_key, const char *key_path)
Add a private key to ssh-agent.
Definition ssh_agent.c:149
void gpg_agent_disconnect(int handle_as_int)
Disconnect from gpg-agent.
Definition agent.c:153
asciichat_error_t ssh_agent_sign(const public_key_t *public_key, const uint8_t *message, size_t message_len, uint8_t signature[64])
Sign data using SSH agent with the specified public key.
Definition ssh_agent.c:260
#define SSH_KEY_PERMISSIONS_MASK
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_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_CRYPTO
Definition error_codes.h:97
@ ERROR_INVALID_PARAM
@ ERROR_NOT_SUPPORTED
Definition error_codes.h:73
uint8_t key[CRYPTO_PUBLIC_KEY_SIZE]
Definition key_types.h:78
uint8_t ed25519[ED25519_PRIVATE_KEY_SIZE]
Definition key_types.h:104
key_type_t type
Definition key_types.h:102
bool use_gpg_agent
Definition key_types.h:108
bool use_ssh_agent
Definition key_types.h:107
char key_comment[MAX_COMMENT_LEN]
Definition key_types.h:110
uint8_t public_key[CRYPTO_PUBLIC_KEY_SIZE]
Definition key_types.h:109
char gpg_keygrip[MAX_GPG_KEYGRIP_LEN]
Definition key_types.h:111
asciichat_error_t parse_ssh_private_key(const char *key_path, private_key_t *key_out)
Parse SSH Ed25519 private key from file.
Definition ssh_keys.c:967
key_type_t type
Definition key_types.h:77
union private_key_t::@040247167361101132173265304166142033301213115260 key
asciichat_error_t validate_ssh_key_file(const char *key_path)
Validate SSH key file permissions and format.
Definition ssh_keys.c:1007
@ KEY_TYPE_ED25519
Definition key_types.h:58
#define log_warn(...)
Log a WARN message.
Definition log/log.h:615
#define log_dev(...)
Log a DEV message (most verbose, development only).
Definition log/log.h:575
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:589
bool path_looks_like_path(const char *value)
Determine if a string is likely intended to reference the filesystem.
Definition path.c:495
asciichat_error_t path_validate_user_path(const char *input, path_role_t role, char **normalized_out)
Validate and canonicalize a user-supplied filesystem path.
Definition path.c:705
int prompt_password_simple_kind(const char *prompt, char *password, size_t max_len, ui_prompt_kind_t kind)
Definition password.c:35
@ PATH_ROLE_KEY_PRIVATE
Definition path.h:325
⚙️ Common definitions, error codes, macros, and types shared throughout the application
#define NOTICE(severity, title,...)
Definition notice.h:56
Password prompting utilities with secure input and formatting.
📂 Path Manipulation Utilities
bool crypto_regex_match_public_key(const char *line, char **base64_key_out, char **comment_out)
Definition regex.c:175
bool crypto_regex_extract_pem_base64(const char *file_content, char **base64_data_out)
Definition regex.c:214
PCRE2-based regex patterns for cryptographic parsing.
#define ED25519_SIGNATURE_SIZE
Ed25519 signature size in bytes.
Definition sizes.h:41
#define ED25519_PUBLIC_KEY_SIZE
Ed25519 public key size in bytes.
Definition sizes.h:37
#define X25519_KEY_SIZE
X25519 key size in bytes.
Definition sizes.h:35
#define CRYPTO_PUBLIC_KEY_SIZE
Public key size (X25519).
Definition sizes.h:71
#define ED25519_SEED_SIZE
Definition sizes.h:169
#define ED25519_PRIVATE_KEY_SIZE
Ed25519 private key size (seed + public) in bytes.
Definition sizes.h:39
#define AES_IV_SIZE
AES initialization vector (IV) size in bytes.
Definition sizes.h:57
char * platform_strdup(const char *s)
asciichat_error_t ed25519_to_x25519_private(const uint8_t ed25519_sk[ED25519_PRIVATE_KEY_SIZE], uint8_t x25519_sk[X25519_KEY_SIZE])
Definition ssh_keys.c:1092
asciichat_error_t ed25519_sign_message(const private_key_t *key, const uint8_t *message, size_t message_len, uint8_t signature[ED25519_SIGNATURE_SIZE])
Definition ssh_keys.c:1109
#define CRYPTO_SSH_SSH_KEYS_KDFNAME_BUFFER_SIZE
Definition ssh_keys.c:9
asciichat_error_t ed25519_verify_signature(const uint8_t public_key[ED25519_PUBLIC_KEY_SIZE], const uint8_t *message, size_t message_len, const uint8_t signature[ED25519_SIGNATURE_SIZE], const char *gpg_key_id)
Definition ssh_keys.c:1209
asciichat_error_t parse_ssh_ed25519_line(const char *line, uint8_t ed25519_pk[ED25519_PUBLIC_KEY_SIZE])
Definition ssh_keys.c:165
#define SSH_BCRYPT_SALT_SIZE
Definition ssh_keys.c:15
#define SSH_PASSWORD_INPUT_BUFFER_SIZE
Definition ssh_keys.c:12
#define CRYPTO_SSH_SSH_KEYS_CIPHERNAME_BUFFER_SIZE
Definition ssh_keys.c:8
asciichat_error_t ed25519_to_x25519_public(const uint8_t ed25519_pk[ED25519_PUBLIC_KEY_SIZE], uint8_t x25519_pk[X25519_KEY_SIZE])
Definition ssh_keys.c:1079
🔤 String Manipulation and Shell Escaping Utilities
Private identity-key material used for server authentication and signing.
Definition key_types.h:101
The normalized public identity used by ascii-chat's crypto and key-management code.
Definition key_types.h:76
uint8_t bcrypt_salt[16]
Definition ssh_keys.c:222
uint8_t ed25519_pubkey[ED25519_PUBLIC_KEY_SIZE]
Definition ssh_keys.c:223
const char * platform_getenv(const char *name)
Definition system.c:45
⏱️ High-precision timing utilities using sokol_time.h and uthash