ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
openpgp.c
Go to the documentation of this file.
1
6
7/* Storage capacities in elements; text buffers include the terminating NUL. */
8#define CRYPTO_GPG_OPENPGP_PASSPHRASE_BUFFER_SIZE 512
9#define CRYPTO_GPG_OPENPGP_FPR_OUTPUT_BUFFER_SIZE 4096
10
11#include <recast/defer.h>
15#include <ascii-chat/common.h>
17#include <ascii-chat/log/log.h>
18#include <ascii-chat/log/io.h>
19#include <libplatform/question.h>
20#include <libplatform/compiler.h>
21#include <libplatform/system.h>
22#include <libplatform/terminal.h>
23#include <libplatform/filesystem.h>
24#include <string.h>
25#include <stdlib.h>
26#include <sodium.h>
27#ifndef _WIN32
28#include <unistd.h>
29#include <sys/types.h>
30#include <sys/stat.h>
31#else
32#include <sys/types.h>
33#include <sys/stat.h>
34#endif
35
36// =============================================================================
37// Base64 Decoding for PGP Armor
38// =============================================================================
39
40asciichat_error_t openpgp_base64_decode(const char *base64, size_t base64_len, uint8_t **binary_out, size_t *binary_len) {
41 if (!base64 || !binary_out || !binary_len) {
42 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters for base64 decode");
43 }
44
45 // Remove whitespace from base64 input (PGP armor has newlines)
46 SAFE_MALLOC_DEFER_FREE(clean_base64, base64_len + 1, char *);
47 char *clean_ptr = clean_base64;
48 for (size_t i = 0; i < base64_len; i++) {
49 if (base64[i] != '\n' && base64[i] != '\r' && base64[i] != ' ' && base64[i] != '\t') {
50 *clean_ptr++ = base64[i];
51 }
52 }
53 *clean_ptr = '\0';
54 size_t clean_len = (size_t)(clean_ptr - clean_base64);
55
56 // Allocate max possible output size
57 *binary_out = SAFE_MALLOC(clean_len, uint8_t *);
58
59 const char *end;
60 int result = sodium_base642bin(*binary_out, clean_len, clean_base64, clean_len, NULL, binary_len, &end, sodium_base64_VARIANT_ORIGINAL);
61
62 if (result != 0) {
63 SAFE_FREE(*binary_out);
64 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to decode base64 PGP armored data");
65 }
66
67 return ASCIICHAT_OK;
68}
69
70// =============================================================================
71// OpenPGP Packet Header Parsing
72// =============================================================================
73
75 if (!data || !header || data_len == 0) {
76 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters for packet header parsing");
77 }
78
79 memset(header, 0, sizeof(openpgp_packet_header_t));
80
81 uint8_t ctb = data[0]; // Cipher Type Byte
82
83 // Check if bit 7 is set (all packets must have bit 7 = 1)
84 if ((ctb & 0x80) == 0) {
85 return SET_ERRNO(ERROR_CRYPTO_KEY, "Invalid OpenPGP packet: bit 7 not set in CTB");
86 }
87
88 // Check if new format (bit 6 = 1) or old format (bit 6 = 0)
89 if (ctb & 0x40) {
90 // New format: bits 5-0 = tag
91 header->new_format = true;
92 header->tag = ctb & 0x3F;
93
94 if (data_len < 2) {
95 return SET_ERRNO(ERROR_CRYPTO_KEY, "Insufficient data for new format packet header");
96 }
97
98 uint8_t len_byte = data[1];
99
100 if (len_byte < 192) {
101 // One-octet length
102 header->length = len_byte;
103 header->header_len = 2;
104 } else if (len_byte < 224) {
105 // Two-octet length
106 if (data_len < 3) {
107 return SET_ERRNO(ERROR_CRYPTO_KEY, "Insufficient data for two-octet length");
108 }
109 header->length = ((len_byte - 192) << 8) + data[2] + 192;
110 header->header_len = 3;
111 } else if (len_byte == 255) {
112 // Five-octet length
113 if (data_len < 6) {
114 return SET_ERRNO(ERROR_CRYPTO_KEY, "Insufficient data for five-octet length");
115 }
116 header->length = ((size_t)data[2] << 24) | ((size_t)data[3] << 16) | ((size_t)data[4] << 8) | data[5];
117 header->header_len = 6;
118 } else {
119 // Partial body length (not supported for our use case)
120 return SET_ERRNO(ERROR_CRYPTO_KEY, "Partial body length not supported");
121 }
122 } else {
123 // Old format: bits 5-2 = tag, bits 1-0 = length type
124 header->new_format = false;
125 header->tag = (ctb >> 2) & 0x0F;
126 uint8_t length_type = ctb & 0x03;
127
128 switch (length_type) {
129 case 0: // One-octet length
130 if (data_len < 2) {
131 return SET_ERRNO(ERROR_CRYPTO_KEY, "Insufficient data for one-octet length");
132 }
133 header->length = data[1];
134 header->header_len = 2;
135 break;
136
137 case 1: // Two-octet length
138 if (data_len < 3) {
139 return SET_ERRNO(ERROR_CRYPTO_KEY, "Insufficient data for two-octet length");
140 }
141 header->length = ((size_t)data[1] << 8) | data[2];
142 header->header_len = 3;
143 break;
144
145 case 2: // Four-octet length
146 if (data_len < 5) {
147 return SET_ERRNO(ERROR_CRYPTO_KEY, "Insufficient data for four-octet length");
148 }
149 header->length = ((size_t)data[1] << 24) | ((size_t)data[2] << 16) | ((size_t)data[3] << 8) | data[4];
150 header->header_len = 5;
151 break;
152
153 case 3: // Indeterminate length (not supported)
154 return SET_ERRNO(ERROR_CRYPTO_KEY, "Indeterminate length not supported");
155
156 default:
157 return SET_ERRNO(ERROR_CRYPTO_KEY, "Invalid length type: %u", length_type);
158 }
159 }
160
161 log_debug("OpenPGP packet: tag=%u, length=%zu, header_len=%zu, new_format=%d", header->tag, header->length, header->header_len, header->new_format);
162
163 return ASCIICHAT_OK;
164}
165
166// =============================================================================
167// MPI (Multi-Precision Integer) Parsing
168// =============================================================================
169
171 if (!mpi || !ed25519_pk || mpi_len < 35) {
172 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters for MPI extraction (need at least 35 bytes)");
173 }
174
175 // MPI format:
176 // - 2 bytes: bit count (big-endian)
177 // - 1 byte: 0x40 prefix (Ed25519 marker)
178 // - 32 bytes: Ed25519 public key
179
180 uint16_t bit_count = ((uint16_t)mpi[0] << 8) | mpi[1];
181 log_debug("MPI bit count: %u", bit_count);
182
183 // Ed25519 with 0x40 prefix is typically 263 bits (0x0107)
184 if (bit_count < 256 || bit_count > 270) {
185 return SET_ERRNO(ERROR_CRYPTO_KEY, "Unexpected MPI bit count for Ed25519: %u (expected ~263)", bit_count);
186 }
187
188 // Check for 0x40 prefix byte
189 if (mpi[2] != 0x40) {
190 return SET_ERRNO(ERROR_CRYPTO_KEY, "Missing 0x40 prefix byte in Ed25519 MPI (found 0x%02x)", mpi[2]);
191 }
192
193 // Extract 32-byte Ed25519 public key
194 memcpy(ed25519_pk, mpi + 3, ED25519_PUBLIC_KEY_SIZE);
195
196 return ASCIICHAT_OK;
197}
198
199// =============================================================================
200// Public Key Packet Parsing
201// =============================================================================
202
204 if (!packet_body || !pubkey || body_len < 6) {
205 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters for public key packet parsing");
206 }
207
208 memset(pubkey, 0, sizeof(openpgp_public_key_t));
209
210 size_t offset = 0;
211
212 // Version (1 byte, must be 4)
213 pubkey->version = packet_body[offset++];
214 if (pubkey->version != 4) {
215 return SET_ERRNO(ERROR_CRYPTO_KEY, "Unsupported OpenPGP public key version: %u (only version 4 supported)", pubkey->version);
216 }
217
218 // Creation time (4 bytes, big-endian Unix timestamp)
219 pubkey->created = ((uint32_t)packet_body[offset] << 24) | ((uint32_t)packet_body[offset + 1] << 16) | ((uint32_t)packet_body[offset + 2] << 8) | packet_body[offset + 3];
220 offset += 4;
221
222 // Algorithm (1 byte)
223 pubkey->algorithm = packet_body[offset++];
224
225 log_debug("Public key packet: version=%u, created=%u, algorithm=%u", pubkey->version, pubkey->created, pubkey->algorithm);
226
227 // Only support EdDSA (algorithm 22)
228 if (pubkey->algorithm != OPENPGP_ALGO_EDDSA) {
229 return SET_ERRNO(ERROR_CRYPTO_KEY, "Unsupported public key algorithm: %u (only EdDSA/22 supported)", pubkey->algorithm);
230 }
231
232 // EdDSA (Ed25519) keys have a special encoding:
233 // - OID for the curve (variable length)
234 // - 0x40 prefix byte
235 // - 32 bytes of Ed25519 public key
236 //
237 // We search for the 0x40 prefix and extract the following 32 bytes
238
239 // Search for 0x40 prefix byte in the remaining packet data
240 bool found_prefix = false;
241 size_t key_offset = 0;
242
243 for (size_t i = offset; i < body_len - 32; i++) {
244 if (packet_body[i] == 0x40) {
245 key_offset = i + 1; // Point to first byte after 0x40
246 found_prefix = true;
247 log_debug("Found Ed25519 key prefix 0x40 at offset %zu", i);
248 break;
249 }
250 }
251
252 if (!found_prefix) {
253 return SET_ERRNO(ERROR_CRYPTO_KEY, "Ed25519 public key prefix (0x40) not found in packet");
254 }
255
256 if (key_offset + 32 > body_len) {
257 return SET_ERRNO(ERROR_CRYPTO_KEY, "Insufficient data for Ed25519 public key (need 32 bytes after 0x40 prefix)");
258 }
259
260 // Extract the 32-byte Ed25519 public key
261 memcpy(pubkey->pubkey, packet_body + key_offset, ED25519_PUBLIC_KEY_SIZE);
262
263 // Calculate Key ID (last 8 bytes of SHA-1 fingerprint)
264 // For now, we'll skip fingerprint calculation and just extract from packet if available
265 // The keyid is typically at a fixed offset for Ed25519 keys
266 // We'll compute it properly by hashing the public key material
267
268 // For version 4 keys, fingerprint = SHA-1(0x99 || length || packet_body)
269 // Key ID = last 8 bytes of fingerprint
270 // For simplicity, we'll set keyid to 0 for now (not critical for our use case)
271 pubkey->keyid = 0;
272
273 return ASCIICHAT_OK;
274}
275
276// =============================================================================
277// PGP Armored Format Parsing
278// =============================================================================
279
281 if (!data || data_len == 0 || !ed25519_pk) {
282 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters for binary OpenPGP public-key parsing");
283 }
284
285 size_t offset = 0;
286 while (offset < data_len) {
288 asciichat_error_t result = openpgp_parse_packet_header(data + offset, data_len - offset, &header);
289 if (result != ASCIICHAT_OK)
290 return result;
291 if (header.header_len > data_len - offset || header.length > data_len - offset - header.header_len) {
292 return SET_ERRNO(ERROR_CRYPTO_KEY, "Truncated OpenPGP packet in public key");
293 }
294 if (header.tag == OPENPGP_TAG_PUBLIC_KEY) {
296 result = openpgp_parse_public_key_packet(data + offset + header.header_len, header.length, &pubkey);
297 if (result == ASCIICHAT_OK) {
298 memcpy(ed25519_pk, pubkey.pubkey, ED25519_PUBLIC_KEY_SIZE);
299 return ASCIICHAT_OK;
300 }
301 }
302 offset += header.header_len + header.length;
303 }
304 return SET_ERRNO(ERROR_CRYPTO_KEY, "No Ed25519 public key found in OpenPGP data");
305}
306
308 if (!armored_text || !ed25519_pk) {
309 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters for armored pubkey parsing");
310 }
311
312 // Find the BEGIN marker
313 const char *begin = strstr(armored_text, "-----BEGIN PGP PUBLIC KEY BLOCK-----");
314 if (!begin) {
315 return SET_ERRNO(ERROR_CRYPTO_KEY, "Missing PGP PUBLIC KEY BLOCK BEGIN marker");
316 }
317
318 // Skip to the end of the BEGIN line
319 const char *base64_start = strchr(begin, '\n');
320 if (!base64_start) {
321 return SET_ERRNO(ERROR_CRYPTO_KEY, "Invalid PGP armored format: no newline after BEGIN marker");
322 }
323 base64_start++; // Skip the newline
324
325 // Find the END marker
326 const char *end = strstr(base64_start, "-----END PGP PUBLIC KEY BLOCK-----");
327 if (!end) {
328 return SET_ERRNO(ERROR_CRYPTO_KEY, "Missing PGP PUBLIC KEY BLOCK END marker");
329 }
330
331 // Find the checksum line (starts with '=') and exclude it
332 const char *base64_end = end;
333 const char *checksum = base64_end;
334 while (checksum > base64_start && *checksum != '=') {
335 checksum--;
336 }
337 if (*checksum == '=') {
338 // Move back to before the checksum line
339 while (checksum > base64_start && (checksum[-1] == '\n' || checksum[-1] == '\r')) {
340 checksum--;
341 }
342 base64_end = checksum;
343 }
344
345 size_t base64_len = (size_t)(base64_end - base64_start);
346
347 log_debug("Extracting base64 data from PGP armor (%zu bytes)", base64_len);
348
349 // Decode base64 to binary OpenPGP packets
350 uint8_t *binary_data;
351 size_t binary_len;
352 asciichat_error_t decode_result = openpgp_base64_decode(base64_start, base64_len, &binary_data, &binary_len);
353 if (decode_result != ASCIICHAT_OK) {
354 return decode_result;
355 }
356
357 defer(SAFE_FREE(binary_data));
358 log_debug("Decoded %zu bytes of OpenPGP packet data", binary_len);
359
360 asciichat_error_t result = openpgp_parse_binary_pubkey(binary_data, binary_len, ed25519_pk);
361 return result;
362}
363
364// =============================================================================
365// Secret Key Packet Parsing
366// =============================================================================
367
369 if (!packet_body || !seckey || body_len < 6) {
370 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters for secret key packet parsing");
371 }
372
373 memset(seckey, 0, sizeof(openpgp_secret_key_t));
374
375 size_t offset = 0;
376
377 // Parse public key portion (same as public key packet)
378 // Version (1 byte, must be 4)
379 seckey->version = packet_body[offset++];
380 if (seckey->version != 4) {
381 return SET_ERRNO(ERROR_CRYPTO_KEY, "Unsupported OpenPGP secret key version: %u (only version 4 supported)", seckey->version);
382 }
383
384 // Creation time (4 bytes, big-endian Unix timestamp)
385 seckey->created = ((uint32_t)packet_body[offset] << 24) | ((uint32_t)packet_body[offset + 1] << 16) | ((uint32_t)packet_body[offset + 2] << 8) | packet_body[offset + 3];
386 offset += 4;
387
388 // Algorithm (1 byte)
389 seckey->algorithm = packet_body[offset++];
390
391 log_debug("Secret key packet: version=%u, created=%u, algorithm=%u", seckey->version, seckey->created, seckey->algorithm);
392
393 // Only support EdDSA (algorithm 22)
394 if (seckey->algorithm != OPENPGP_ALGO_EDDSA) {
395 return SET_ERRNO(ERROR_CRYPTO_KEY, "Unsupported secret key algorithm: %u (only EdDSA/22 supported)", seckey->algorithm);
396 }
397
398 // EdDSA public key: OID + 0x40 prefix + 32 bytes of Ed25519 public key
399 // Search for 0x40 prefix byte
400 bool found_prefix = false;
401 size_t pubkey_offset = 0;
402
403 for (size_t i = offset; i < body_len - 32; i++) {
404 if (packet_body[i] == 0x40) {
405 pubkey_offset = i + 1;
406 found_prefix = true;
407 log_debug("Found Ed25519 public key prefix 0x40 at offset %zu", i);
408 break;
409 }
410 }
411
412 if (!found_prefix) {
413 return SET_ERRNO(ERROR_CRYPTO_KEY, "Ed25519 public key prefix (0x40) not found in secret key packet");
414 }
415
416 if (pubkey_offset + 32 > body_len) {
417 return SET_ERRNO(ERROR_CRYPTO_KEY, "Insufficient data for Ed25519 public key (need 32 bytes after 0x40 prefix)");
418 }
419
420 // Extract the 32-byte Ed25519 public key
421 memcpy(seckey->pubkey, packet_body + pubkey_offset, ED25519_PUBLIC_KEY_SIZE);
422
423 // Move offset past public key material
424 offset = pubkey_offset + 32;
425
426 // S2K usage byte (1 byte)
427 // 0x00 = secret key is not encrypted
428 // 0xFE or 0xFF = secret key is encrypted with S2K
429 if (offset >= body_len) {
430 return SET_ERRNO(ERROR_CRYPTO_KEY, "Missing S2K usage byte in secret key packet");
431 }
432
433 uint8_t s2k_usage = packet_body[offset++];
434 log_debug("S2K usage byte: 0x%02x", s2k_usage);
435
436 if (s2k_usage != 0x00) {
437 seckey->is_encrypted = true;
438 log_debug("Detected encrypted secret key (S2K usage = 0x%02x)", s2k_usage);
439 // Don't parse encrypted key material here - caller will need to decrypt with gpg
440 return ASCIICHAT_OK;
441 }
442
443 seckey->is_encrypted = false;
444
445 // The Ed25519 secret scalar is encoded as an OpenPGP MPI (bit count followed by bytes).
446 if (offset + 2 > body_len) {
447 return SET_ERRNO(ERROR_CRYPTO_KEY, "Missing Ed25519 secret-key MPI length");
448 }
449 uint16_t secret_bits = (uint16_t)(((uint16_t)packet_body[offset] << 8) | packet_body[offset + 1]);
450 size_t secret_bytes = (secret_bits + 7u) / 8u;
451 offset += 2;
452 if (secret_bits == 0 || secret_bits > 256 || secret_bytes > sizeof(seckey->seckey) || offset + secret_bytes + 2 > body_len) {
453 return SET_ERRNO(ERROR_CRYPTO_KEY, "Invalid Ed25519 secret-key MPI length: %u bits", secret_bits);
454 }
455
456 // Ed25519 private material is 32 bytes; left-pad shorter MPIs as specified by OpenPGP.
457 memcpy(seckey->seckey + sizeof(seckey->seckey) - secret_bytes, packet_body + offset, secret_bytes);
458
459 log_debug("Extracted Ed25519 secret key");
460
461 return ASCIICHAT_OK;
462}
463
476#ifndef EMSCRIPTEN_BUILD
477static asciichat_error_t openpgp_decrypt_with_gpg(const char *armored_text, char **decrypted_out) {
478 if (!armored_text || !decrypted_out) {
479 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters for GPG decryption");
480 }
481
482 // Get passphrase from environment variable or interactive prompt
483 const char *passphrase = SAFE_GETENV("ASCII_CHAT_KEY_PASSWORD");
484 char passphrase_buffer[CRYPTO_GPG_OPENPGP_PASSPHRASE_BUFFER_SIZE] = {0};
485
486 if (!passphrase) {
487 // No environment variable - try interactive prompt
489 log_info("GPG key is encrypted - prompting for passphrase");
490 prompt_opts_t prompt_opts = PROMPT_OPTS_PASSWORD;
491 prompt_opts.kind = UI_PROMPT_GPG_PASSPHRASE;
492 if (platform_prompt_question("Enter passphrase for GPG key", passphrase_buffer, sizeof(passphrase_buffer), prompt_opts) != 0) {
493 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to read passphrase for encrypted GPG key");
494 }
495 passphrase = passphrase_buffer;
496 } else {
497 return SET_ERRNO(ERROR_CRYPTO_KEY, "Encrypted GPG key requires passphrase. Set ASCII_CHAT_KEY_PASSWORD environment variable or "
498 "run interactively.");
499 }
500 }
501
502 // Create a temporary GPG homedir (isolated from user's keyring)
504 if (!homedir) {
505 sodium_memzero(passphrase_buffer, sizeof(passphrase_buffer));
506 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to create temporary GPG homedir");
507 }
508
509 // Create temporary files for input (armored key) and output (decrypted key)
510 char input_path[PLATFORM_MAX_PATH_LENGTH];
511 int input_fd = -1;
512 if (platform_create_temp_file(input_path, sizeof(input_path), "asc_gpg_in", &input_fd) != 0) {
513 gpg_homedir_destroy(homedir);
514 sodium_memzero(passphrase_buffer, sizeof(passphrase_buffer));
515 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to create temporary input file");
516 }
517
518#ifdef _WIN32
519 // On Windows, platform_create_temp_file returns fd=-1, need to open separately
520 input_fd = platform_open("gpg_input_file", input_path, O_WRONLY | O_BINARY);
521 if (input_fd < 0) {
522 platform_delete_temp_file(input_path);
523 gpg_homedir_destroy(homedir);
524 sodium_memzero(passphrase_buffer, sizeof(passphrase_buffer));
525 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to open temporary input file");
526 }
527#endif
528
529 // Write armored key to temp file
530 size_t armored_len = strlen(armored_text);
531 ssize_t written = write(input_fd, armored_text, armored_len);
532 close(input_fd);
533
534 if (written != (ssize_t)armored_len) {
535 platform_unlink(input_path);
536 gpg_homedir_destroy(homedir);
537 sodium_memzero(passphrase_buffer, sizeof(passphrase_buffer));
538 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to write armored key to temp file");
539 }
540
541 // Create temporary output file for decrypted key
542 char output_path[PLATFORM_MAX_PATH_LENGTH];
543 int output_fd = -1;
544 if (platform_create_temp_file(output_path, sizeof(output_path), "asc_gpg_out", &output_fd) != 0) {
545 platform_unlink(input_path);
546 gpg_homedir_destroy(homedir);
547 sodium_memzero(passphrase_buffer, sizeof(passphrase_buffer));
548 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to create temporary output file");
549 }
550 if (output_fd >= 0) {
551 close(output_fd);
552 }
553
554 // Use temporary homedir for isolation instead of shell pipeline
555 const char *homedir_path = gpg_homedir_path(homedir);
556
557 // Step 1: Import the key into the temporary homedir
558 log_debug("Importing GPG key into temporary homedir");
559 const char *argv_import[] = {"gpg", "--homedir", homedir_path, "--batch", "--import", input_path, NULL};
560 int status = 0;
561 LOG_IO("gpg", { status = platform_execute_subprocess("gpg", argv_import, NULL, 0, NULL, NULL); });
562
563 // Clean up input file (no longer needed)
564 platform_unlink(input_path);
565
566 if (status != 0) {
567 platform_unlink(output_path);
568 gpg_homedir_destroy(homedir);
569 sodium_memzero(passphrase_buffer, sizeof(passphrase_buffer));
570 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to import GPG key into temporary homedir");
571 }
572
573 // Step 2: Get the key fingerprint from the temporary homedir
574 log_debug("Retrieving GPG key fingerprint");
576 const char *argv_list[] = {"gpg", "--homedir", homedir_path, "--batch", "--list-secret-keys", "--with-colons", NULL};
577 LOG_IO("gpg", { status = platform_execute_subprocess("gpg", argv_list, fpr_output, sizeof(fpr_output), NULL, NULL); });
578
579 if (status != 0) {
580 platform_unlink(output_path);
581 gpg_homedir_destroy(homedir);
582 sodium_memzero(passphrase_buffer, sizeof(passphrase_buffer));
583 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to retrieve GPG key fingerprint");
584 }
585
586 // Parse fingerprint from output: find line starting with "fpr" and extract field 10
587 char key_fpr[GPG_FINGERPRINT_HEX_BUFFER_SIZE] = {0}; // Ed25519 fingerprints are 40 hex chars
588 const char *line = fpr_output;
589 while (*line) {
590 if (strncmp(line, "fpr:", 4) == 0) {
591 // Found fpr line, extract the fingerprint (field 10, colon-separated)
592 int field_count = 0;
593 const char *field_start = line;
594 for (const char *p = line; *p && *p != '\n'; p++) {
595 if (*p == ':') {
596 field_count++;
597 field_start = p + 1;
598 if (field_count == 10) {
599 // Found field 10, copy until next colon or newline
600 size_t fpr_len = 0;
601 while (field_start[fpr_len] && field_start[fpr_len] != ':' && field_start[fpr_len] != '\n' && fpr_len < sizeof(key_fpr) - 1) {
602 fpr_len++;
603 }
604 if (fpr_len > 0 && fpr_len < sizeof(key_fpr)) {
605 safe_snprintf(key_fpr, sizeof(key_fpr), "%.*s", (int)fpr_len, field_start);
606 }
607 break;
608 }
609 }
610 }
611 break;
612 }
613 // Skip to next line
614 while (*line && *line != '\n')
615 line++;
616 if (*line == '\n')
617 line++;
618 }
619
620 if (!key_fpr[0]) {
621 log_error("Could not find GPG key fingerprint in output");
622 platform_unlink(output_path);
623 gpg_homedir_destroy(homedir);
624 sodium_memzero(passphrase_buffer, sizeof(passphrase_buffer));
625 return SET_ERRNO(ERROR_CRYPTO_KEY, "GPG key fingerprint not found in keyring");
626 }
627
628 log_debug("Found GPG key fingerprint: %s", key_fpr);
629
630 // Step 3: Export the secret key using the fingerprint with passphrase
631 log_debug("Exporting decrypted GPG key");
632 const char *argv_export[] = {"gpg",
633 "--homedir",
634 homedir_path,
635 "--batch",
636 "--pinentry-mode",
637 "loopback",
638 "--passphrase",
639 passphrase,
640 "--armor",
641 "--export-secret-keys",
642 "--export-options",
643 "export-minimal,no-export-attributes",
644 "--output",
645 output_path,
646 key_fpr,
647 NULL};
648 LOG_IO("gpg", { status = platform_execute_subprocess("gpg", argv_export, NULL, 0, NULL, NULL); });
649
650 if (status != 0) {
651 platform_unlink(output_path);
652 gpg_homedir_destroy(homedir);
653 sodium_memzero(passphrase_buffer, sizeof(passphrase_buffer));
654 return SET_ERRNO(ERROR_CRYPTO_KEY, "GPG export failed. Check passphrase and key format.");
655 }
656
657 // Read the decrypted output
658 FILE *output_file = platform_fopen("file_stream", output_path, "r");
659 if (!output_file) {
660 platform_unlink(output_path);
661 gpg_homedir_destroy(homedir);
662 sodium_memzero(passphrase_buffer, sizeof(passphrase_buffer));
663 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to read decrypted GPG output");
664 }
665
666 fseek(output_file, 0, SEEK_END);
667 long output_size = ftell(output_file);
668 fseek(output_file, 0, SEEK_SET);
669
670 if (output_size <= 0 || output_size > 1024 * 1024) {
671 fclose(output_file);
672 platform_unlink(output_path);
673 gpg_homedir_destroy(homedir);
674 sodium_memzero(passphrase_buffer, sizeof(passphrase_buffer));
675 return SET_ERRNO(ERROR_CRYPTO_KEY, "Invalid decrypted GPG output size: %ld bytes", output_size);
676 }
677
678 // Read the decrypted key data
679 *decrypted_out = SAFE_MALLOC((size_t)output_size + 1, char *);
680 if (!*decrypted_out) {
681 fclose(output_file);
682 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate memory for decrypted GPG output");
683 }
684 size_t bytes_read = fread(*decrypted_out, 1, (size_t)output_size, output_file);
685 (*decrypted_out)[bytes_read] = '\0';
686 fclose(output_file);
687
688 // Clean up temporary output file
689 platform_unlink(output_path);
690
691 // Clean up temporary GPG homedir (automatic: deletes entire directory)
692 gpg_homedir_destroy(homedir);
693
694 // Securely erase passphrase from memory
695 sodium_memzero(passphrase_buffer, sizeof(passphrase_buffer));
696
697 log_debug("Successfully decrypted GPG key using passphrase");
698 return ASCIICHAT_OK;
699}
700#endif
701
703 if (!data || data_len == 0 || !ed25519_pk || !ed25519_sk) {
704 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters for binary OpenPGP secret-key parsing");
705 }
706
707 size_t offset = 0;
708 while (offset < data_len) {
710 asciichat_error_t result = openpgp_parse_packet_header(data + offset, data_len - offset, &header);
711 if (result != ASCIICHAT_OK)
712 return result;
713 if (header.header_len > data_len - offset || header.length > data_len - offset - header.header_len) {
714 return SET_ERRNO(ERROR_CRYPTO_KEY, "Truncated OpenPGP packet in secret key");
715 }
716 if (header.tag == OPENPGP_TAG_SECRET_KEY) {
718 result = openpgp_parse_secret_key_packet(data + offset + header.header_len, header.length, &seckey);
719 if (result == ASCIICHAT_OK) {
720 if (seckey.is_encrypted) {
721 return SET_ERRNO(ERROR_NOT_SUPPORTED, "Encrypted binary OpenPGP private keys are not supported; use an unencrypted key");
722 }
723 memcpy(ed25519_pk, seckey.pubkey, ED25519_PUBLIC_KEY_SIZE);
724 memcpy(ed25519_sk, seckey.seckey, ED25519_SEED_SIZE);
725 return ASCIICHAT_OK;
726 }
727 }
728 offset += header.header_len + header.length;
729 }
730 return SET_ERRNO(ERROR_CRYPTO_KEY, "No unencrypted Ed25519 secret key found in OpenPGP data");
731}
732
734 if (!armored_text || !ed25519_pk || !ed25519_sk) {
735 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters for armored seckey parsing");
736 }
737
738 // Find the BEGIN marker (try both "PRIVATE KEY" and "SECRET KEY" formats)
739 const char *begin = strstr(armored_text, "-----BEGIN PGP PRIVATE KEY BLOCK-----");
740 if (!begin) {
741 begin = strstr(armored_text, "-----BEGIN PGP SECRET KEY BLOCK-----");
742 }
743 if (!begin) {
744 return SET_ERRNO(ERROR_CRYPTO_KEY, "Missing PGP PRIVATE/SECRET KEY BLOCK BEGIN marker");
745 }
746
747 // Skip to the end of the BEGIN line
748 const char *base64_start = strchr(begin, '\n');
749 if (!base64_start) {
750 return SET_ERRNO(ERROR_CRYPTO_KEY, "Invalid PGP armored format: no newline after BEGIN marker");
751 }
752 base64_start++; // Skip the newline
753
754 // Find the END marker (try both formats)
755 const char *end = strstr(base64_start, "-----END PGP PRIVATE KEY BLOCK-----");
756 if (!end) {
757 end = strstr(base64_start, "-----END PGP SECRET KEY BLOCK-----");
758 }
759 if (!end) {
760 return SET_ERRNO(ERROR_CRYPTO_KEY, "Missing PGP PRIVATE/SECRET KEY BLOCK END marker");
761 }
762
763 // Find the checksum line (starts with '=') and exclude it
764 const char *base64_end = end;
765 const char *checksum = base64_end;
766 while (checksum > base64_start && *checksum != '=') {
767 checksum--;
768 }
769 if (*checksum == '=') {
770 // Move back to before the checksum line
771 while (checksum > base64_start && (checksum[-1] == '\n' || checksum[-1] == '\r')) {
772 checksum--;
773 }
774 base64_end = checksum;
775 }
776
777 size_t base64_len = (size_t)(base64_end - base64_start);
778
779 log_debug("Extracting base64 data from PGP secret key armor (%zu bytes)", base64_len);
780
781 // Decode base64 to binary OpenPGP packets
782 uint8_t *binary_data;
783 size_t binary_len;
784 asciichat_error_t decode_result = openpgp_base64_decode(base64_start, base64_len, &binary_data, &binary_len);
785 if (decode_result != ASCIICHAT_OK) {
786 return decode_result;
787 }
788
789 defer(SAFE_FREE(binary_data));
790
791 log_debug("Decoded %zu bytes of OpenPGP secret key packet data", binary_len);
792
793 // Parse OpenPGP packets to find the secret key packet (tag 5)
794 size_t offset = 0;
795 bool found_seckey = false;
796
797 while (offset < binary_len) {
799 asciichat_error_t header_result = openpgp_parse_packet_header(binary_data + offset, binary_len - offset, &header);
800 if (header_result != ASCIICHAT_OK) {
801 return header_result;
802 }
803
804 log_debug("Packet at offset %zu: tag=%u, length=%zu", offset, header.tag, header.length);
805
806 // Check if this is a secret key packet (tag 5)
807 if (header.tag == OPENPGP_TAG_SECRET_KEY) {
809 asciichat_error_t parse_result = openpgp_parse_secret_key_packet(binary_data + offset + header.header_len, header.length, &seckey);
810
811 if (parse_result == ASCIICHAT_OK) {
812 // Check if key is encrypted
813 if (seckey.is_encrypted) {
814#ifdef EMSCRIPTEN_BUILD
815 return SET_ERRNO(ERROR_NOT_SUPPORTED, "Encrypted OpenPGP private keys are not supported in the browser; use an unencrypted key");
816#else
817 log_debug("Detected encrypted GPG key, attempting to decrypt with passphrase");
818
819 // Decrypt the key using gpg binary
820 char *decrypted_text = NULL;
821 asciichat_error_t decrypt_result = openpgp_decrypt_with_gpg(armored_text, &decrypted_text);
822 if (decrypt_result != ASCIICHAT_OK) {
823 return decrypt_result;
824 }
825
826 // Recursively parse the decrypted key
827 asciichat_error_t recursive_result = openpgp_parse_armored_seckey(decrypted_text, ed25519_pk, ed25519_sk);
828 SAFE_FREE(decrypted_text);
829 return recursive_result;
830#endif
831 }
832
833 // Unencrypted key - extract directly
834 memcpy(ed25519_pk, seckey.pubkey, ED25519_PUBLIC_KEY_SIZE);
835 memcpy(ed25519_sk, seckey.seckey, ED25519_SEED_SIZE);
836 found_seckey = true;
837 log_debug("Extracted Ed25519 keypair from OpenPGP armored secret key block");
838 break;
839 } else {
840 // Not an Ed25519 key, try next packet
841 log_debug("Skipping non-Ed25519 secret key packet");
842 }
843 }
844
845 // Move to next packet
846 offset += header.header_len + header.length;
847 }
848
849 if (!found_seckey) {
850 return SET_ERRNO(ERROR_CRYPTO_KEY, "No Ed25519 secret key found in PGP armored block");
851 }
852
853 return ASCIICHAT_OK;
854}
Synchronized per-thread pending error stacks and value snapshots. SET_ERRNO pushes,...
#define SET_ERRNO(code,...)
bool platform_is_interactive(void)
int platform_open(const char *name, const char *pathname, int flags,...)
Definition filesystem.c:65
FILE * platform_fopen(const char *name, const char *filename, const char *mode)
Definition filesystem.c:18
unsigned short uint16_t
unsigned int uint32_t
#define SAFE_FREE(ptr)
#define SAFE_MALLOC_DEFER_FREE(name, size, cast)
#define SAFE_MALLOC(size, cast)
#define SAFE_GETENV(name)
#define PLATFORM_MAX_PATH_LENGTH
unsigned char uint8_t
#define OPENPGP_TAG_SECRET_KEY
OpenPGP packet tag for Secret Key Packet.
Definition openpgp.h:52
asciichat_error_t openpgp_base64_decode(const char *base64, size_t base64_len, uint8_t **binary_out, size_t *binary_len)
Decode PGP armored base64 data.
Definition openpgp.c:40
asciichat_error_t openpgp_parse_packet_header(const uint8_t *data, size_t data_len, openpgp_packet_header_t *header)
Parse OpenPGP packet header.
Definition openpgp.c:74
asciichat_error_t openpgp_parse_public_key_packet(const uint8_t *packet_body, size_t body_len, openpgp_public_key_t *pubkey)
Parse OpenPGP Public Key Packet (tag 6).
Definition openpgp.c:203
#define OPENPGP_TAG_PUBLIC_KEY
OpenPGP packet tag for Public Key Packet.
Definition openpgp.h:49
asciichat_error_t openpgp_parse_secret_key_packet(const uint8_t *packet_body, size_t body_len, openpgp_secret_key_t *seckey)
Parse OpenPGP Secret Key Packet (tag 5).
Definition openpgp.c:368
#define OPENPGP_ALGO_EDDSA
OpenPGP algorithm ID for EdDSA (Ed25519).
Definition openpgp.h:61
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_INVALID_PARAM
@ ERROR_NOT_SUPPORTED
Definition error_codes.h:73
#define log_error(...)
Log an ERROR message.
Definition log/log.h:628
#define log_info(...)
Log an INFO message.
Definition log/log.h:602
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:589
const char * gpg_homedir_path(const gpg_homedir_t *homedir)
Get the homedir path for use in GPG commands.
Definition homedir.c:52
void gpg_homedir_destroy(gpg_homedir_t *homedir)
Destroy a temporary GPG homedir and clean up all files.
Definition homedir.c:59
gpg_homedir_t * gpg_homedir_create(void)
Create a temporary GPG homedir for isolated key operations.
Definition homedir.c:24
Temporary GPG homedir management for isolated key operations.
struct gpg_homedir gpg_homedir_t
Opaque handle to a temporary GPG homedir.
Definition homedir.h:45
⚙️ Common definitions, error codes, macros, and types shared throughout the application
Capture stdout/stderr and redirect to logging system.
#define LOG_IO(prefix, block)
Definition io.h:104
📝 Logging API with multiple log levels and terminal output control
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_pubkey(const uint8_t *data, size_t data_len, uint8_t ed25519_pk[ED25519_PUBLIC_KEY_SIZE])
Definition openpgp.c:280
asciichat_error_t openpgp_extract_ed25519_from_mpi(const uint8_t *mpi, size_t mpi_len, uint8_t ed25519_pk[ED25519_PUBLIC_KEY_SIZE])
Definition openpgp.c:170
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
#define CRYPTO_GPG_OPENPGP_FPR_OUTPUT_BUFFER_SIZE
Definition openpgp.c:9
#define CRYPTO_GPG_OPENPGP_PASSPHRASE_BUFFER_SIZE
Definition openpgp.c:8
asciichat_error_t openpgp_parse_armored_pubkey(const char *armored_text, uint8_t ed25519_pk[ED25519_PUBLIC_KEY_SIZE])
Definition openpgp.c:307
OpenPGP (RFC 4880) packet format parser.
#define GPG_FINGERPRINT_HEX_BUFFER_SIZE
Definition sizes.h:172
#define ED25519_PUBLIC_KEY_SIZE
Ed25519 public key size in bytes.
Definition sizes.h:37
#define ED25519_SEED_SIZE
Definition sizes.h:169
🔤 String Manipulation and Shell Escaping Utilities
The framing fields needed to locate and classify one OpenPGP packet body.
Definition openpgp.h:81
The parsed identity portion of an OpenPGP public-key packet.
Definition openpgp.h:104
uint64_t keyid
OpenPGP Key ID (last 8 bytes of fingerprint).
Definition openpgp.h:109
uint32_t created
Creation timestamp (Unix epoch).
Definition openpgp.h:106
uint8_t pubkey[32]
Ed25519 public key (32 bytes).
Definition openpgp.h:108
uint8_t algorithm
Public key algorithm (22 = EdDSA).
Definition openpgp.h:107
uint8_t version
Packet version (should be 4).
Definition openpgp.h:105
The parsed public and private material from an OpenPGP secret-key packet.
Definition openpgp.h:128
uint8_t seckey[32]
Ed25519 secret key (32 bytes).
Definition openpgp.h:133
uint8_t pubkey[32]
Ed25519 public key (32 bytes).
Definition openpgp.h:132
bool is_encrypted
True if secret key material is encrypted.
Definition openpgp.h:135
uint32_t created
Creation timestamp (Unix epoch).
Definition openpgp.h:130
uint8_t algorithm
Public key algorithm (22 = EdDSA).
Definition openpgp.h:131
uint8_t version
Packet version (should be 4).
Definition openpgp.h:129
int platform_execute_subprocess(const char *executable, const char **argv, char *output_buffer, size_t output_size, bool(*cancel)(void *), void *data)
Definition system.c:35