ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
gpg_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_GPG_GPG_KEYS_HEX_KEY_ID_BUFFER_SIZE 17
9
10/* Existing buffer budgets in bytes, including NUL for text storage. */
11#define GPG_COLON_FIELD_CAPACITY 12
12
15#include <ascii-chat/crypto/gpg/openpgp.h> // For openpgp_parse_armored_pubkey()
17#include <ascii-chat/common.h>
20#include <libplatform/process.h>
21#include <ascii-chat/crypto/gpg/export.h> // For gpg_get_public_key()
22#include <sodium.h>
23#include <string.h>
24#include <stdlib.h>
25#include <stdio.h>
26#include <time.h>
27
28// =============================================================================
29// GPG Key Parsing Implementation
30// =============================================================================
31
32asciichat_error_t parse_gpg_key(const char *gpg_key_id, public_key_t *key_out) {
33 if (!gpg_key_id || !key_out) {
34 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: gpg_key_id=%p, key_out=%p", gpg_key_id, key_out);
36 }
37
38 // Validate key ID format (must be 8, 16, or 40 hex characters, optionally with 0x prefix)
39 // - 8 chars: short key ID (last 8 chars of fingerprint)
40 // - 16 chars: long key ID (last 16 chars of fingerprint)
41 // - 40 chars: full fingerprint
42 const char *key_id = gpg_key_id;
43 if (strncmp(key_id, "0x", 2) == 0 || strncmp(key_id, "0X", 2) == 0) {
44 key_id += 2; // Skip 0x prefix
45 }
46
47 size_t key_id_len = strlen(key_id);
48 if (key_id_len != 8 && key_id_len != 16 && key_id_len != 40) {
49 return SET_ERRNO(ERROR_CRYPTO_KEY, "Invalid GPG key ID length: %zu (expected 8, 16, or 40 hex chars)", key_id_len);
50 }
51
52 // Validate hex characters
53 for (size_t i = 0; i < key_id_len; i++) {
54 char c = key_id[i];
55 if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'))) {
56 return SET_ERRNO(ERROR_CRYPTO_KEY, "Invalid GPG key ID: contains non-hex character '%c'", c);
57 }
58 }
59
60 // Extract Ed25519 public key from GPG keyring using gpg --list-keys
62 asciichat_error_t extract_result = extract_ed25519_from_gpg(key_id, ed25519_pk);
63 if (extract_result != ASCIICHAT_OK) {
64 return extract_result;
65 }
66
67 // Initialize the public key structure
68 memset(key_out, 0, sizeof(public_key_t));
69 key_out->type = KEY_TYPE_GPG;
70 memcpy(key_out->key, ed25519_pk, ED25519_PUBLIC_KEY_SIZE);
71
72 // Set comment for display
73 safe_snprintf(key_out->comment, sizeof(key_out->comment), "GPG key %s", key_id);
74
75 return ASCIICHAT_OK;
76}
77
78asciichat_error_t parse_gpg_key_binary(const uint8_t *gpg_key_binary, size_t key_size, public_key_t *key_out) {
79 if (!gpg_key_binary || !key_out) {
80 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: gpg_key_binary=%p, key_out=%p", gpg_key_binary, key_out);
82 }
83
84 if (key_size == 0) {
85 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid key size: %zu", key_size);
87 }
88
90 asciichat_error_t result;
91 if (key_size >= strlen("-----BEGIN PGP PUBLIC KEY BLOCK-----") && memcmp(gpg_key_binary, "-----BEGIN PGP PUBLIC KEY BLOCK-----", strlen("-----BEGIN PGP PUBLIC KEY BLOCK-----")) == 0) {
92 char *armored_text = SAFE_MALLOC(key_size + 1, char *);
93 memcpy(armored_text, gpg_key_binary, key_size);
94 armored_text[key_size] = '\0';
95 result = openpgp_parse_armored_pubkey(armored_text, ed25519_pk);
96 SAFE_FREE(armored_text);
97 } else {
98 result = openpgp_parse_binary_pubkey(gpg_key_binary, key_size, ed25519_pk);
99 }
100
101 if (result != ASCIICHAT_OK) {
102 return result;
103 }
104
105 // Initialize the public key structure
106 memset(key_out, 0, sizeof(public_key_t));
107 key_out->type = KEY_TYPE_GPG;
108 memcpy(key_out->key, ed25519_pk, ED25519_PUBLIC_KEY_SIZE);
109
110 // Set comment for display
111 safe_snprintf(key_out->comment, sizeof(key_out->comment), "GPG Ed25519 key");
112
113 return ASCIICHAT_OK;
114}
115
117 if (!gpg_key_id || !ed25519_pk) {
118 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: gpg_key_id=%p, ed25519_pk=%p", gpg_key_id, ed25519_pk);
119 return ERROR_INVALID_PARAM;
120 }
121
122 // Use gpg_get_public_key() to extract Ed25519 public key from GPG keyring
123 // Note: gpg_key_id should be the key ID (e.g., "7FE90A79F2E80ED3")
124 char keygrip[MAX_GPG_KEYGRIP_LEN];
125 if (gpg_get_public_key(gpg_key_id, ed25519_pk, keygrip) != 0) {
126 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to extract Ed25519 public key from GPG for key ID: %s", gpg_key_id);
127 }
128
129 return ASCIICHAT_OK;
130}
131
132asciichat_error_t gpg_to_x25519_public(const char *gpg_key_text, uint8_t x25519_pk[X25519_KEY_SIZE]) {
133 if (!gpg_key_text || !x25519_pk) {
134 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: gpg_key_text=%p, x25519_pk=%p", gpg_key_text, x25519_pk);
135 return ERROR_INVALID_PARAM;
136 }
137
138 // First extract the Ed25519 public key from the GPG key
140 asciichat_error_t extract_result = extract_ed25519_from_gpg(gpg_key_text, ed25519_pk);
141 if (extract_result != ASCIICHAT_OK) {
142 return extract_result;
143 }
144
145 // Convert Ed25519 to X25519
146 if (crypto_sign_ed25519_pk_to_curve25519(x25519_pk, ed25519_pk) != 0) {
147 SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to convert Ed25519 to X25519");
148 return ERROR_CRYPTO_KEY;
149 }
150
151 return ASCIICHAT_OK;
152}
153
154// =============================================================================
155// GPG Key Operations
156// =============================================================================
157
158asciichat_error_t get_gpg_fingerprint(const char *gpg_key_text, uint8_t fingerprint_out[GPG_FINGERPRINT_SIZE]) {
159 if (!gpg_key_text || !fingerprint_out) {
160 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: gpg_key_text=%p, fingerprint_out=%p", gpg_key_text, fingerprint_out);
161 return ERROR_INVALID_PARAM;
162 }
163
164 // TODO: Implement GPG fingerprint extraction
165 // This requires parsing the OpenPGP packet structure and computing SHA-1
166
167 SET_ERRNO(ERROR_CRYPTO_KEY, "GPG fingerprint extraction not yet implemented");
168 return ERROR_CRYPTO_KEY;
169}
170
171asciichat_error_t get_gpg_key_id(const char *gpg_key_text, uint8_t key_id_out[GPG_KEY_ID_SIZE]) {
172 if (!gpg_key_text || !key_id_out) {
173 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: gpg_key_text=%p, key_id_out=%p", gpg_key_text, key_id_out);
174 return ERROR_INVALID_PARAM;
175 }
176
177 // TODO: Implement GPG key ID extraction
178 // This is typically the last 8 bytes of the fingerprint
179
180 SET_ERRNO(ERROR_CRYPTO_KEY, "GPG key ID extraction not yet implemented");
181 return ERROR_CRYPTO_KEY;
182}
183
184asciichat_error_t check_gpg_key_expiry(const char *gpg_key_text, bool *is_expired) {
185 if (!gpg_key_text || !is_expired) {
186 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: gpg_key_text=%p, is_expired=%p", gpg_key_text, is_expired);
187 return ERROR_INVALID_PARAM;
188 }
189
190 // For GPG key expiry checking, we need a key ID
191 // If gpg_key_text is a key ID (8, 16, or 40 hex chars), use it directly
192 // Otherwise, we'd need to parse the GPG armored text (complex)
193 size_t key_len = strlen(gpg_key_text);
194 const char *key_id = gpg_key_text;
195
196 // Check if it looks like a key ID (hex characters only)
197 bool is_hex = true;
198 for (size_t i = 0; i < key_len; i++) {
199 if (!((gpg_key_text[i] >= '0' && gpg_key_text[i] <= '9') || (gpg_key_text[i] >= 'A' && gpg_key_text[i] <= 'F') || (gpg_key_text[i] >= 'a' && gpg_key_text[i] <= 'f'))) {
200 is_hex = false;
201 break;
202 }
203 }
204
205 // Only support key ID format (8, 16, or 40 hex chars)
206 if (!is_hex || (key_len != 8 && key_len != 16 && key_len != 40)) {
207 log_warn("Input is not a key ID format (expected 8/16/40 hex chars)");
208 *is_expired = false; // Assume not expired if we can't check
209 return ASCIICHAT_OK;
210 }
211
212 // Use gpg --list-keys with colon-separated output to check expiry
213 char cmd[BUFFER_SIZE_MEDIUM];
214 safe_snprintf(cmd, sizeof(cmd), "gpg --list-keys --with-colons %s " PLATFORM_SHELL_NULL_REDIRECT, key_id);
215
216 FILE *fp = NULL;
217 if (platform_popen("gpg_keys", cmd, "r", &fp) != ASCIICHAT_OK || !fp) {
218 log_error("Failed to run gpg --list-keys for key %s", key_id);
219 *is_expired = false; // Assume not expired if we can't check
220 return ASCIICHAT_OK;
221 }
222
223 char line[BUFFER_SIZE_LARGE];
224 bool found_pub = false;
225 *is_expired = false;
226
227 // Parse colon-separated output
228 // Format: pub:trust:keylen:algo:keyid:creation:expiry:...
229 // Field 6 is expiry timestamp (seconds since epoch), or empty if no expiry
230 while (fgets(line, sizeof(line), fp)) {
231 if (strncmp(line, "pub:", 4) == 0) {
232 found_pub = true;
233
234 // Split line by colons
235 char *fields[GPG_COLON_FIELD_CAPACITY];
236 int field_count = 0;
237 char *ptr = line;
238 char *field_start = ptr;
239
240 while (*ptr && field_count < GPG_COLON_FIELD_CAPACITY) {
241 if (*ptr == ':' || *ptr == '\n') {
242 *ptr = '\0';
243 fields[field_count++] = field_start;
244 field_start = ptr + 1;
245 }
246 ptr++;
247 }
248
249 // Field 6 is expiry date (index 6)
250 if (field_count >= 7 && strlen(fields[6]) > 0) {
251 // Parse expiry timestamp
252 long expiry_timestamp = strtol(fields[6], NULL, 10);
253 time_t now = time(NULL);
254
255 if (expiry_timestamp > 0 && expiry_timestamp <= now) {
256 *is_expired = true;
257 log_warn("GPG key %s has expired (expiry: %ld, now: %ld)", key_id, expiry_timestamp, (long)now);
258 } else if (expiry_timestamp > 0) {
259 log_debug("GPG key %s expires at timestamp %ld (valid)", key_id, expiry_timestamp);
260 } else {
261 log_debug("GPG key %s has no expiration date", key_id);
262 }
263 } else {
264 log_debug("GPG key %s has no expiration date (field empty)", key_id);
265 }
266
267 break; // Found the pub line, stop parsing
268 }
269 }
270
271 platform_pclose(&fp);
272
273 if (!found_pub) {
274 log_warn("Could not find GPG key %s in keyring", key_id);
275 *is_expired = false; // Assume not expired if key not found
276 }
277
278 return ASCIICHAT_OK;
279}
280
281// =============================================================================
282// GPG Key Formatting
283// =============================================================================
284
285asciichat_error_t format_gpg_key_display(const char *gpg_key_text, char *output, size_t output_size) {
286 if (!gpg_key_text || !output) {
287 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: gpg_key_text=%p, output=%p", gpg_key_text, output);
288 return ERROR_INVALID_PARAM;
289 }
290
291 if (output_size < 64) {
292 SET_ERRNO(ERROR_INVALID_PARAM, "Output buffer too small: %zu (minimum 64)", output_size);
293 return ERROR_INVALID_PARAM;
294 }
295
296 // Extract key ID for display
297 uint8_t key_id[GPG_KEY_ID_SIZE];
298 asciichat_error_t key_id_result = get_gpg_key_id(gpg_key_text, key_id);
299 if (key_id_result != ASCIICHAT_OK) {
300 // Fallback to generic GPG key display
301 SAFE_STRNCPY(output, "GPG key (key ID extraction failed)", output_size - 1);
302 return ASCIICHAT_OK;
303 }
304
305 // Format as hex key ID
307 for (int i = 0; i < 8; i++) {
308 safe_snprintf(hex_key_id + i * 2, 3, "%02x", key_id[i]);
309 }
310 hex_key_id[16] = '\0';
311
312 // Create display string
313 int result = safe_snprintf(output, output_size, "GPG key ID: %s", hex_key_id);
314 if (result < 0 || result >= (int)output_size) {
315 SET_ERRNO(ERROR_STRING, "Failed to format GPG key display");
316 return ERROR_STRING;
317 }
318
319 return ASCIICHAT_OK;
320}
321
322asciichat_error_t extract_gpg_key_comment(const char *gpg_key_text, char *comment_out, size_t comment_size) {
323 if (!gpg_key_text || !comment_out) {
324 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: gpg_key_text=%p, comment_out=%p", gpg_key_text, comment_out);
325 return ERROR_INVALID_PARAM;
326 }
327
328 if (comment_size == 0) {
329 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid comment size: %zu", comment_size);
330 return ERROR_INVALID_PARAM;
331 }
332
333 // TODO: Implement GPG key comment extraction
334 // This requires parsing the OpenPGP packet structure and extracting user ID packets
335
336 // For now, use a generic comment
337 SAFE_STRNCPY(comment_out, "GPG key", comment_size - 1);
338 return ASCIICHAT_OK;
339}
Synchronized per-thread pending error stacks and value snapshots. SET_ERRNO pushes,...
#define SET_ERRNO(code,...)
GPG public key export interface.
#define CRYPTO_GPG_GPG_KEYS_HEX_KEY_ID_BUFFER_SIZE
Definition gpg_keys.c:8
#define GPG_COLON_FIELD_CAPACITY
Definition gpg_keys.c:11
#define BUFFER_SIZE_LARGE
Large buffer size (1024 bytes).
#define BUFFER_SIZE_MEDIUM
Medium buffer size (512 bytes).
#define SAFE_STRNCPY(dst, src, size)
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
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
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_STRING
@ ERROR_INVALID_PARAM
uint8_t key[CRYPTO_PUBLIC_KEY_SIZE]
Definition key_types.h:78
asciichat_error_t check_gpg_key_expiry(const char *gpg_key_text, bool *is_expired)
Check if GPG key is expired.
Definition gpg_keys.c:184
asciichat_error_t extract_ed25519_from_gpg(const char *gpg_key_id, uint8_t ed25519_pk[32])
Extract Ed25519 public key from GPG key.
Definition gpg_keys.c:116
asciichat_error_t extract_gpg_key_comment(const char *gpg_key_text, char *comment_out, size_t comment_size)
Extract key comment/email from GPG key.
Definition gpg_keys.c:322
char comment[MAX_COMMENT_LEN]
Definition key_types.h:79
asciichat_error_t get_gpg_key_id(const char *gpg_key_text, uint8_t key_id_out[8])
Get GPG key ID (short fingerprint).
Definition gpg_keys.c:171
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
asciichat_error_t get_gpg_fingerprint(const char *gpg_key_text, uint8_t fingerprint_out[20])
Get GPG key fingerprint.
Definition gpg_keys.c:158
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 format_gpg_key_display(const char *gpg_key_text, char *output, size_t output_size)
Format GPG key for display.
Definition gpg_keys.c:285
key_type_t type
Definition key_types.h:77
asciichat_error_t gpg_to_x25519_public(const char *gpg_key_text, uint8_t x25519_pk[32])
Convert GPG key to X25519 for key exchange.
Definition gpg_keys.c:132
@ KEY_TYPE_GPG
Definition key_types.h:60
#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
⚙️ Common definitions, error codes, macros, and types shared throughout the application
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_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 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 GPG_KEY_ID_SIZE
Definition sizes.h:173
#define GPG_FINGERPRINT_SIZE
Definition sizes.h:171
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
The normalized public identity used by ascii-chat's crypto and key-management code.
Definition key_types.h:76
⏱️ High-precision timing utilities using sokol_time.h and uthash