ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
verification.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_VERIFICATION_CMD_BUFFER_SIZE 1024
9#define CRYPTO_GPG_VERIFICATION_OUTPUT_BUFFER_SIZE 4096
10#define CRYPTO_GPG_VERIFICATION_MSG_HEX_BUFFER_SIZE 128
11
16#include <ascii-chat/common.h>
19#include <ascii-chat/log/log.h>
20#include <libplatform/system.h>
21#include <libplatform/filesystem.h>
22#include <libplatform/process.h>
23
24#include <ctype.h>
25#include <errno.h>
26#include <stdio.h>
27#include <stdlib.h>
28#include <string.h>
29#ifndef _WIN32
30#include <unistd.h>
31#endif
32
33#ifdef HAVE_LIBGCRYPT
34#include <gcrypt.h>
35#endif
36
37int gpg_verify_detached_ed25519(const char *key_id, const uint8_t *message, size_t message_len, const uint8_t signature[ED25519_SIGNATURE_SIZE]) {
38 // Note: We don't use the raw signature parameter directly.
39 // Instead, we regenerate the OpenPGP signature using GPG (Ed25519 is deterministic).
40 (void)signature;
41
42 log_debug("Verifying signature with key ID %s using gpg --verify", key_id);
43
44 // To verify with GPG, we need to:
45 // 1. Reconstruct the OpenPGP signature packet from the raw R||S signature
46 // 2. Write message and signature to temp files
47 // 3. Call gpg --verify
48
49 // First, reconstruct OpenPGP signature by signing the same message
50 // Since Ed25519 is deterministic, we should get the same OpenPGP packet
51 uint8_t openpgp_signature[GPG_SIGNATURE_PACKET_CAPACITY];
52 size_t openpgp_len = 0;
53
54 int sign_result = gpg_sign_with_key(key_id, message, message_len, openpgp_signature, &openpgp_len);
55 if (sign_result != 0) {
56 log_error("Failed to create reference signature for verification");
57 return -1;
58 }
59
60 // Now verify using gpg --verify
61 char msg_path[PLATFORM_MAX_PATH_LENGTH];
62 char sig_path[PLATFORM_MAX_PATH_LENGTH];
63 int msg_fd = -1;
64 int sig_fd = -1;
65
66 if (platform_create_temp_file(msg_path, sizeof(msg_path), "gpg_verify_msg", &msg_fd) != 0) {
67 log_error("Failed to create temporary message file");
68 return -1;
69 }
70
71 if (platform_create_temp_file(sig_path, sizeof(sig_path), "gpg_verify_sig", &sig_fd) != 0) {
72 platform_delete_temp_file(msg_path);
73 log_error("Failed to create temporary signature file");
74 return -1;
75 }
76
77 // Write message
78 if (write(msg_fd, message, message_len) != (ssize_t)message_len) {
79 log_error("Failed to write message to temp file");
80 close(msg_fd);
81 close(sig_fd);
82 platform_delete_temp_file(msg_path);
83 platform_delete_temp_file(sig_path);
84 return -1;
85 }
86 close(msg_fd);
87
88 // Write OpenPGP signature
89 if (write(sig_fd, openpgp_signature, openpgp_len) != (ssize_t)openpgp_len) {
90 log_error("Failed to write signature to temp file");
91 close(sig_fd);
92 platform_delete_temp_file(msg_path);
93 platform_delete_temp_file(sig_path);
94 return -1;
95 }
96 close(sig_fd);
97
98 // Call gpg --verify
100 safe_snprintf(cmd, sizeof(cmd), "gpg --verify '%s' '%s' 2>&1", sig_path, msg_path);
101 log_debug("Running: %s", cmd);
102
103 FILE *fp;
104 platform_popen("gpg_verify", cmd, "r", &fp);
105 if (!fp) {
106 log_error("Failed to run gpg --verify");
107 platform_unlink(msg_path);
108 platform_unlink(sig_path);
109 return -1;
110 }
111
113 size_t output_len = fread(output, 1, sizeof(output) - 1, fp);
114 int exit_code = platform_pclose(&fp);
115
116 // Cleanup temp files
117 platform_delete_temp_file(msg_path);
118 platform_delete_temp_file(sig_path);
119
120 if (exit_code == 0) {
121 log_debug("GPG signature verification PASSED");
122 return 0;
123 } else {
124 log_error("GPG signature verification FAILED (exit code %d)", exit_code);
125 if (output_len > 0) {
126 log_debug("GPG output: %s", output);
127 }
128 return -1;
129 }
130}
131
132int gpg_verify_signature(const uint8_t *public_key, const uint8_t *message, size_t message_len, const uint8_t *signature) {
133#ifdef HAVE_LIBGCRYPT
134 gcry_error_t err;
135 gcry_sexp_t s_pubkey = NULL;
136 gcry_sexp_t s_sig = NULL;
137 gcry_sexp_t s_data = NULL;
138
139 // Initialize libgcrypt if not already done
140 if (!gcry_control(GCRYCTL_INITIALIZATION_FINISHED_P)) {
141 gcry_check_version(NULL);
142 gcry_control(GCRYCTL_DISABLE_SECMEM, 0);
143 gcry_control(GCRYCTL_INITIALIZATION_FINISHED, 0);
144 }
145
146 // Build public key S-expression: (public-key (ecc (curve Ed25519) (flags eddsa) (q %b)))
147 // Must include (flags eddsa) to match libgcrypt's Ed25519 test suite.
148 // See libgcrypt/tests/t-ed25519.c line 246-251.
149 err = gcry_sexp_build(&s_pubkey, NULL, "(public-key (ecc (curve Ed25519) (flags eddsa) (q %b)))", 32, public_key);
150 if (err) {
151 log_error("Failed to build public key S-expression: %s", gcry_strerror(err));
152 return -1;
153 }
154
155 // Build signature S-expression: (sig-val (eddsa (r %b) (s %b)))
156 // Signature is 64 bytes: first 32 bytes are R, last 32 bytes are S
157 err = gcry_sexp_build(&s_sig, NULL, "(sig-val (eddsa (r %b) (s %b)))", 32, signature, 32, signature + 32);
158 if (err) {
159 log_error("Failed to build signature S-expression: %s", gcry_strerror(err));
160 gcry_sexp_release(s_pubkey);
161 return -1;
162 }
163
164 // Build data S-expression with raw message
165 // According to libgcrypt's test suite (t-ed25519.c line 273),
166 // Ed25519 data should be: (data (value %b)) with no flags.
167 // The (flags eddsa) belongs in the key S-expression above, not in the data.
168 // GPG agent's internal format is different - this is the correct libgcrypt API usage.
169 err = gcry_sexp_build(&s_data, NULL, "(data (value %b))", message_len, message);
170 if (err) {
171 log_error("Failed to build data S-expression: %s", gcry_strerror(err));
172 gcry_sexp_release(s_pubkey);
173 gcry_sexp_release(s_sig);
174 return -1;
175 }
176
177 // Debug logging
178 char pubkey_hex[HEX_STRING_SIZE_32];
179 char r_hex[HEX_STRING_SIZE_32];
180 char s_hex[HEX_STRING_SIZE_32];
182
183 for (int i = 0; i < 32; i++) {
184 safe_snprintf(pubkey_hex + i * 2, 3, "%02x", public_key[i]);
185 safe_snprintf(r_hex + i * 2, 3, "%02x", signature[i]);
186 safe_snprintf(s_hex + i * 2, 3, "%02x", signature[32 + i]);
187 }
188 for (size_t i = 0; i < (message_len < 32 ? message_len : 32); i++) {
189 safe_snprintf(msg_hex + i * 2, 3, "%02x", message[i]);
190 }
191
192 log_debug("pubkey=%s", pubkey_hex);
193 log_debug("R=%s", r_hex);
194 log_debug("S=%s", s_hex);
195 log_debug("msg=%s (len=%zu)", msg_hex, message_len);
196
197 // Verify the signature
198 err = gcry_pk_verify(s_sig, s_data, s_pubkey);
199
200 // Clean up S-expressions
201 gcry_sexp_release(s_pubkey);
202 gcry_sexp_release(s_sig);
203 gcry_sexp_release(s_data);
204
205 if (err) {
206 log_debug("Signature verification failed: %s", gcry_strerror(err));
207 return -1;
208 }
209
210 log_debug("Signature verified successfully");
211 return 0;
212#else
213 // Explicitly mark parameters as unused when libgcrypt is not available
214 (void)public_key;
215 (void)message;
216 (void)message_len;
217 (void)signature;
218 log_error("libgcrypt not available");
219 return -1;
220#endif
221}
222
223int gpg_verify_signature_with_binary(const uint8_t *signature, size_t signature_len, const uint8_t *message, size_t message_len, const char *expected_key_id) {
224 // Validate inputs
225 if (!signature || signature_len == 0 || signature_len > 512) {
226 log_error("Invalid signature (expected 1-512 bytes, got %zu)", signature_len);
227 return -1;
228 }
229 if (!message || message_len == 0) {
230 log_error("Invalid message");
231 return -1;
232 }
233
234 // Create temporary files for signature and message
235 char sig_path[PLATFORM_MAX_PATH_LENGTH];
236 char msg_path[PLATFORM_MAX_PATH_LENGTH];
237 int sig_fd = -1;
238 int msg_fd = -1;
239 int result = -1;
240
241 // Create temp files using platform abstraction
242 if (platform_create_temp_file(sig_path, sizeof(sig_path), "asciichat_sig", &sig_fd) != 0) {
243 log_error("Failed to create signature temp file");
244 return -1;
245 }
246
247 if (platform_create_temp_file(msg_path, sizeof(msg_path), "asciichat_msg", &msg_fd) != 0) {
248 log_error("Failed to create message temp file");
249 platform_delete_temp_file(sig_path);
250 return -1;
251 }
252
253#ifdef _WIN32
254 // Windows: Write to already-created files using CreateFileA
255 HANDLE sig_handle = CreateFileA(sig_path, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY, NULL);
256 if (sig_handle == INVALID_HANDLE_VALUE) {
257 log_error("Failed to open signature temp file: %lu", GetLastError());
258 platform_delete_temp_file(sig_path);
259 platform_delete_temp_file(msg_path);
260 return -1;
261 }
262
263 DWORD bytes_written;
264 if (!WriteFile(sig_handle, signature, (DWORD)signature_len, &bytes_written, NULL) || bytes_written != signature_len) {
265 log_error("Failed to write signature to temp file: %lu", GetLastError());
266 CloseHandle(sig_handle);
267 platform_delete_temp_file(sig_path);
268 platform_delete_temp_file(msg_path);
269 return -1;
270 }
271 CloseHandle(sig_handle);
272
273 HANDLE msg_handle = CreateFileA(msg_path, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY, NULL);
274 if (msg_handle == INVALID_HANDLE_VALUE) {
275 log_error("Failed to open message temp file: %lu", GetLastError());
276 platform_delete_temp_file(sig_path);
277 platform_delete_temp_file(msg_path);
278 return -1;
279 }
280
281 if (!WriteFile(msg_handle, message, (DWORD)message_len, &bytes_written, NULL) || bytes_written != message_len) {
282 log_error("Failed to write message to temp file: %lu", GetLastError());
283 CloseHandle(msg_handle);
284 platform_delete_temp_file(sig_path);
285 platform_delete_temp_file(msg_path);
286 return -1;
287 }
288 CloseHandle(msg_handle);
289
290#else
291 // Unix: Write to open file descriptors returned by platform_create_temp_file
292 ssize_t sig_written = write(sig_fd, signature, signature_len);
293 if (sig_written != (ssize_t)signature_len) {
294 log_error("Failed to write signature to temp file: %s", SAFE_STRERROR(errno));
295 close(sig_fd);
296 close(msg_fd);
297 platform_delete_temp_file(sig_path);
298 platform_delete_temp_file(msg_path);
299 return -1;
300 }
301 close(sig_fd);
302
303 ssize_t msg_written = write(msg_fd, message, message_len);
304 if (msg_written != (ssize_t)message_len) {
305 log_error("Failed to write message to temp file: %s", SAFE_STRERROR(errno));
306 close(msg_fd);
307 platform_delete_temp_file(sig_path);
308 platform_delete_temp_file(msg_path);
309 return -1;
310 }
311 close(msg_fd);
312#endif
313
314 // Build gpg --verify command
315 char cmd[BUFFER_SIZE_LARGE];
316#ifdef _WIN32
317 safe_snprintf(cmd, sizeof(cmd), "gpg --verify \"%s\" \"%s\" 2>&1", sig_path, msg_path);
318#else
319 safe_snprintf(cmd, sizeof(cmd), "gpg --verify '%s' '%s' 2>&1", sig_path, msg_path);
320#endif
321
322 log_debug("Running GPG verify command: %s", cmd);
323
324 // Execute gpg --verify command
325 FILE *fp;
326 platform_popen("gpg_verify", cmd, "r", &fp);
327 if (!fp) {
328 log_error("Failed to execute gpg --verify command");
329 goto cleanup;
330 }
331
332 // Parse output for "Good signature" and verify key ID
333 char line[BUFFER_SIZE_MEDIUM];
334 bool found_good_sig = false;
335 bool found_key_id = false;
336
337 while (fgets(line, sizeof(line), fp)) {
338 log_debug("GPG output: %s", line);
339
340 // Check for "Good signature"
341 if (strstr(line, "Good signature")) {
342 found_good_sig = true;
343 }
344
345 // Check if this line contains the expected key ID (GPG outputs key ID on separate line)
346 if (expected_key_id && strlen(expected_key_id) > 0) {
347 if (strstr(line, expected_key_id)) {
348 found_key_id = true;
349 log_debug("Found expected key ID in GPG output: %s", expected_key_id);
350 }
351 }
352
353 // Check for signature errors
354 if (strstr(line, "BAD signature")) {
355 log_error("GPG reports BAD signature");
356 platform_pclose(&fp);
357 fp = NULL;
358 goto cleanup;
359 }
360 }
361
362 // Check exit code
363 int status = platform_pclose(&fp);
364 fp = NULL;
365
366#ifdef _WIN32
367 int exit_code = status;
368#else
369 int exit_code = WEXITSTATUS(status);
370#endif
371
372 if (exit_code != 0) {
373 log_error("GPG verify failed with exit code: %d", exit_code);
374 goto cleanup;
375 }
376
377 if (!found_good_sig) {
378 log_error("GPG verify did not report 'Good signature'");
379 goto cleanup;
380 }
381
382 // If expected_key_id was provided, verify we found it in the output
383 if (expected_key_id && strlen(expected_key_id) > 0) {
384 if (!found_key_id) {
385 log_error("GPG signature key ID does not match expected key ID: %s", expected_key_id);
386 goto cleanup;
387 }
388 }
389
390 log_debug("GPG signature verified successfully via gpg --verify binary");
391 result = 0;
392
393cleanup:
394 // Clean up temp files
395 platform_delete_temp_file(sig_path);
396 platform_delete_temp_file(msg_path);
397
398 if (fp) {
399 platform_pclose(&fp);
400 }
401
402 return result;
403}
Dedicated worker for all pending errno stacks and handled history. Signal handlers may only request a...
#define BUFFER_SIZE_LARGE
Large buffer size (1024 bytes).
#define BUFFER_SIZE_MEDIUM
Medium buffer size (512 bytes).
#define SAFE_STRERROR(errnum)
#define PLATFORM_MAX_PATH_LENGTH
unsigned char uint8_t
int gpg_verify_detached_ed25519(const char *key_id, const uint8_t *message, size_t message_len, const uint8_t signature[ED25519_SIGNATURE_SIZE])
Verify Ed25519 signature using GPG binary.
int gpg_verify_signature(const uint8_t *public_key, const uint8_t *message, size_t message_len, const uint8_t *signature)
Verify Ed25519 signature using libgcrypt (no GPG binary required).
int gpg_verify_signature_with_binary(const uint8_t *signature, size_t signature_len, const uint8_t *message, size_t message_len, const char *expected_key_id)
Verify OpenPGP signature using GPG binary.
int gpg_sign_with_key(const char *key_id, const uint8_t *message, size_t message_len, uint8_t *signature_out, size_t *signature_len_out)
Sign a message using GPG key (via gpg –detach-sign).
Definition signing.c:46
#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
📝 Logging API with multiple log levels and terminal output control
atomic_t bytes_written
Definition mmap.c:45
GPG message signing interface.
#define ED25519_SIGNATURE_SIZE
Ed25519 signature size in bytes.
Definition sizes.h:41
#define GPG_SIGNATURE_PACKET_CAPACITY
Definition sizes.h:4
#define HEX_STRING_SIZE_32
Hex string size for 32-byte values (64 hex chars + null terminator).
Definition sizes.h:158
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
Common validation macros to reduce duplication in protocol handlers.
#define CRYPTO_GPG_VERIFICATION_OUTPUT_BUFFER_SIZE
Definition verification.c:9
#define CRYPTO_GPG_VERIFICATION_MSG_HEX_BUFFER_SIZE
#define CRYPTO_GPG_VERIFICATION_CMD_BUFFER_SIZE
Definition verification.c:8
GPG signature verification interface.