ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
export.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_EXPORT_FOUND_KEYGRIP_BUFFER_SIZE 128
9
10/* Existing buffer budgets in bytes, including NUL for text storage. */
11#define GPG_EXPORT_PACKET_CAPACITY 8192
12
18#include <ascii-chat/common.h>
21#include <ascii-chat/log/log.h>
22#include <ascii-chat/log/io.h>
23#include <libplatform/system.h>
24#include <libplatform/filesystem.h>
25#include <libplatform/process.h>
26#include <libplatform/pipe.h>
27
28#include <ctype.h>
29#include <errno.h>
30#include <stdio.h>
31#include <stdlib.h>
32#include <string.h>
33#ifndef _WIN32
34#include <unistd.h>
35#endif
36
47static int gpg_export_public_key(const char *key_id, uint8_t *public_key_out) {
48 if (!key_id || !public_key_out) {
49 log_error("Invalid arguments");
50 return -1;
51 }
52
53 // Create temp file for exported key
54 char temp_path[PLATFORM_MAX_PATH_LENGTH];
55 int temp_fd = -1;
56 if (platform_create_temp_file(temp_path, sizeof(temp_path), "asciichat_gpg_export", &temp_fd) != 0) {
57 log_error("Failed to create temp file for GPG export");
58 return -1;
59 }
60 if (temp_fd >= 0) {
61 close(temp_fd);
62 }
63
64 // Use gpg --export to export the public key in binary format
65 const char *argv[] = {"gpg", "--batch", "--yes", "--output", temp_path, "--export", key_id, NULL};
66 int result = 0;
67 LOG_IO("gpg", { result = platform_execute_subprocess("gpg", argv, NULL, 0, NULL, NULL); });
68 if (result != 0) {
69 log_error("Failed to export GPG public key for key ID: %s (exit code: %d)", key_id, result);
70 platform_delete_temp_file(temp_path);
71 return -1;
72 }
73 log_debug("GPG export completed successfully");
74
75 // Read the exported key file
76 FILE *fp = platform_fopen("file_stream", temp_path, "rb");
77 if (!fp) {
78 log_error("Failed to open exported GPG key file");
79 platform_delete_temp_file(temp_path);
80 return -1;
81 }
82
83 // Read up to 8KB (should be more than enough for a public key packet)
85 size_t bytes_read = fread(packet_data, 1, sizeof(packet_data), fp);
86 fclose(fp);
87 platform_delete_temp_file(temp_path);
88
89 if (bytes_read == 0) {
90 log_error("GPG export produced empty output - key may not exist");
91 return -1;
92 }
93
94 log_debug("Read %zu bytes from GPG export", bytes_read);
95
96 // Parse OpenPGP packet to extract Ed25519 public key
97 // OpenPGP public key packet format (simplified):
98 // - Packet tag (1 byte): 0x99 for public key packet (old format) or 0xC6 (new format)
99 // - Packet length (variable)
100 // - Version (1 byte): 0x04 for modern keys
101 // - Creation time (4 bytes)
102 // - Algorithm (1 byte): 22 (0x16) for EdDSA
103 // - Curve OID length + OID
104 // - Public key material (MPI format)
105
106 size_t offset = 0;
107
108 // Skip to public key packet (tag 6 - public key, or tag 14 - public subkey)
109 while (offset < bytes_read) {
110 uint8_t tag = packet_data[offset];
111
112 // Check if this is a public key packet (old or new format)
113 bool is_public_key = false;
114 size_t packet_len = 0;
115
116 if ((tag & 0x80) == 0) {
117 // Not a valid packet tag
118 offset++;
119 continue;
120 }
121
122 if ((tag & 0x40) == 0) {
123 // Old format packet
124 uint8_t packet_type = (tag >> 2) & 0x0F;
125 is_public_key = (packet_type == 6 || packet_type == 14); // Public key or subkey
126
127 uint8_t length_type = tag & 0x03;
128 offset++; // Move past tag
129
130 if (length_type == 0) {
131 packet_len = packet_data[offset++];
132 } else if (length_type == 1) {
133 packet_len = (packet_data[offset] << 8) | packet_data[offset + 1];
134 offset += 2;
135 } else if (length_type == 2) {
136 packet_len = (packet_data[offset] << 24) | (packet_data[offset + 1] << 16) | (packet_data[offset + 2] << 8) | packet_data[offset + 3];
137 offset += 4;
138 } else {
139 // Indeterminate length - skip
140 break;
141 }
142 } else {
143 // New format packet
144 uint8_t packet_type = tag & 0x3F;
145 is_public_key = (packet_type == 6 || packet_type == 14); // Public key or subkey
146 offset++; // Move past tag
147
148 // Parse new format length
149 if (offset >= bytes_read)
150 break;
151 uint8_t first_len = packet_data[offset++];
152
153 if (first_len < 192) {
154 packet_len = first_len;
155 } else if (first_len < 224) {
156 if (offset >= bytes_read)
157 break;
158 packet_len = ((first_len - 192) << 8) + packet_data[offset++] + 192;
159 } else if (first_len == 255) {
160 if (offset + 4 > bytes_read)
161 break;
162 packet_len = (packet_data[offset] << 24) | (packet_data[offset + 1] << 16) | (packet_data[offset + 2] << 8) | packet_data[offset + 3];
163 offset += 4;
164 } else {
165 // Partial body length - not expected for key packets
166 break;
167 }
168 }
169
170 if (!is_public_key || packet_len == 0 || offset + packet_len > bytes_read) {
171 offset += packet_len;
172 continue;
173 }
174
175 // Parse the public key packet content
176 size_t packet_start = offset;
177
178 // Check version (should be 4)
179 if (packet_data[offset] != 0x04) {
180 offset += packet_len;
181 continue;
182 }
183 offset++; // Skip version
184
185 offset += 4; // Skip creation time
186
187 // Check algorithm (22 = EdDSA/Ed25519)
188 if (offset >= packet_start + packet_len) {
189 offset = packet_start + packet_len;
190 continue;
191 }
192
193 uint8_t algorithm = packet_data[offset++];
194 if (algorithm != 22) { // Not EdDSA
195 offset = packet_start + packet_len;
196 continue;
197 }
198
199 // Skip curve OID (should be Ed25519 OID)
200 if (offset >= packet_start + packet_len) {
201 offset = packet_start + packet_len;
202 continue;
203 }
204
205 uint8_t oid_len = packet_data[offset++];
206 offset += oid_len; // Skip OID bytes
207
208 // Now we should have the MPI-encoded public key
209 // MPI format: 2-byte bit count, then key data
210 if (offset + 2 > packet_start + packet_len) {
211 offset = packet_start + packet_len;
212 continue;
213 }
214
215 uint16_t mpi_bits = (packet_data[offset] << 8) | packet_data[offset + 1];
216 offset += 2;
217
218 // Ed25519 public keys should be 263 bits (0x0107) - includes 0x40 prefix byte
219 // Or 256 bits for just the key without prefix
220 size_t mpi_bytes = (mpi_bits + 7) / 8;
221
222 if (offset + mpi_bytes > packet_start + packet_len) {
223 offset = packet_start + packet_len;
224 continue;
225 }
226
227 // Ed25519 keys in OpenPGP have a 0x40 prefix byte
228 if (mpi_bytes == 33 && packet_data[offset] == 0x40) {
229 // Found it! Extract the 32-byte public key (skip 0x40 prefix)
230 memcpy(public_key_out, &packet_data[offset + 1], ED25519_PUBLIC_KEY_SIZE);
231 log_debug("Extracted Ed25519 public key from gpg --export (fallback method)");
232 return 0;
233 } else if (mpi_bytes == 32) {
234 // Key without prefix (less common but valid)
235 memcpy(public_key_out, &packet_data[offset], ED25519_PUBLIC_KEY_SIZE);
236 log_debug("Extracted Ed25519 public key from gpg --export (fallback method)");
237 return 0;
238 }
239
240 offset = packet_start + packet_len;
241 }
242
243 log_error("Failed to find Ed25519 public key in GPG export data");
244 return -1;
245}
246
247int gpg_get_public_key(const char *key_id, uint8_t *public_key_out, char *keygrip_out) {
248 if (!key_id || !public_key_out) {
249 log_error("Invalid arguments");
250 return -1;
251 }
252
253 // SECURITY: Validate key_id to prevent command injection
254 // GPG key IDs should be hexadecimal (0-9, a-f, A-F)
255 if (!validate_shell_safe(key_id, NULL)) {
256 log_error("Invalid GPG key ID format - contains unsafe characters: %s", key_id);
257 return -1;
258 }
259
260 // Additional validation: ensure key_id is hex alphanumeric
261 for (size_t i = 0; key_id[i] != '\0'; i++) {
262 if (!isxdigit((unsigned char)key_id[i])) {
263 log_error("Invalid GPG key ID format - must be hexadecimal: %s", key_id);
264 return -1;
265 }
266 }
267
268 // Escape key_id for safe use in shell command (single quotes)
269 char escaped_key_id[BUFFER_SIZE_MEDIUM];
270 if (!escape_shell_single_quotes(key_id, escaped_key_id, sizeof(escaped_key_id))) {
271 log_error("Failed to escape GPG key ID for shell command");
272 return -1;
273 }
274
275 // Use gpg to list the key and get the keygrip
276 char cmd[BUFFER_SIZE_LARGE];
277 safe_snprintf(cmd, sizeof(cmd), "gpg --list-keys --with-keygrip --with-colons 0x%s " PLATFORM_SHELL_NULL_REDIRECT, escaped_key_id);
278
279 FILE *fp = NULL;
280 if (platform_popen("gpg_export", cmd, "r", &fp) != ASCIICHAT_OK || !fp) {
281 log_error("Failed to run gpg command - GPG may not be installed");
282#ifdef _WIN32
283 log_error("To install GPG on Windows, download Gpg4win from:");
284 log_error(" https://www.gpg4win.org/download.html");
285#elif defined(__APPLE__)
286 log_error("To install GPG on macOS, use Homebrew:");
287 log_error(" brew install gnupg");
288#else
289 log_error("To install GPG on Linux:");
290 log_error(" Debian/Ubuntu: sudo apt-get install gnupg");
291 log_error(" Fedora/RHEL: sudo dnf install gnupg2");
292 log_error(" Arch Linux: sudo pacman -S gnupg");
293 log_error(" Alpine Linux: sudo apk add gnupg");
294#endif
295 return -1;
296 }
297
298 char line[BUFFER_SIZE_XLARGE];
299 char found_keygrip[CRYPTO_GPG_EXPORT_FOUND_KEYGRIP_BUFFER_SIZE] = {0};
300 bool found_key = false;
301
302 // Parse gpg output
303 // Format: pub:..., grp:::::::::<keygrip>:
304 while (fgets(line, sizeof(line), fp)) {
305 if (strncmp(line, "pub:", 4) == 0) {
306 // Found the public key line
307 found_key = true;
308 } else if (found_key && strncmp(line, "grp:", 4) == 0) {
309 // Extract keygrip using PCRE2 regex
310 // Format: grp:::::::::D52FF935FBA59609EE65E1685287828242A1EA1A:
311 char *keygrip_extracted = NULL;
312
313 if (crypto_regex_extract_gpg_keygrip(line, &keygrip_extracted)) {
314 // Successfully extracted keygrip
315 SAFE_STRNCPY(found_keygrip, keygrip_extracted, sizeof(found_keygrip));
316 if (keygrip_out) {
317 SAFE_STRNCPY(keygrip_out, found_keygrip, 41);
318 }
319 SAFE_FREE(keygrip_extracted);
320 } else {
321 // Fallback to manual parsing if regex fails
322 const char *grp_start = line + 4;
323 int colon_count = 0;
324 while (*grp_start && colon_count < 8) {
325 if (*grp_start == ':') {
326 colon_count++;
327 }
328 grp_start++;
329 }
330
331 if (colon_count == 8) {
332 const char *grp_end = strchr(grp_start, ':');
333 if (grp_end) {
334 size_t grp_len = grp_end - grp_start;
335 if (grp_len < sizeof(found_keygrip)) {
336 memcpy(found_keygrip, grp_start, grp_len);
337 found_keygrip[grp_len] = '\0';
338
339 if (keygrip_out) {
340 SAFE_STRNCPY(keygrip_out, found_keygrip, 41);
341 }
342 }
343 }
344 }
345 }
346 break;
347 }
348 }
349
350 platform_pclose(&fp);
351
352 if (!found_key || strlen(found_keygrip) == 0) {
353 log_error("Could not find GPG key with ID: %s", key_id);
354 return -1;
355 }
356
357 log_debug("Found keygrip for key %s: %s", key_id, found_keygrip);
358
359 // Try to use GPG agent API to read the public key directly via READKEY command
360 int agent_sock = gpg_agent_connect();
361 if (agent_sock < 0) {
362 log_debug("GPG agent not available, falling back to gpg --export for public key extraction");
363 // Fallback: Use gpg --export to get the public key
364 int export_result = gpg_export_public_key(key_id, public_key_out);
365 if (export_result == 0) {
366 log_debug("Successfully extracted public key using fallback method");
367 } else {
368 log_error("Fallback public key extraction failed for key ID: %s", key_id);
369 }
370 return export_result;
371 }
372
373 // Send READKEY command with keygrip to get the public key S-expression
374 char readkey_cmd[BUFFER_SIZE_SMALL];
375 safe_snprintf(readkey_cmd, sizeof(readkey_cmd), "READKEY %s\n", found_keygrip);
376
377 // Cast agent_sock back to pipe_t (gpg_agent_connect returns pipe_t cast to int for portability)
378 pipe_t agent_pipe = (pipe_t)(intptr_t)agent_sock;
379 ssize_t bytes_written = platform_pipe_write(agent_pipe, (const unsigned char *)readkey_cmd, strlen(readkey_cmd));
380 if (bytes_written != (ssize_t)strlen(readkey_cmd)) {
381 log_error("Failed to send READKEY command to GPG agent");
382 gpg_agent_disconnect(agent_sock);
383 return -1;
384 }
385
386 // Read the response (public key S-expression)
387 char response[BUFFER_SIZE_XXXLARGE];
388 memset(response, 0, sizeof(response));
389 ssize_t bytes_read = platform_pipe_read(agent_pipe, (unsigned char *)response, sizeof(response) - 1);
390
391 gpg_agent_disconnect(agent_sock);
392
393 if (bytes_read <= 0) {
394 log_error("Failed to read READKEY response from GPG agent");
395 return -1;
396 }
397
398 // Assuan data lines escape %, CR and LF, including bytes inside the S-expression.
399 size_t decoded = 0;
400 for (size_t i = 0; i < (size_t)bytes_read; ++i) {
401 if (response[i] == '%' && i + 2 < (size_t)bytes_read && isxdigit((unsigned char)response[i + 1]) && isxdigit((unsigned char)response[i + 2])) {
402 unsigned char high = (unsigned char)tolower((unsigned char)response[i + 1]);
403 unsigned char low = (unsigned char)tolower((unsigned char)response[i + 2]);
404 high = high <= '9' ? high - '0' : high - 'a' + 10;
405 low = low <= '9' ? low - '0' : low - 'a' + 10;
406 response[decoded++] = (char)((high << 4) | low);
407 i += 2;
408 } else {
409 response[decoded++] = response[i];
410 }
411 }
412 response[decoded] = '\0';
413
414 // Parse the S-expression to extract Ed25519 public key (q value)
415 // GPG agent returns binary S-expressions in format: (1:q<length>:<binary-data>)
416 // Example: (1:q33:<33-bytes>) where first byte is 0x40 (Ed25519 prefix), then 32-byte key
417 const char *q_marker = strstr(response, "(1:q");
418 if (!q_marker) {
419 log_warn("Failed to find public key (1:q) in GPG agent READKEY response, trying gpg --export fallback");
420 log_debug("Response was: %.*s", (int)(bytes_read < 200 ? bytes_read : 200), response);
421 gpg_agent_disconnect(agent_sock);
422
423 // Fallback: Use gpg --export for public-only keys
424 int export_result = gpg_export_public_key(key_id, public_key_out);
425 if (export_result == 0) {
426 log_debug("Successfully extracted public key using gpg --export fallback");
427 } else {
428 log_error("Fallback public key extraction failed for key ID: %s", key_id);
429 }
430 return export_result;
431 }
432
433 // Skip "(1:q" to get to the length field
434 const char *len_start = q_marker + 4;
435
436 // Parse the length (e.g., "33:")
437 char *colon = strchr(len_start, ':');
438 if (!colon) {
439 log_error("Malformed S-expression: missing colon after length");
440 return -1;
441 }
442
443 size_t key_len = strtoul(len_start, NULL, 10);
444 if (key_len != 33) {
445 log_error("Unexpected Ed25519 public key length: %zu bytes (expected 33)", key_len);
446 return -1;
447 }
448
449 // Skip the colon to get to the binary data
450 const unsigned char *binary_start = (const unsigned char *)(colon + 1);
451 if ((size_t)(binary_start - (const unsigned char *)response) + key_len > decoded) {
452 log_error("Truncated Ed25519 public key in GPG agent response");
453 return -1;
454 }
455
456 // Ed25519 public keys in GPG format have a 0x40 prefix byte, then 32 bytes of actual key
457 if (binary_start[0] != 0x40) {
458 log_error("Invalid Ed25519 public key prefix: 0x%02x (expected 0x40)", binary_start[0]);
459 return -1;
460 }
461
462 // Copy the 32-byte public key (skip the 0x40 prefix)
463 memcpy(public_key_out, binary_start + 1, ED25519_PUBLIC_KEY_SIZE);
464
465 log_debug("Extracted Ed25519 public key from GPG agent via READKEY command");
466 return 0;
467}
GPG agent connection and communication interface.
Dedicated worker for all pending errno stacks and handled history. Signal handlers may only request a...
#define GPG_EXPORT_PACKET_CAPACITY
Definition export.c:11
#define CRYPTO_GPG_EXPORT_FOUND_KEYGRIP_BUFFER_SIZE
Definition export.c:8
GPG public key export interface.
FILE * platform_fopen(const char *name, const char *filename, const char *mode)
Definition filesystem.c:18
#define BUFFER_SIZE_XXXLARGE
Extra extra extra large buffer size (8192 bytes).
#define BUFFER_SIZE_LARGE
Large buffer size (1024 bytes).
#define BUFFER_SIZE_SMALL
Small buffer size (256 bytes).
#define BUFFER_SIZE_XLARGE
Extra large buffer size (2048 bytes).
#define BUFFER_SIZE_MEDIUM
Medium buffer size (512 bytes).
unsigned short uint16_t
#define SAFE_STRNCPY(dst, src, size)
#define SAFE_FREE(ptr)
#define PLATFORM_MAX_PATH_LENGTH
unsigned char uint8_t
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
int gpg_agent_connect(void)
Connect to gpg-agent.
Definition agent.c:103
void gpg_agent_disconnect(int handle_as_int)
Disconnect from gpg-agent.
Definition agent.c:153
@ ASCIICHAT_OK
Definition error_codes.h:50
#define log_warn(...)
Log a WARN message.
Definition log/log.h:615
#define log_error(...)
Log an ERROR message.
Definition log/log.h:628
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:589
bool escape_shell_single_quotes(const char *str, char *out_buffer, size_t out_buffer_size)
Validate that a string contains only safe characters for shell commands.
⚙️ 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
atomic_t bytes_written
Definition mmap.c:45
bool crypto_regex_extract_gpg_keygrip(const char *line, char **keygrip_out)
Definition regex.c:245
PCRE2-based regex patterns for cryptographic parsing.
#define ED25519_PUBLIC_KEY_SIZE
Ed25519 public key size in bytes.
Definition sizes.h:37
int platform_popen(const char *name, const char *command, const char *mode, FILE **out_stream)
int platform_pclose(FILE **stream_ptr)
🔤 String Manipulation and Shell Escaping Utilities
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
Common validation macros to reduce duplication in protocol handlers.