ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
signing.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_SIGNING_ESCAPED_KEY_ID_BUFFER_SIZE 64
9#define CRYPTO_GPG_SIGNING_HEX_S_BUFFER_SIZE 65
10
15#include <ascii-chat/common.h>
18#include <ascii-chat/log/log.h>
19#include <ascii-chat/log/io.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
46int 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) {
47 if (!key_id || !message || message_len == 0 || !signature_out || !signature_len_out) {
48 log_error("Invalid parameters");
49 return -1;
50 }
51
52 char msg_path[PLATFORM_MAX_PATH_LENGTH];
53 char sig_path[PLATFORM_MAX_PATH_LENGTH];
54 int msg_fd = -1;
55 int sig_fd = -1;
56 int result = -1;
57
58 // Create temp files using platform abstraction
59 if (platform_create_temp_file(msg_path, sizeof(msg_path), "asciichat_msg", &msg_fd) != 0) {
60 log_error("Failed to create temp message file");
61 return -1;
62 }
63
64 if (platform_create_temp_file(sig_path, sizeof(sig_path), "asciichat_sig", &sig_fd) != 0) {
65 log_error("Failed to create temp signature file");
66 platform_delete_temp_file(msg_path);
67 return -1;
68 }
69
70 // Close signature file descriptor (will be created by gpg)
71 if (sig_fd >= 0) {
72 close(sig_fd);
73 }
74 platform_delete_temp_file(sig_path); // Remove it so gpg can create it fresh
75
76 // Write message to temp file
77 ssize_t written = write(msg_fd, message, message_len);
78 close(msg_fd);
79 msg_fd = -1;
80
81 if (written != (ssize_t)message_len) {
82 log_error("Failed to write message to temp file");
83 goto cleanup;
84 }
85
86 // Escape key ID for shell command (prevent injection)
88 if (!escape_path_for_shell(key_id, escaped_key_id, sizeof(escaped_key_id))) {
89 log_error("Failed to escape GPG key ID for shell command");
90 goto cleanup;
91 }
92
93 // Call gpg --detach-sign
94 // Use gpg with --detach-sign and --output for safe subprocess execution
95 const char *argv[] = {"gpg", "--local-user", escaped_key_id, "--detach-sign", "--output", sig_path, msg_path, NULL};
96
97 // Note: Don't log the full command as it may contain sensitive key material
98 log_debug("Signing with GPG key 0x%s", escaped_key_id);
99 int status = 0;
100 LOG_IO("gpg", { status = platform_execute_subprocess("gpg", argv, NULL, 0, NULL, NULL); });
101 if (status != 0) {
102 log_error("GPG signing failed (exit code %d)", status);
103 goto cleanup;
104 }
105
106 // Read signature file
107 FILE *sig_fp = platform_fopen("file_stream", sig_path, "rb");
108 if (!sig_fp) {
109 log_error("Failed to open signature file: %s", SAFE_STRERROR(errno));
110 goto cleanup;
111 }
112
113 fseek(sig_fp, 0, SEEK_END);
114 long sig_size = ftell(sig_fp);
115 fseek(sig_fp, 0, SEEK_SET);
116
117 if (sig_size <= 0 || sig_size > 512) {
118 log_error("Invalid signature size: %ld bytes", sig_size);
119 fclose(sig_fp);
120 goto cleanup;
121 }
122
123 size_t bytes_read = fread(signature_out, 1, sig_size, sig_fp);
124 fclose(sig_fp);
125
126 if (bytes_read != (size_t)sig_size) {
127 log_error("Failed to read signature file");
128 goto cleanup;
129 }
130
131 *signature_len_out = sig_size;
132 log_debug("GPG signature created successfully (%zu bytes)", *signature_len_out);
133 result = 0;
134
135cleanup:
136 if (msg_fd >= 0) {
137 close(msg_fd);
138 }
139 platform_delete_temp_file(msg_path);
140 platform_delete_temp_file(sig_path);
141 return result;
142}
143
144int gpg_sign_detached_ed25519(const char *key_id, const uint8_t *message, size_t message_len, uint8_t signature_out[ED25519_SIGNATURE_SIZE]) {
145 log_debug("Signing with key ID %s (fallback mode)", key_id);
146
147 // Get OpenPGP signature packet from gpg --detach-sign
148 uint8_t openpgp_signature[GPG_SIGNATURE_PACKET_CAPACITY];
149 size_t openpgp_len = 0;
150
151 int result = gpg_sign_with_key(key_id, message, message_len, openpgp_signature, &openpgp_len);
152 if (result != 0) {
153 log_error("GPG detached signing failed for key %s", key_id);
154 return -1;
155 }
156
157 log_debug("gpg_sign_with_key returned %zu bytes", openpgp_len);
158
159 if (openpgp_len < 10) {
160 log_error("GPG signature too short: %zu bytes", openpgp_len);
161 return -1;
162 }
163
164 log_debug("Parsing OpenPGP signature packet (%zu bytes) to extract Ed25519 signature", openpgp_len);
165
166 // Parse OpenPGP signature packet format
167 // Reference: RFC 4880 Section 5.2 (Signature Packet)
168 // Format: [header][version][type][algo][hash-algo][...][signature-data]
169 size_t offset = 0;
170
171 // Parse packet header
172 uint8_t tag = openpgp_signature[offset++];
173 size_t packet_len = 0;
174
175 if ((tag & 0x40) == 0) {
176 // Old format packet
177 uint8_t length_type = tag & 0x03;
178 if (length_type == 0) {
179 packet_len = openpgp_signature[offset++];
180 } else if (length_type == 1) {
181 packet_len = (openpgp_signature[offset] << 8) | openpgp_signature[offset + 1];
182 offset += 2;
183 } else if (length_type == 2) {
184 packet_len = (openpgp_signature[offset] << 24) | (openpgp_signature[offset + 1] << 16) | (openpgp_signature[offset + 2] << 8) | openpgp_signature[offset + 3];
185 offset += 4;
186 } else {
187 log_error("Unsupported old-format packet length type: %d", length_type);
188 return -1;
189 }
190 } else {
191 // New format packet
192 uint8_t length_byte = openpgp_signature[offset++];
193 if (length_byte < 192) {
194 packet_len = length_byte;
195 } else if (length_byte < 224) {
196 packet_len = ((length_byte - 192) << 8) + openpgp_signature[offset++] + 192;
197 } else if (length_byte == 255) {
198 packet_len = (openpgp_signature[offset] << 24) | (openpgp_signature[offset + 1] << 16) | (openpgp_signature[offset + 2] << 8) | openpgp_signature[offset + 3];
199 offset += 4;
200 } else {
201 log_error("Unsupported new-format packet length encoding: %d", length_byte);
202 return -1;
203 }
204 }
205
206 if (offset + packet_len > openpgp_len) {
207 log_error("Packet length exceeds signature size: %zu + %zu > %zu", offset, packet_len, openpgp_len);
208 return -1;
209 }
210
211 log_debug("Signature packet: offset=%zu, length=%zu", offset, packet_len);
212
213 // Parse signature packet body
214 // Skip: version (1), sig_type (1), pub_algo (1), hash_algo (1)
215 if (offset + 4 > openpgp_len) {
216 log_error("Signature packet too short for header");
217 return -1;
218 }
219
220 uint8_t version = openpgp_signature[offset++];
221 uint8_t sig_type = openpgp_signature[offset++];
222 uint8_t pub_algo = openpgp_signature[offset++];
223 uint8_t hash_algo = openpgp_signature[offset++];
224
225 log_debug("Signature: version=%d, type=%d, algo=%d, hash=%d", version, sig_type, pub_algo, hash_algo);
226
227 // Verify algorithm is Ed25519 (22 = EdDSA)
228 if (pub_algo != 22) {
229 log_error("Expected EdDSA algorithm (22), got %d", pub_algo);
230 return -1;
231 }
232
233 // For v4 signatures: skip hashed subpackets
234 if (version == 4) {
235 if (offset + 2 > openpgp_len) {
236 log_error("Cannot read hashed subpacket length");
237 return -1;
238 }
239 uint16_t hashed_len = (openpgp_signature[offset] << 8) | openpgp_signature[offset + 1];
240 offset += 2;
241 offset += hashed_len; // Skip hashed subpackets
242
243 if (offset + 2 > openpgp_len) {
244 log_error("Cannot read unhashed subpacket length");
245 return -1;
246 }
247 uint16_t unhashed_len = (openpgp_signature[offset] << 8) | openpgp_signature[offset + 1];
248 offset += 2;
249 offset += unhashed_len; // Skip unhashed subpackets
250
251 // Skip left 16 bits of signed hash value
252 if (offset + 2 > openpgp_len) {
253 log_error("Cannot read hash left bits");
254 return -1;
255 }
256 offset += 2;
257 }
258
259 // Now we're at the signature data (MPI format for Ed25519)
260 // Ed25519 signature is: r (32 bytes) || s (32 bytes) = 64 bytes total
261 // In OpenPGP, each MPI is encoded as: [2-byte bit count][data]
262
263 if (offset + 2 > openpgp_len) {
264 log_error("Cannot read MPI bit count for R");
265 return -1;
266 }
267
268 uint16_t r_bits = (openpgp_signature[offset] << 8) | openpgp_signature[offset + 1];
269 offset += 2;
270 size_t r_bytes = (r_bits + 7) / 8;
271
272 log_debug("R: %d bits (%zu bytes)", r_bits, r_bytes);
273
274 if (r_bytes == 0 || r_bytes > 32) {
275 log_error("Expected a 1-32 byte R value, got %zu bytes", r_bytes);
276 return -1;
277 }
278
279 if (offset + r_bytes > openpgp_len) {
280 log_error("R value exceeds packet size");
281 return -1;
282 }
283
284 // OpenPGP MPIs omit leading zero bytes; raw signatures retain fixed-width components.
285 memset(signature_out, 0, ED25519_SIGNATURE_SIZE);
286 memcpy(signature_out + 32 - r_bytes, &openpgp_signature[offset], r_bytes);
287 offset += r_bytes;
288
289 // Read S value
290 if (offset + 2 > openpgp_len) {
291 log_error("Cannot read MPI bit count for S");
292 return -1;
293 }
294
295 uint16_t s_bits = (openpgp_signature[offset] << 8) | openpgp_signature[offset + 1];
296 offset += 2;
297 size_t s_bytes = (s_bits + 7) / 8;
298
299 log_debug("S: %d bits (%zu bytes)", s_bits, s_bytes);
300
301 if (s_bytes == 0 || s_bytes > 32) {
302 log_error("Expected a 1-32 byte S value, got %zu bytes", s_bytes);
303 return -1;
304 }
305
306 if (offset + s_bytes > openpgp_len) {
307 log_error("S value exceeds packet size");
308 return -1;
309 }
310
311 memcpy(signature_out + 64 - s_bytes, &openpgp_signature[offset], s_bytes);
312
313 log_debug("Successfully extracted 64-byte Ed25519 signature from OpenPGP packet");
314
315 // Debug: Log signature components
317 for (int i = 0; i < 32; i++) {
318 safe_snprintf(hex_r + i * 2, 3, "%02x", signature_out[i]);
319 safe_snprintf(hex_s + i * 2, 3, "%02x", signature_out[i + 32]);
320 }
321 hex_r[64] = hex_s[64] = '\0';
322 log_debug("Signature R (first 32 bytes): %s", hex_r);
323 log_debug("Signature S (last 32 bytes): %s", hex_s);
324
325 return 0;
326}
327
GPG agent connection and communication interface.
Dedicated worker for all pending errno stacks and handled history. Signal handlers may only request a...
FILE * platform_fopen(const char *name, const char *filename, const char *mode)
Definition filesystem.c:18
unsigned short uint16_t
#define SAFE_STRERROR(errnum)
#define PLATFORM_MAX_PATH_LENGTH
unsigned char uint8_t
int gpg_sign_detached_ed25519(const char *key_id, const uint8_t *message, size_t message_len, uint8_t signature_out[ED25519_SIGNATURE_SIZE])
Sign message with GPG and extract raw Ed25519 signature.
Definition signing.c:144
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
bool escape_path_for_shell(const char *path, char *out_buffer, size_t out_buffer_size)
Check if a string needs shell quoting (contains spaces or special chars).
⚙️ 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
#define CRYPTO_GPG_SIGNING_HEX_S_BUFFER_SIZE
Definition signing.c:9
#define CRYPTO_GPG_SIGNING_ESCAPED_KEY_ID_BUFFER_SIZE
Definition signing.c:8
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
🔤 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.