ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
agent.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_AGENT_SIGKEY_CMD_BUFFER_SIZE 128
9#define CRYPTO_GPG_AGENT_SETHASH_CMD_BUFFER_SIZE 256
10
14#include <ascii-chat/common.h>
16#include <ascii-chat/log/log.h>
17#include <libplatform/system.h>
18#include <libplatform/agent.h>
19#include <libplatform/pipe.h>
20
21#include <ctype.h>
22#include <errno.h>
23#include <sodium.h>
24#include <stdio.h>
25#include <stdlib.h>
26#include <string.h>
27
28#ifndef _WIN32
29#include <sys/socket.h>
30#include <sys/un.h>
31#include <unistd.h>
32#endif
33
34// Maximum response size from gpg-agent
35#define GPG_AGENT_MAX_RESPONSE 8192
36
41static int read_agent_line(pipe_t pipe, char *buf, size_t buf_size, size_t *line_len) {
42 size_t pos = 0;
43 while (pos < buf_size - 1) {
44 char c;
45 ssize_t n = platform_pipe_read(pipe, &c, 1);
46 if (n <= 0) {
47 if (n == 0) {
48 log_error("GPG agent connection closed");
49 } else {
50 log_error("Error reading from GPG agent");
51 }
52 return -1;
53 }
54
55 if (c == '\n') {
56 buf[pos] = '\0';
57 if (line_len)
58 *line_len = pos;
59 return 0;
60 }
61
62 buf[pos++] = c;
63 }
64
65 log_error("GPG agent response too long");
66 return -1;
67}
68
72static int send_agent_command(pipe_t pipe, const char *command) {
73 size_t len = strlen(command);
74 char *cmd_with_newline;
75 cmd_with_newline = SAFE_MALLOC(len + 2, char *);
76 if (!cmd_with_newline) {
77 log_error("Failed to allocate memory for command");
78 return -1;
79 }
80
81 memcpy(cmd_with_newline, command, len);
82 cmd_with_newline[len] = '\n';
83 cmd_with_newline[len + 1] = '\0';
84
85 ssize_t sent = platform_pipe_write(pipe, cmd_with_newline, len + 1);
86 SAFE_FREE(cmd_with_newline);
87
88 if (sent != (ssize_t)(len + 1)) {
89 log_error("Failed to send command to GPG agent");
90 return -1;
91 }
92
93 return 0;
94}
95
99static bool is_ok_response(const char *line) {
100 return strncmp(line, "OK", 2) == 0;
101}
102
104 char agent_path[PLATFORM_MAX_PATH_LENGTH];
105 if (platform_get_gpg_agent_socket(agent_path, sizeof(agent_path)) != 0) {
106 log_error("Failed to get GPG agent path");
107 return -1;
108 }
109
110 log_debug("Connecting to GPG agent at: %s", agent_path);
111
112 // Use platform abstraction for pipe/socket connection
113 pipe_t pipe = platform_pipe_connect(agent_path);
114 if (!platform_pipe_is_valid(pipe)) {
115 log_error("Failed to connect to GPG agent");
116 return -1;
117 }
118
119 // Read initial greeting
120 char response[GPG_AGENT_MAX_RESPONSE];
121 if (read_agent_line(pipe, response, sizeof(response), NULL) != 0) {
122 log_error("Failed to read GPG agent greeting");
123 platform_pipe_close(pipe);
124 return -1;
125 }
126
127 if (!is_ok_response(response)) {
128 log_error("Unexpected GPG agent greeting: %s", response);
129 platform_pipe_close(pipe);
130 return -1;
131 }
132
133 log_debug("Connected to GPG agent successfully");
134
135 // Set loopback pinentry mode to avoid interactive prompts
136 // This allows GPG agent to work in non-interactive environments
137 if (send_agent_command(pipe, "OPTION pinentry-mode=loopback") != 0) {
138 log_warn("Failed to set loopback pinentry mode (continuing anyway)");
139 } else {
140 // Read response for OPTION command
141 if (read_agent_line(pipe, response, sizeof(response), NULL) != 0) {
142 log_warn("Failed to read OPTION command response (continuing anyway)");
143 } else if (is_ok_response(response)) {
144 log_debug("Loopback pinentry mode enabled");
145 } else {
146 log_warn("Failed to enable loopback pinentry mode: %s (continuing anyway)", response);
147 }
148 }
149
150 return (int)(intptr_t)pipe;
151}
152
153void gpg_agent_disconnect(int handle_as_int) {
154 if (handle_as_int >= 0) {
155 pipe_t pipe = (pipe_t)(intptr_t)handle_as_int;
156 send_agent_command(pipe, "BYE");
157 platform_pipe_close(pipe);
158 }
159}
160
161int gpg_agent_sign(int handle_as_int, const char *keygrip, const uint8_t *message, size_t message_len, uint8_t *signature_out, size_t *signature_len_out) {
162 if (handle_as_int < 0 || !keygrip || !message || !signature_out || !signature_len_out) {
163 log_error("Invalid arguments");
164 return -1;
165 }
166
167 pipe_t handle = (pipe_t)(intptr_t)handle_as_int;
168 char response[GPG_AGENT_MAX_RESPONSE];
169
170 // 1. Set the key to use (SIGKEY command)
172 safe_snprintf(sigkey_cmd, sizeof(sigkey_cmd), "SIGKEY %s", keygrip);
173 if (send_agent_command(handle, sigkey_cmd) != 0) {
174 log_error("Failed to send SIGKEY command");
175 return -1;
176 }
177
178 if (read_agent_line(handle, response, sizeof(response), NULL) != 0) {
179 log_error("Failed to read SIGKEY response");
180 return -1;
181 }
182
183 if (!is_ok_response(response)) {
184 log_error("SIGKEY failed: %s", response);
185 return -1;
186 }
187
188 // 2. For EdDSA/Ed25519, GPG agent requires SETHASH with a hash algorithm
189 // GPG agent doesn't support --inquire for SETHASH - the command syntax is:
190 // SETHASH (--hash=<name>)|(<algonumber>) <hexstring>
191 // For Ed25519, we hash the message with SHA512 (algo 10) first
192
193 // Hash the message with SHA512 using libsodium
194 uint8_t hash[crypto_hash_sha512_BYTES];
195 crypto_hash_sha512(hash, message, message_len);
196
197 // Build SETHASH command with SHA512 hash (algo 10)
198 // Format: "SETHASH 10 <128 hex chars for 64-byte SHA512 hash>"
200 int offset = safe_snprintf(sethash_cmd, sizeof(sethash_cmd), "SETHASH 10 ");
201 for (size_t i = 0; i < crypto_hash_sha512_BYTES; i++) {
202 offset += safe_snprintf(sethash_cmd + offset, sizeof(sethash_cmd) - (size_t)offset, "%02X", hash[i]);
203 }
204
205 log_debug("Sending SETHASH command with SHA512 hash");
206 if (send_agent_command(handle, sethash_cmd) != 0) {
207 log_error("Failed to send SETHASH command");
208 return -1;
209 }
210
211 // Read SETHASH response
212 if (read_agent_line(handle, response, sizeof(response), NULL) != 0) {
213 log_error("Failed to read SETHASH response");
214 return -1;
215 }
216
217 if (!is_ok_response(response)) {
218 log_error("SETHASH failed: %s", response);
219 return -1;
220 }
221
222 // 3. Request signature using PKSIGN
223 if (send_agent_command(handle, "PKSIGN") != 0) {
224 log_error("Failed to send PKSIGN command");
225 return -1;
226 }
227
228 // Read response - skip status/error lines and wait for data line (D ...)
229 // GPG agent sends informational ERR lines that are not fatal (e.g., "Not implemented")
230 // Keep reading until we get the actual signature data
231 bool found_data = false;
232 size_t response_len = 0;
233 for (int attempts = 0; attempts < 20; attempts++) {
234 if (read_agent_line(handle, response, sizeof(response), &response_len) != 0) {
235 log_error("Failed to read PKSIGN response");
236 return -1;
237 }
238
239 log_debug("PKSIGN response line %d (%zu bytes)", attempts + 1, response_len);
240
241 // Skip status lines (S INQUIRE_MAXLEN, etc)
242 if (response[0] == 'S' && response[1] == ' ') {
243 log_debug("Skipping PKSIGN status line: %s", response);
244 continue;
245 }
246
247 // Skip informational ERR lines (GPG agent sends these even on success)
248 // Common ERR codes: 67109141 (IPC cancelled), 67108933 (Not implemented)
249 if (strncmp(response, "ERR", 3) == 0) {
250 log_debug("Skipping PKSIGN error line (informational): %s", response);
251 continue;
252 }
253
254 // Check if it's a data line (D followed by space)
255 if (response[0] == 'D' && response[1] == ' ') {
256 log_debug("Found signature data line");
257 found_data = true;
258 break;
259 }
260
261 // Check for OK (success without data would be unexpected)
262 if (strncmp(response, "OK", 2) == 0) {
263 log_warn("PKSIGN returned OK without data line");
264 continue; // Keep trying in case D line follows
265 }
266
267 // Check if GPG agent is sending another INQUIRE (shouldn't happen)
268 if (strncmp(response, "INQUIRE", 7) == 0) {
269 log_error("Unexpected INQUIRE after PKSIGN: %s", response);
270 return -1;
271 }
272
273 // Unknown response type
274 log_warn("Unexpected PKSIGN response (attempt %d): %s", attempts + 1, response);
275 }
276
277 if (!found_data) {
278 log_error("Expected D line from PKSIGN after %d attempts", 20);
279 return -1;
280 }
281
282 // Assuan escapes binary bytes as %HH. Decode before reading canonical S-expression fields.
284 size_t decoded_len = 0;
285 for (size_t input = 2; input < response_len; ++input) {
286 if (decoded_len == sizeof(decoded)) {
287 log_error("GPG agent signature response exceeds buffer");
288 return -1;
289 }
290 if (response[input] == '%') {
291 if (response_len - input < 3 || !isxdigit((unsigned char)response[input + 1]) || !isxdigit((unsigned char)response[input + 2])) {
292 log_error("Invalid percent escape in GPG agent signature");
293 return -1;
294 }
295 char hex[3] = {response[input + 1], response[input + 2], 0};
296 decoded[decoded_len++] = (uint8_t)strtoul(hex, NULL, 16);
297 input += 2;
298 } else {
299 decoded[decoded_len++] = (uint8_t)response[input];
300 }
301 }
302 static const char prefix[] = "(7:sig-val(5:eddsa(1:r32:";
303 static const char separator[] = ")(1:s32:";
304 static const char suffix[] = ")))";
305 const size_t prefix_len = sizeof(prefix) - 1;
306 const size_t separator_len = sizeof(separator) - 1;
307 const size_t expected_len = prefix_len + 32 + separator_len + 32 + sizeof(suffix) - 1;
308 if (decoded_len != expected_len || memcmp(decoded, prefix, prefix_len) != 0 || memcmp(decoded + prefix_len + 32, separator, separator_len) != 0 ||
309 memcmp(decoded + expected_len - (sizeof(suffix) - 1), suffix, sizeof(suffix) - 1) != 0) {
310 log_error("Invalid Ed25519 signature S-expression from GPG agent");
311 return -1;
312 }
313 memcpy(signature_out, decoded + prefix_len, ED25519_SIGNATURE_PART_SIZE);
314 memcpy(signature_out + ED25519_SIGNATURE_PART_SIZE, decoded + prefix_len + 32 + separator_len, ED25519_SIGNATURE_PART_SIZE);
315 *signature_len_out = 64;
316
317 // DEBUG: Print signature in hex
318 char sig_hex[HEX_STRING_SIZE_64];
319 for (int i = 0; i < 64; i++) {
320 safe_snprintf(sig_hex + i * 2, 3, "%02x", (unsigned char)signature_out[i]);
321 }
322 sig_hex[128] = '\0';
323 log_debug("Extracted signature (64 bytes): %s", sig_hex);
324
325 // Read final OK
326 if (read_agent_line(handle, response, sizeof(response), &response_len) != 0) {
327 log_error("Failed to read final PKSIGN response");
328 return -1;
329 }
330
331 if (!is_ok_response(response)) {
332 log_error("PKSIGN final response not OK: %s", response);
333 return -1;
334 }
335
336 log_debug("Successfully signed message with GPG agent");
337 return 0;
338}
339
341 int sock = gpg_agent_connect();
342 if (sock < 0) {
343 return false;
344 }
346 return true;
347}
#define CRYPTO_GPG_AGENT_SIGKEY_CMD_BUFFER_SIZE
Definition agent.c:8
#define CRYPTO_GPG_AGENT_SETHASH_CMD_BUFFER_SIZE
Definition agent.c:9
#define GPG_AGENT_MAX_RESPONSE
Definition agent.c:35
GPG agent connection and communication interface.
Dedicated worker for all pending errno stacks and handled history. Signal handlers may only request a...
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
#define PLATFORM_MAX_PATH_LENGTH
unsigned char uint8_t
bool gpg_agent_is_available(void)
Check if GPG agent is available.
Definition agent.c:340
int gpg_agent_connect(void)
Connect to gpg-agent.
Definition agent.c:103
int gpg_agent_sign(int handle_as_int, const char *keygrip, const uint8_t *message, size_t message_len, uint8_t *signature_out, size_t *signature_len_out)
Sign a message using GPG agent.
Definition agent.c:161
void gpg_agent_disconnect(int handle_as_int)
Disconnect from gpg-agent.
Definition agent.c:153
#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
📝 Logging API with multiple log levels and terminal output control
#define ED25519_SIGNATURE_PART_SIZE
Definition sizes.h:7
#define HEX_STRING_SIZE_64
Hex string size for 64-byte values (128 hex chars + null terminator).
Definition sizes.h:160
🔤 String Manipulation and Shell Escaping Utilities