ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
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_KEYS_HEADER_BUFFER_SIZE 50
9
17#include <ascii-chat/common.h>
18#include <recast/defer.h>
22#include <ascii-chat/util/url.h> // For url_is_valid(), url_parse()
23#include <ascii-chat/crypto/gpg/export.h> // For gpg_get_public_key()
24#include <ascii-chat/network/http/client/client.h> // For https_get()
25#include <libplatform/filesystem.h>
26#include <util/string.h>
27#include <string.h>
28#include <stdlib.h>
29#include <stdio.h>
30#include <ctype.h>
31
32// =============================================================================
33// High-Level Key Parsing Functions
34// =============================================================================
35
36asciichat_error_t parse_public_key(const char *input, public_key_t *key_out) {
37 if (!input || !key_out) {
38 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters for public key parsing");
39 }
40
41 // Clear output structure
42 memset(key_out, 0, sizeof(public_key_t));
43
44 // Try SSH key parsing first (full format with prefix)
45 if (strncmp(input, "ssh-ed25519", 11) == 0) {
46 key_out->type = KEY_TYPE_ED25519;
47 asciichat_error_t result = parse_ssh_ed25519_line(input, key_out->key);
48 if (result == ASCIICHAT_OK) {
49 platform_strncpy(key_out->comment, sizeof(key_out->comment), "ssh-ed25519", sizeof(key_out->comment) - 1);
50 }
51 return result;
52 }
53
54 // Try raw base64 SSH public key (without "ssh-ed25519" prefix)
55 // SSH Ed25519 public keys in base64 are typically ~68 characters
56 size_t input_len = strlen(input);
57 if (input_len >= 50 && input_len <= 80) {
58 // Check if it looks like base64 (only contains valid base64 chars)
59 bool looks_like_base64 = true;
60 for (size_t i = 0; i < input_len; i++) {
61 char c = input[i];
62 if (!((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '+' || c == '/' || c == '=')) {
63 looks_like_base64 = false;
64 break;
65 }
66 }
67
68 if (looks_like_base64) {
69 // Try to decode as SSH public key blob
70 SAFE_MALLOC_DEFER_FREE(blob, input_len, uint8_t *);
71 size_t blob_len = 0;
72
73 const char *end = NULL;
74 int decode_result = sodium_base642bin(blob, input_len, input, input_len,
75 NULL, // ignore chars
76 &blob_len, &end, sodium_base64_VARIANT_ORIGINAL);
77
78 if (decode_result == 0 && blob_len >= 47) { // Minimum size: 4+11+4+32 = 51 bytes
79 // Validate SSH key blob structure
80 // Format: [4 bytes: length][11 bytes: "ssh-ed25519"][4 bytes: length][32 bytes: key]
81 if (blob_len >= 4) {
82 uint32_t key_type_len = ((uint32_t)blob[0] << 24) | ((uint32_t)blob[1] << 16) | ((uint32_t)blob[2] << 8) | blob[3];
83 if (key_type_len == 11 && blob_len >= 15 && memcmp(blob + 4, "ssh-ed25519", 11) == 0) {
84 // Valid ssh-ed25519 blob, extract the 32-byte public key
85 if (blob_len >= 19) {
86 uint32_t pubkey_len = ((uint32_t)blob[15] << 24) | ((uint32_t)blob[16] << 16) | ((uint32_t)blob[17] << 8) | blob[18];
87 if (pubkey_len == 32 && blob_len >= 51) {
88 // Extract Ed25519 public key
89 key_out->type = KEY_TYPE_ED25519;
90 memcpy(key_out->key, blob + 19, CRYPTO_PUBLIC_KEY_SIZE);
91 platform_strncpy(key_out->comment, sizeof(key_out->comment), "raw-base64", sizeof(key_out->comment) - 1);
92 return ASCIICHAT_OK;
93 }
94 }
95 }
96 }
97 }
98 }
99 }
100
101 // Try GPG key parsing
102 if (strncmp(input, "gpg:", 4) == 0) {
103 return parse_gpg_key(input + 4, key_out);
104 }
105
106 // Try HTTPS URLs (validated via production-grade URL regex)
107 if (url_is_valid(input)) {
108 // Parse HTTPS URL to extract hostname and path
109 url_parts_t url_parts = {0};
110 asciichat_error_t parse_result = url_parse(input, &url_parts);
111 if (parse_result != ASCIICHAT_OK) {
112 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to parse HTTPS URL: %s", input);
113 }
114
115 // Fetch the key via HTTPS
116 char *response = https_get(url_parts.host, url_parts.path);
117 url_parts_destroy(&url_parts);
118
119 if (!response) {
120 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to fetch key from HTTPS URL: %s", input);
121 }
122
123 // Parse the fetched content as a public key
124 asciichat_error_t result = parse_public_key(response, key_out);
125 SAFE_FREE(response);
126 return result;
127 }
128
129 // Try HTTPS key fetching (GitHub/GitLab) - delegate to parse_public_keys and return first
130 if (strncmp(input, "github:", 7) == 0 || strncmp(input, "gitlab:", 7) == 0) {
131 public_key_t keys[1];
132 size_t num_keys = 0;
133 asciichat_error_t result = parse_public_keys(input, keys, &num_keys, 1);
134 if (result == ASCIICHAT_OK && num_keys > 0) {
135 *key_out = keys[0];
136 }
137 return result;
138 }
139
140 // Try raw hex key (64 hex chars = 32 bytes)
141 if (strlen(input) == 64) {
142 // Check if it's valid hex
143 bool is_valid_hex = true;
144 for (int i = 0; i < 64; i++) {
145 if (!((input[i] >= '0' && input[i] <= '9') || (input[i] >= 'a' && input[i] <= 'f') || (input[i] >= 'A' && input[i] <= 'F'))) {
146 is_valid_hex = false;
147 break;
148 }
149 }
150
151 if (is_valid_hex) {
152 // Assume it's a raw X25519 public key in hex (default for raw hex)
153 key_out->type = KEY_TYPE_X25519;
154 // Use hex_decode utility to safely decode hex string to binary
155 if (hex_decode(input, key_out->key, 32) != ASCIICHAT_OK) {
156 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to decode hex key");
157 }
158 platform_strncpy(key_out->comment, sizeof(key_out->comment), "raw-hex", sizeof(key_out->comment) - 1);
159 return ASCIICHAT_OK;
160 }
161 }
162
163 // Try PGP armored format (-----BEGIN PGP PUBLIC KEY BLOCK-----)
164 if (strstr(input, "-----BEGIN PGP PUBLIC KEY BLOCK-----") != NULL) {
165 return parse_gpg_key_binary((const uint8_t *)input, strlen(input), key_out);
166 }
167
168 if (path_looks_like_path(input)) {
169 char *normalized_path = NULL;
170 defer(SAFE_FREE(normalized_path));
171 asciichat_error_t path_result = path_validate_user_path(input, PATH_ROLE_KEY_PUBLIC, &normalized_path);
172 if (path_result != ASCIICHAT_OK) {
173 return path_result;
174 }
175
176 FILE *f = platform_fopen("file_stream", normalized_path, "rb");
177 if (f) {
178 defer(SAFE_FCLOSE(f));
179 char line[BUFFER_SIZE_LARGE];
180 if (fgets(line, sizeof(line), f)) {
181 uint8_t first_packet = (uint8_t)line[0];
182 unsigned int packet_tag = (first_packet & 0x80u) ? ((first_packet & 0x40u) ? (first_packet & 0x3fu) : ((first_packet >> 2) & 0x0fu)) : 0u;
183 bool armored_gpg = strstr(line, "-----BEGIN PGP PUBLIC KEY BLOCK-----") != NULL;
184 if (armored_gpg || packet_tag == 6u) {
185 if (fseek(f, 0, SEEK_END) != 0) {
186 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to seek OpenPGP public key file: %s", input);
187 }
188 long file_size = ftell(f);
189 if (file_size <= 0 || file_size > 1024 * 1024 || fseek(f, 0, SEEK_SET) != 0) {
190 return SET_ERRNO(ERROR_CRYPTO_KEY, "Invalid OpenPGP public key file size: %ld bytes", file_size);
191 }
192 SAFE_MALLOC_DEFER_FREE(file_content, (size_t)file_size, uint8_t *);
193 size_t content_read = fread(file_content, 1, (size_t)file_size, f);
194 SAFE_FCLOSE(f);
195 if (content_read != (size_t)file_size) {
196 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to read OpenPGP public key file: %s", input);
197 }
198 asciichat_error_t result = parse_gpg_key_binary(file_content, content_read, key_out);
199 return result;
200 }
201 SAFE_FCLOSE(f);
202 // Remove newline
203 line[strcspn(line, "\r\n")] = 0;
204 return parse_public_key(line, key_out);
205 }
206 }
207 }
208
209 return SET_ERRNO(ERROR_CRYPTO_KEY, "Unsupported key format: %s", input);
210}
211
212asciichat_error_t parse_private_key(const char *key_path, private_key_t *key_out) {
213 if (!key_path || !key_out) {
214 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters for private key parsing");
215 }
216
217 // Clear output structure
218 memset(key_out, 0, sizeof(private_key_t));
219
220 // Check for GPG key format: "gpg:KEYID" where KEYID is 8, 16, or 40 hex chars
221 // - 8 chars: short key ID (last 8 chars of fingerprint)
222 // - 16 chars: long key ID (last 16 chars of fingerprint)
223 // - 40 chars: full fingerprint
224 if (strncmp(key_path, "gpg:", 4) == 0) {
225 const char *key_id = key_path + 4; // Skip "gpg:" prefix
226
227 // Validate key ID format (must be 8, 16, or 40 hex characters)
228 size_t key_id_len = strlen(key_id);
229 if (key_id_len != 8 && key_id_len != 16 && key_id_len != 40) {
230 return SET_ERRNO(ERROR_CRYPTO_KEY, "Invalid GPG key ID length: %zu (expected 8, 16, or 40 hex chars)", key_id_len);
231 }
232
233 // Validate hex characters
234 for (size_t i = 0; i < key_id_len; i++) {
235 char c = key_id[i];
236 if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'))) {
237 return SET_ERRNO(ERROR_CRYPTO_KEY, "Invalid GPG key ID: contains non-hex character '%c'", c);
238 }
239 }
240
241 // Get public key and keygrip from GPG keyring
243 char keygrip[MAX_GPG_KEYGRIP_LEN];
244 if (gpg_get_public_key(key_id, public_key, keygrip) != 0) {
245 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to get public key from GPG for key ID: %s", key_id);
246 }
247
248 // Populate private_key_t structure for GPG agent use
249 key_out->type = KEY_TYPE_ED25519;
250 key_out->use_gpg_agent = true;
251 key_out->use_ssh_agent = false;
252
253 // Store public key (for handshake and verification)
254 memcpy(key_out->public_key, public_key, ED25519_PUBLIC_KEY_SIZE);
255
256 // Store keygrip (for GPG agent signing operations)
257 platform_strncpy(key_out->gpg_keygrip, sizeof(key_out->gpg_keygrip), keygrip, sizeof(key_out->gpg_keygrip) - 1);
258
259 // Store comment for display
260 safe_snprintf(key_out->key_comment, sizeof(key_out->key_comment), "GPG key %s", key_id);
261
262 // Clear the key.ed25519 field (we don't have the private key in memory)
263 // The private key stays protected in GPG agent
264 memset(key_out->key.ed25519, 0, ED25519_PRIVATE_KEY_SIZE);
265
266 // Set the public key in the second half of ed25519 key (standard Ed25519 format)
267 // This is for compatibility with code that expects the public key at offset 32
268 memcpy(key_out->key.ed25519 + ED25519_SEED_SIZE, public_key, ED25519_PUBLIC_KEY_SIZE);
269
270 log_debug("Loaded GPG key %s (keygrip: %.40s) for agent signing", key_id, keygrip);
271 return ASCIICHAT_OK;
272 }
273
274 // Try to load file and detect format
275 char *normalized_path = NULL;
276 defer(SAFE_FREE(normalized_path));
277 asciichat_error_t path_result = path_validate_user_path(key_path, PATH_ROLE_KEY_PRIVATE, &normalized_path);
278 if (path_result != ASCIICHAT_OK) {
279 return path_result;
280 }
281
282 // Read file content to detect format
283 FILE *f = platform_fopen("file_stream", normalized_path, "rb");
284 if (!f) {
285 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to open private key file: %s", key_path);
286 }
287
288 // Read first 50 bytes to detect format
290 size_t bytes_read = fread(header, 1, sizeof(header) - 1, f);
291 header[bytes_read] = '\0';
292 fclose(f);
293
294 log_debug("Read %zu bytes from %s", bytes_read, key_path);
295
296 // Check for PGP armored secret key format
297 if (strstr(header, "-----BEGIN PGP PRIVATE KEY") != NULL || strstr(header, "-----BEGIN PGP SECRET KEY") != NULL) {
298 log_debug("Detected PGP armored secret key format in %s", key_path);
299 // Load entire file for OpenPGP parsing
300 f = platform_fopen("file_stream", normalized_path, "r");
301 if (!f) {
302 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to open GPG key file: %s", key_path);
303 }
304
305 // Get file size
306 fseek(f, 0, SEEK_END);
307 long file_size = ftell(f);
308 fseek(f, 0, SEEK_SET);
309
310 if (file_size <= 0 || file_size > 1024 * 1024) { // Sanity check: max 1MB
311 fclose(f);
312
313 return SET_ERRNO(ERROR_CRYPTO_KEY, "Invalid GPG key file size: %ld bytes", file_size);
314 }
315
316 SAFE_MALLOC_DEFER_FREE(file_content, (size_t)file_size + 1, char *);
317 size_t content_read = fread(file_content, 1, (size_t)file_size, f);
318 file_content[content_read] = '\0';
319 fclose(f);
320
321 // Parse OpenPGP armored secret key
323 uint8_t ed25519_sk[ED25519_SEED_SIZE];
324 asciichat_error_t openpgp_result = openpgp_parse_armored_seckey(file_content, ed25519_pk, ed25519_sk);
325
326 if (openpgp_result != ASCIICHAT_OK) {
327 return openpgp_result;
328 }
329
330 // Populate private_key_t structure
331 key_out->type = KEY_TYPE_ED25519;
332 key_out->use_gpg_agent = false;
333 key_out->use_ssh_agent = false;
334
335 // Store keypair in Ed25519 format (64 bytes: 32-byte seed + 32-byte public key)
336 // libsodium expects the seed in first 32 bytes and public key in second 32 bytes
337 memcpy(key_out->key.ed25519, ed25519_sk, ED25519_SEED_SIZE); // Secret key (seed)
338 memcpy(key_out->key.ed25519 + ED25519_SEED_SIZE, ed25519_pk, ED25519_PUBLIC_KEY_SIZE); // Public key
339 memcpy(key_out->public_key, ed25519_pk, ED25519_PUBLIC_KEY_SIZE); // Also store in public_key field
340
341 // Store comment
342 safe_snprintf(key_out->key_comment, sizeof(key_out->key_comment), "GPG Ed25519 key from %s", key_path);
343
344 log_debug("Loaded unencrypted GPG Ed25519 key from %s", key_path);
345 return ASCIICHAT_OK;
346 }
347
348 uint8_t first_packet = bytes_read > 0 ? (uint8_t)header[0] : 0;
349 unsigned int first_packet_tag = (first_packet & 0x80u) ? ((first_packet & 0x40u) ? (first_packet & 0x3fu) : ((first_packet >> 2) & 0x0fu)) : 0u;
350 if (bytes_read > 0 && first_packet_tag == 5u) {
351 f = platform_fopen("file_stream", normalized_path, "rb");
352 if (!f) {
353 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to open binary OpenPGP key file: %s", key_path);
354 }
355 if (fseek(f, 0, SEEK_END) != 0) {
356 (void)fclose(f);
357
358 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to seek binary OpenPGP key file: %s", key_path);
359 }
360 long file_size = ftell(f);
361 if (file_size <= 0 || file_size > 1024 * 1024 || fseek(f, 0, SEEK_SET) != 0) {
362 (void)fclose(f);
363
364 return SET_ERRNO(ERROR_CRYPTO_KEY, "Invalid binary OpenPGP key file size: %ld bytes", file_size);
365 }
366 SAFE_MALLOC_DEFER_FREE(file_content, (size_t)file_size, uint8_t *);
367 size_t content_read = fread(file_content, 1, (size_t)file_size, f);
368 (void)fclose(f);
369 if (content_read != (size_t)file_size) {
370 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to read binary OpenPGP key file: %s", key_path);
371 }
372
374 uint8_t ed25519_sk[ED25519_SEED_SIZE];
375 asciichat_error_t openpgp_result = openpgp_parse_binary_seckey(file_content, content_read, ed25519_pk, ed25519_sk);
376 sodium_memzero(file_content, content_read);
377
378 if (openpgp_result != ASCIICHAT_OK)
379 return openpgp_result;
380
381 key_out->type = KEY_TYPE_ED25519;
382 key_out->use_gpg_agent = false;
383 key_out->use_ssh_agent = false;
384 memcpy(key_out->key.ed25519, ed25519_sk, ED25519_SEED_SIZE);
385 memcpy(key_out->key.ed25519 + ED25519_SEED_SIZE, ed25519_pk, ED25519_PUBLIC_KEY_SIZE);
386 memcpy(key_out->public_key, ed25519_pk, ED25519_PUBLIC_KEY_SIZE);
387 safe_snprintf(key_out->key_comment, sizeof(key_out->key_comment), "GPG Ed25519 key from %s", key_path);
388 sodium_memzero(ed25519_sk, sizeof(ed25519_sk));
389 return ASCIICHAT_OK;
390 }
391
392 // Fall back to SSH private key parsing
393 asciichat_error_t result = parse_ssh_private_key(normalized_path, key_out);
394
395 return result;
396}
397
398// =============================================================================
399// Multi-Key Public Key Parsing
400// =============================================================================
401
402asciichat_error_t parse_public_keys(const char *input, public_key_t *keys_out, size_t *num_keys, size_t max_keys) {
403 if (!input || !keys_out || !num_keys || max_keys == 0) {
404 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters for multi-key parsing");
405 }
406
407 *num_keys = 0;
408
409 // Handle comma-separated key specifiers
410 if (strchr(input, ',') != NULL) {
411 size_t input_len = strlen(input);
412 char *input_copy = SAFE_MALLOC(input_len + 1, char *);
413 memcpy(input_copy, input, input_len + 1);
414
415 char *saveptr = NULL;
416 char *specifier = platform_strtok_r(input_copy, ",", &saveptr);
417
418 while (specifier != NULL && *num_keys < max_keys) {
419 // Trim leading/trailing whitespace
420 while (*specifier && isspace((unsigned char)*specifier)) {
421 specifier++;
422 }
423 char *end = specifier + strlen(specifier) - 1;
424 while (end > specifier && isspace((unsigned char)*end)) {
425 *end-- = '\0';
426 }
427
428 // Skip empty specifiers
429 if (strlen(specifier) > 0) {
430 // Recursively parse this single specifier (will not re-enter comma handling)
431 size_t current_num = 0;
432 asciichat_error_t result = parse_public_keys(specifier, &keys_out[*num_keys], &current_num, max_keys - *num_keys);
433 if (result == ASCIICHAT_OK && current_num > 0) {
434 *num_keys += current_num;
435 } else {
436 log_warn("Failed to parse key specifier: %s", specifier);
437 // Continue parsing remaining specifiers even if one fails
438 }
439 }
440
441 specifier = platform_strtok_r(NULL, ",", &saveptr);
442 }
443
444 SAFE_FREE(input_copy);
445
446 if (*num_keys == 0) {
447 return SET_ERRNO(ERROR_CRYPTO_KEY, "No valid keys found in comma-separated list: %s", input);
448 }
449 return ASCIICHAT_OK;
450 }
451
452 // Check for direct SSH Ed25519 key format BEFORE checking for file paths
453 // (SSH keys can contain '/' in base64, which would match path_looks_like_path)
454 if (strncmp(input, "ssh-ed25519", 11) == 0) {
455 asciichat_error_t result = parse_public_key(input, &keys_out[0]);
456 if (result == ASCIICHAT_OK) {
457 *num_keys = 1;
458 }
459 return result;
460 }
461
462 // Check if this is a GitHub/GitLab reference - these support multiple keys
463 if (strncmp(input, "github:", 7) == 0 || strncmp(input, "gitlab:", 7) == 0) {
464 const char *username = input + 7; // Skip "github:" or "gitlab:"
465 bool is_github = (strncmp(input, "github:", 7) == 0);
466 bool is_gpg = (strstr(username, ".gpg") != NULL);
467
468 char **keys = NULL;
469 size_t num_fetched_keys = 0;
470 asciichat_error_t result;
471
472 if (is_github) {
473 if (is_gpg) {
474 result = fetch_github_gpg_keys(username, &keys, &num_fetched_keys);
475 } else {
476 result = fetch_github_ssh_keys(username, &keys, &num_fetched_keys);
477 }
478 } else {
479 if (is_gpg) {
480 result = fetch_gitlab_gpg_keys(username, &keys, &num_fetched_keys);
481 } else {
482 result = fetch_gitlab_ssh_keys(username, &keys, &num_fetched_keys);
483 }
484 }
485
486 if (result != ASCIICHAT_OK || num_fetched_keys == 0) {
487 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to fetch keys from %s for user: %s", is_github ? "GitHub" : "GitLab", username);
488 }
489
490 // Parse each fetched key (only Ed25519 keys will succeed)
491 for (size_t i = 0; i < num_fetched_keys && *num_keys < max_keys; i++) {
492 if (parse_public_key(keys[i], &keys_out[*num_keys]) == ASCIICHAT_OK) {
493 (*num_keys)++;
494 }
495 // Non-Ed25519 keys are silently skipped
496 }
497
498 // Free the keys array
499 for (size_t i = 0; i < num_fetched_keys; i++) {
500 SAFE_FREE(keys[i]);
501 }
502 SAFE_FREE(keys);
503
504 if (*num_keys == 0) {
505 return SET_ERRNO(ERROR_CRYPTO_KEY, "No valid Ed25519 keys found for %s user: %s", is_github ? "GitHub" : "GitLab", username);
506 }
507
508 log_debug("Parsed %zu Ed25519 key(s) from %s user: %s", *num_keys, is_github ? "GitHub" : "GitLab", username);
509 return ASCIICHAT_OK;
510 }
511
512 // For file paths, delegate to parse_keys_from_file
513 if (path_looks_like_path(input)) {
514 return parse_keys_from_file(input, keys_out, num_keys, max_keys);
515 }
516
517 // For all other formats, use single-key parsing
518 asciichat_error_t result = parse_public_key(input, &keys_out[0]);
519 if (result == ASCIICHAT_OK) {
520 *num_keys = 1;
521 }
522 return result;
523}
524
525// =============================================================================
526// Key Conversion Functions
527// =============================================================================
528
530 if (!key || !x25519_pk) {
531 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters");
532 }
533
534 if (key->type == KEY_TYPE_X25519) {
535 // Passthrough for X25519 keys
536 memcpy(x25519_pk, key->key, X25519_KEY_SIZE);
537 return ASCIICHAT_OK;
538 }
539
540 if (key->type == KEY_TYPE_ED25519) {
541 // Convert Ed25519 to X25519
542 return ed25519_to_x25519_public(key->key, x25519_pk);
543 }
544
545 return SET_ERRNO(ERROR_CRYPTO_KEY, "Unsupported key type for X25519 conversion: %d", key->type);
546}
547
549 if (!key || !x25519_sk) {
550 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters");
551 }
552
553 if (key->type == KEY_TYPE_X25519) {
554 // Passthrough for X25519 keys
555 memcpy(x25519_sk, key->key.x25519, X25519_KEY_SIZE);
556 return ASCIICHAT_OK;
557 }
558
559 if (key->type == KEY_TYPE_ED25519) {
560 // Convert Ed25519 to X25519 (Ed25519 private key is 64 bytes: seed + public)
561 return ed25519_to_x25519_private(key->key.ed25519, x25519_sk);
562 }
563
564 return SET_ERRNO(ERROR_CRYPTO_KEY, "Unsupported key type for X25519 conversion: %d", key->type);
565}
566
567// =============================================================================
568// HTTPS Key Fetching Wrapper Functions
569// =============================================================================
570
571asciichat_error_t fetch_github_keys(const char *username, char ***keys_out, size_t *num_keys, bool use_gpg) {
572 if (!username || !keys_out || !num_keys) {
573 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters");
574 }
575
576 if (use_gpg) {
577 return fetch_github_gpg_keys(username, keys_out, num_keys);
578 } else {
579 return fetch_github_ssh_keys(username, keys_out, num_keys);
580 }
581}
582
583asciichat_error_t fetch_gitlab_keys(const char *username, char ***keys_out, size_t *num_keys, bool use_gpg) {
584 if (!username || !keys_out || !num_keys) {
585 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters");
586 }
587
588 if (use_gpg) {
589 return fetch_gitlab_gpg_keys(username, keys_out, num_keys);
590 } else {
591 return fetch_gitlab_ssh_keys(username, keys_out, num_keys);
592 }
593}
594
595// =============================================================================
596// Key Formatting Functions
597// =============================================================================
598
599asciichat_error_t parse_keys_from_file(const char *path, public_key_t *keys, size_t *num_keys, size_t max_keys) {
600 if (!path || !keys || !num_keys || max_keys == 0) {
601 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters for key file parsing");
602 }
603
604 *num_keys = 0;
605
606 if (!path_looks_like_path(path)) {
607 return SET_ERRNO(ERROR_CRYPTO_KEY, "Invalid keys file path: %s", path);
608 }
609
610 char *normalized_path = NULL;
611 defer(SAFE_FREE(normalized_path));
612 asciichat_error_t path_result = path_validate_user_path(path, PATH_ROLE_CLIENT_KEYS, &normalized_path);
613 if (path_result != ASCIICHAT_OK) {
614 return path_result;
615 }
616
617 FILE *f = platform_fopen("file_stream", normalized_path, "rb");
618 if (!f) {
619 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to open keys file: %s", path);
620 }
621
622 defer(SAFE_FCLOSE(f));
623
624 char line[BUFFER_SIZE_LARGE];
625 bool has_first_line = fgets(line, sizeof(line), f) != NULL;
626 uint8_t first_packet = has_first_line ? (uint8_t)line[0] : 0;
627 unsigned int first_packet_tag = (first_packet & 0x80u) ? ((first_packet & 0x40u) ? (first_packet & 0x3fu) : ((first_packet >> 2) & 0x0fu)) : 0u;
628 if (has_first_line && (strstr(line, "-----BEGIN PGP PUBLIC KEY BLOCK-----") != NULL || first_packet_tag == 6u)) {
629 if (fseek(f, 0, SEEK_END) != 0) {
630 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to seek OpenPGP key file: %s", path);
631 }
632 long file_size = ftell(f);
633 if (file_size <= 0 || file_size > 1024 * 1024 || fseek(f, 0, SEEK_SET) != 0) {
634 return SET_ERRNO(ERROR_CRYPTO_KEY, "Invalid OpenPGP key file size: %ld bytes", file_size);
635 }
636 SAFE_MALLOC_DEFER_FREE(armored_key, (size_t)file_size + 1, char *);
637 size_t bytes_read = fread(armored_key, 1, (size_t)file_size, f);
638
639 if (bytes_read != (size_t)file_size) {
640 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to read OpenPGP key file: %s", path);
641 }
642 asciichat_error_t result;
643 if (first_packet_tag == 6u) {
644 result = parse_gpg_key_binary((const uint8_t *)armored_key, bytes_read, &keys[0]);
645 } else {
646 armored_key[bytes_read] = '\0';
647 result = parse_public_key(armored_key, &keys[0]);
648 }
649
650 if (result == ASCIICHAT_OK)
651 *num_keys = 1;
652 return result;
653 }
654 rewind(f);
655 while (fgets(line, sizeof(line), f) && *num_keys < max_keys) {
656 // Remove newline
657 line[strcspn(line, "\r\n")] = 0;
658
659 // Skip empty lines and comments
660 if (strlen(line) == 0 || line[0] == '#') {
661 continue;
662 }
663
664 if (parse_public_key(line, &keys[*num_keys]) == ASCIICHAT_OK) {
665 (*num_keys)++;
666 }
667 }
668
669 return ASCIICHAT_OK;
670}
671
672void format_public_key(const public_key_t *key, char *output, size_t output_size) {
673 if (!key || !output || output_size == 0) {
674 return;
675 }
676
677 if (key->type == KEY_TYPE_ED25519) {
678 // Format as SSH Ed25519 public key
679 // Simple base64 encoding for 32 bytes = 43 chars + padding
680 // For now, just use hex encoding
681 char hex_key[HEX_STRING_SIZE_32];
682 for (size_t i = 0; i < 32; i++) {
683 char hex_byte[3];
684 safe_snprintf(hex_byte, sizeof(hex_byte), "%02x", key->key[i]);
685 hex_key[i * 2] = hex_byte[0];
686 hex_key[i * 2 + 1] = hex_byte[1];
687 }
688 hex_key[64] = '\0';
689 safe_snprintf(output, output_size, "ssh-ed25519 %s %s", hex_key, key->comment);
690 } else if (key->type == KEY_TYPE_X25519) {
691 // Format as hex X25519 key
692 char hex_key[HEX_STRING_SIZE_32];
693 for (size_t i = 0; i < 32; i++) {
694 char hex_byte[3];
695 safe_snprintf(hex_byte, sizeof(hex_byte), "%02x", key->key[i]);
696 hex_key[i * 2] = hex_byte[0];
697 hex_key[i * 2 + 1] = hex_byte[1];
698 }
699 hex_key[64] = '\0';
700 safe_snprintf(output, output_size, "x25519 %s", hex_key);
701 } else {
702 safe_snprintf(output, output_size, "unknown key type: %d", key->type);
703 }
704}
705
706// =============================================================================
707// Hex Encoding/Decoding Utilities
708// =============================================================================
709
710asciichat_error_t hex_decode(const char *hex, uint8_t *output, size_t output_len) {
711 if (!hex || !output) {
712 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters");
713 }
714
715 size_t hex_len = strlen(hex);
716 size_t expected_hex_len = output_len * 2;
717
718 if (hex_len != expected_hex_len) {
719 return SET_ERRNO(ERROR_INVALID_PARAM, "Hex string length (%zu) doesn't match expected output length (%zu * 2 = %zu)", hex_len, output_len, expected_hex_len);
720 }
721
722 // Decode hex string to binary
723 for (size_t i = 0; i < output_len; i++) {
724 char hex_byte[3] = {hex[i * 2], hex[i * 2 + 1], '\0'};
725 char *endptr;
726 unsigned long byte = strtoul(hex_byte, &endptr, 16);
727
728 // Validate hex character
729 if (*endptr != '\0' || byte > 255) {
730 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid hex character at position %zu: '%c%c'", i * 2, hex[i * 2], hex[i * 2 + 1]);
731 }
732
733 output[i] = (uint8_t)byte;
734 }
735
736 return ASCIICHAT_OK;
737}
Synchronized per-thread pending error stacks and value snapshots. SET_ERRNO pushes,...
#define SET_ERRNO(code,...)
GPG public key export interface.
FILE * platform_fopen(const char *name, const char *filename, const char *mode)
Definition filesystem.c:18
#define BUFFER_SIZE_LARGE
Large buffer size (1024 bytes).
unsigned int uint32_t
#define SAFE_FREE(ptr)
#define SAFE_MALLOC_DEFER_FREE(name, size, cast)
#define SAFE_MALLOC(size, cast)
unsigned char uint8_t
#define SAFE_FCLOSE(fp)
int gpg_get_public_key(const char *key_id, uint8_t *public_key_out, char *keygrip_out)
Get public key from GPG keyring by key ID.
Definition export.c:247
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
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_INVALID_PARAM
uint8_t key[CRYPTO_PUBLIC_KEY_SIZE]
Definition key_types.h:78
asciichat_error_t parse_keys_from_file(const char *path, public_key_t *keys, size_t *num_keys, size_t max_keys)
Parse SSH keys from file (supports authorized_keys and known_hosts formats).
Definition keys.c:599
asciichat_error_t parse_private_key(const char *key_path, private_key_t *key_out)
Parse SSH private key from file.
Definition keys.c:212
asciichat_error_t fetch_gitlab_gpg_keys(const char *username, char ***keys_out, size_t *num_keys)
Fetch GPG keys from GitLab using BearSSL.
Definition https_keys.c:263
uint8_t ed25519[ED25519_PRIVATE_KEY_SIZE]
Definition key_types.h:104
asciichat_error_t fetch_github_ssh_keys(const char *username, char ***keys_out, size_t *num_keys)
Fetch SSH keys from GitHub using HTTPS.
Definition https_keys.c:173
key_type_t type
Definition key_types.h:102
asciichat_error_t fetch_github_gpg_keys(const char *username, char ***keys_out, size_t *num_keys)
Fetch GPG keys from GitHub using BearSSL.
Definition https_keys.c:233
char comment[MAX_COMMENT_LEN]
Definition key_types.h:79
uint8_t x25519[X25519_KEY_SIZE]
Definition key_types.h:105
asciichat_error_t parse_public_keys(const char *input, public_key_t *keys_out, size_t *num_keys, size_t max_keys)
Parse all SSH/GPG public keys from any format (returns all keys).
Definition keys.c:402
bool use_gpg_agent
Definition key_types.h:108
asciichat_error_t fetch_gitlab_ssh_keys(const char *username, char ***keys_out, size_t *num_keys)
Fetch SSH keys from GitLab using HTTPS.
Definition https_keys.c:203
bool use_ssh_agent
Definition key_types.h:107
asciichat_error_t parse_gpg_key(const char *gpg_key_id, public_key_t *key_out)
Parse Ed25519 public key from PGP armored format.
Definition gpg_keys.c:32
char key_comment[MAX_COMMENT_LEN]
Definition key_types.h:110
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
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 hex_decode(const char *hex, uint8_t *output, size_t output_len)
Decode hex string to binary (utility function for testing).
Definition keys.c:710
asciichat_error_t parse_gpg_key_binary(const uint8_t *gpg_key_binary, size_t key_size, public_key_t *key_out)
Parse GPG key from binary format.
Definition gpg_keys.c:78
asciichat_error_t fetch_gitlab_keys(const char *username, char ***keys_out, size_t *num_keys, bool use_gpg)
Fetch SSH/GPG keys from GitLab using BearSSL.
Definition keys.c:583
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
void format_public_key(const public_key_t *key, char *output, size_t output_size)
Convert public key to display format (ssh-ed25519 or x25519 hex).
Definition keys.c:672
key_type_t type
Definition key_types.h:77
asciichat_error_t fetch_github_keys(const char *username, char ***keys_out, size_t *num_keys, bool use_gpg)
Fetch SSH/GPG keys from GitHub using BearSSL.
Definition keys.c:571
union private_key_t::@040247167361101132173265304166142033301213115260 key
@ KEY_TYPE_ED25519
Definition key_types.h:58
@ KEY_TYPE_X25519
Definition key_types.h:59
#define log_warn(...)
Log a WARN message.
Definition log/log.h:615
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:589
char * https_get(const char *hostname, const char *path)
Perform HTTPS GET request.
bool path_looks_like_path(const char *value)
Determine if a string is likely intended to reference the filesystem.
Definition path.c:495
void url_parts_destroy(url_parts_t *parts)
Free parsed URL components.
Definition url.c:299
bool url_is_valid(const char *url)
URL validation using shared parsing and ICU hostname checks.
Definition url.c:156
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
asciichat_error_t url_parse(const char *url, url_parts_t *parts_out)
Parse HTTP(S), WebSocket, and TCP URL into components.
Definition url.c:163
@ PATH_ROLE_CLIENT_KEYS
Definition path.h:327
@ PATH_ROLE_KEY_PUBLIC
Definition path.h:326
@ PATH_ROLE_KEY_PRIVATE
Definition path.h:325
⚙️ Common definitions, error codes, macros, and types shared throughout the application
Simple HTTPS client for fetching public keys from GitHub/GitLab.
#define CRYPTO_KEYS_HEADER_BUFFER_SIZE
Definition keys.c:8
asciichat_error_t public_key_to_x25519(const public_key_t *key, uint8_t x25519_pk[X25519_KEY_SIZE])
Definition keys.c:529
asciichat_error_t private_key_to_x25519(const private_key_t *key, uint8_t x25519_sk[X25519_KEY_SIZE])
Definition keys.c:548
asciichat_error_t openpgp_parse_armored_seckey(const char *armored_text, uint8_t ed25519_pk[ED25519_PUBLIC_KEY_SIZE], uint8_t ed25519_sk[ED25519_SEED_SIZE])
Definition openpgp.c:733
asciichat_error_t openpgp_parse_binary_seckey(const uint8_t *data, size_t data_len, uint8_t ed25519_pk[ED25519_PUBLIC_KEY_SIZE], uint8_t ed25519_sk[ED25519_SEED_SIZE])
Definition openpgp.c:702
OpenPGP (RFC 4880) packet format parser.
📂 Path Manipulation Utilities
#define ED25519_PUBLIC_KEY_SIZE
Ed25519 public key size in bytes.
Definition sizes.h:37
#define MAX_GPG_KEYGRIP_LEN
Definition sizes.h:177
#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 HEX_STRING_SIZE_32
Hex string size for 32-byte values (64 hex chars + null terminator).
Definition sizes.h:158
#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
int platform_strncpy(char *dest, size_t dest_size, const char *src, size_t count)
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 parse_ssh_ed25519_line(const char *line, uint8_t ed25519_pk[ED25519_PUBLIC_KEY_SIZE])
Definition ssh_keys.c:165
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
Structure containing parsed URL components.
Definition url.h:69
char * path
Extracted path, query, and fragment (allocated if present, may be NULL).
Definition url.h:75
char * host
Canonical ASCII hostname or IP address (allocated).
Definition url.h:72
🌐 Production-Grade URL Validation and Parsing