ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
ssh_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_SSH_SSH_AGENT_PIPE_PATH_BUFFER_SIZE 256
9
12#include <ascii-chat/common.h>
13#include <ascii-chat/util/bytes.h> // For write_u32_be, read_u32_be
14#include <stdio.h>
15#include <stdlib.h>
16#include <string.h>
17#include <sodium.h>
18#include <libplatform/pipe.h>
19#include <libplatform/agent.h>
20#include <ascii-chat/log/log.h>
21
22#ifdef _WIN32
23#include <io.h>
24#include <sys/stat.h>
25#include <fcntl.h>
26#else
27#include <unistd.h>
28#include <sys/stat.h>
29#include <fcntl.h>
30#endif
31
32// Open the SSH agent pipe/socket
33static pipe_t ssh_agent_open_pipe(void) {
35 if (platform_get_ssh_agent_socket(pipe_path, sizeof(pipe_path)) != 0) {
36 log_debug("Failed to get SSH agent socket path");
37 return INVALID_PIPE_VALUE;
38 }
39 return platform_pipe_connect(pipe_path);
40}
41
43 /* Try to open the SSH agent connection */
44 pipe_t pipe = ssh_agent_open_pipe();
45 if (pipe != INVALID_PIPE_VALUE) {
46 platform_pipe_close(pipe);
47 log_dev("ssh-agent is available");
48 return true;
49 }
50 log_dev("ssh-agent not available");
51 return false;
52}
53
54bool ssh_agent_has_key(const public_key_t *public_key) {
55 if (public_key == NULL) {
56 log_warn("NULL is not a valid public key");
57 return false;
58 }
59
60 // Use SSH agent protocol to list keys (works on both Windows and Unix)
61 pipe_t pipe = ssh_agent_open_pipe();
62 if (pipe == INVALID_PIPE_VALUE) {
63 return false;
64 }
65
66 // Build SSH2_AGENTC_REQUEST_IDENTITIES message (type 11)
67 unsigned char request[5];
68 request[0] = 0; // length: 1 (4-byte big-endian)
69 request[1] = 0;
70 request[2] = 0;
71 request[3] = 1;
72 request[4] = 11; // SSH2_AGENTC_REQUEST_IDENTITIES
73
74 // Send request
75 ssize_t bytes_written = platform_pipe_write(pipe, request, 5);
76 if (bytes_written != 5) {
77 platform_pipe_close(pipe);
78 return false;
79 }
80
81 // Read response
82 unsigned char response[BUFFER_SIZE_XXXLARGE];
83 ssize_t bytes_read = platform_pipe_read(pipe, response, sizeof(response));
84 if (bytes_read < 9) {
85 platform_pipe_close(pipe);
86 return false;
87 }
88
89 platform_pipe_close(pipe);
90
91 // Parse response: type should be SSH2_AGENT_IDENTITIES_ANSWER (12)
92 uint8_t resp_type = response[4];
93 if (resp_type != 12) {
94 return false;
95 }
96
97 // Number of keys at bytes 5-8
98 uint32_t num_keys = read_u32_be(response + 5);
99
100 // Parse keys and check if our public key matches
101 size_t pos = 9;
102 for (uint32_t i = 0; i < num_keys && pos + 4 < (size_t)bytes_read; i++) {
103 // Read key blob length
104 uint32_t blob_len = read_u32_be(response + pos);
105 pos += 4;
106
107 if (pos + blob_len > (size_t)bytes_read)
108 break;
109
110 // Parse the blob to extract the Ed25519 public key
111 size_t blob_pos = pos;
112 // Skip key type string
113 if (blob_pos + 4 > pos + blob_len) {
114 pos += blob_len;
115 continue;
116 }
117 uint32_t type_len = read_u32_be(response + blob_pos);
118 blob_pos += 4 + type_len;
119
120 // Read public key data
121 if (blob_pos + 4 > pos + blob_len) {
122 pos += blob_len;
123 continue;
124 }
125 uint32_t pubkey_len = read_u32_be(response + blob_pos);
126 blob_pos += 4;
127
128 // Compare public key (should be 32 bytes for Ed25519)
129 // Use constant-time comparison to prevent timing side channels
130 if (pubkey_len == 32 && blob_pos + 32 <= pos + blob_len) {
131 if (sodium_memcmp(response + blob_pos, public_key->key, 32) == 0) {
132 log_debug("Found matching key in ssh-agent");
133 return true;
134 }
135 }
136
137 pos += blob_len;
138
139 // Skip comment string length + comment
140 if (pos + 4 > (size_t)bytes_read)
141 break;
142 uint32_t comment_len = read_u32_be(response + pos);
143 pos += 4 + comment_len;
144 }
145
146 return false;
147}
148
149asciichat_error_t ssh_agent_add_key(const private_key_t *private_key, const char *key_path) {
150 if (private_key == NULL) {
151 return SET_ERRNO(ERROR_INVALID_PARAM, "Cannot add key to ssh-agent: private_key is NULL");
152 }
153 if (private_key->type != KEY_TYPE_ED25519) {
154 return SET_ERRNO(ERROR_INVALID_PARAM, "Cannot add key to ssh-agent: only Ed25519 keys supported");
155 }
156
157 log_debug("Adding key to ssh-agent: %s", key_path ? key_path : "(memory)");
158
159 // Open the pipe/socket for this operation (works on both Windows and Unix)
160 pipe_t pipe = ssh_agent_open_pipe();
161 if (pipe == INVALID_PIPE_VALUE) {
162 return SET_ERRNO(ERROR_CRYPTO, "Failed to connect to ssh-agent");
163 }
164
165 // Build SSH agent protocol message: SSH2_AGENTC_ADD_IDENTITY (17)
166 // Message format:
167 // uint32: message length
168 // byte: SSH2_AGENTC_ADD_IDENTITY (17)
169 // string: key type ("ssh-ed25519")
170 // string: public key (32 bytes)
171 // string: private key (64 bytes)
172 // string: comment (key path or empty)
173
174 unsigned char buf[BUFFER_SIZE_XXLARGE];
175 size_t pos = 4; // Reserve space for length prefix
176
177 // Message type: SSH2_AGENTC_ADD_IDENTITY
178 buf[pos++] = 17;
179
180 // Key type: "ssh-ed25519" (11 bytes)
181 uint32_t len = 11;
182 write_u32_be(buf + pos, len);
183 pos += 4;
184 // Binary protocol: intentionally not null-terminated
185 // NOLINTNEXTLINE(bugprone-not-null-terminated-result) - binary data
186 memcpy(buf + pos, "ssh-ed25519", 11);
187 pos += 11;
188
189 // Public key (32 bytes) - last 32 bytes of the 64-byte ed25519 key
190 len = 32;
191 write_u32_be(buf + pos, len);
192 pos += 4;
193 memcpy(buf + pos, private_key->key.ed25519 + ED25519_SEED_SIZE, ED25519_PUBLIC_KEY_SIZE); // Public key is second half
194 pos += 32;
195
196 // Private key (64 bytes - full ed25519 key: 32-byte seed + 32-byte public)
197 len = 64;
198 write_u32_be(buf + pos, len);
199 pos += 4;
200 memcpy(buf + pos, private_key->key.ed25519, ED25519_PRIVATE_KEY_SIZE);
201 pos += 64;
202
203 // Comment (key path)
204 len = key_path ? strlen(key_path) : 0;
205
206 // SECURITY: Validate key path length to prevent buffer overflow
207 // Buffer is BUFFER_SIZE_XXLARGE (4096), pos is ~128 at this point, need 4 bytes for length prefix
208 size_t max_key_path_len = sizeof(buf) - pos - 4;
209 if (len > max_key_path_len) {
210 platform_pipe_close(pipe);
211 sodium_memzero(buf, sizeof(buf));
212 return SET_ERRNO(ERROR_BUFFER_OVERFLOW, "SSH key path too long: %u bytes (max %zu)", len, max_key_path_len);
213 }
214
215 write_u32_be(buf + pos, len);
216 pos += 4;
217 if (len > 0) {
218 memcpy(buf + pos, key_path, len);
219 pos += len;
220 }
221
222 // Write message length at start (excluding the 4-byte length field itself)
223 uint32_t msg_len = pos - 4;
224 write_u32_be(buf, msg_len);
225
226 // Send message to agent
227 ssize_t bytes_written = platform_pipe_write(pipe, buf, pos);
228 if (bytes_written != (ssize_t)pos) {
229 platform_pipe_close(pipe);
230 sodium_memzero(buf, sizeof(buf));
231 return SET_ERRNO_SYS(ERROR_CRYPTO, "Failed to write to ssh-agent pipe");
232 }
233
234 // Read response
235 unsigned char response[BUFFER_SIZE_SMALL];
236 ssize_t bytes_read = platform_pipe_read(pipe, response, sizeof(response));
237 if (bytes_read < 5) {
238 platform_pipe_close(pipe);
239 sodium_memzero(buf, sizeof(buf));
240 return SET_ERRNO_SYS(ERROR_CRYPTO, "Failed to read from ssh-agent pipe");
241 }
242
243 // Done with the pipe - close it
244 platform_pipe_close(pipe);
245 sodium_memzero(buf, sizeof(buf));
246
247 // Check response: should be SSH_AGENT_SUCCESS (6)
248 // Response format: uint32 length, byte message_type
249 uint8_t response_type = response[4];
250 if (response_type == 6) {
251 log_debug("Successfully added key to ssh-agent");
252 return ASCIICHAT_OK;
253 } else if (response_type == 5) {
254 return SET_ERRNO(ERROR_CRYPTO, "ssh-agent rejected key (SSH_AGENT_FAILURE)");
255 } else {
256 return SET_ERRNO(ERROR_CRYPTO, "ssh-agent returned unexpected response: %d", response_type);
257 }
258}
259
260asciichat_error_t ssh_agent_sign(const public_key_t *public_key, const uint8_t *message, size_t message_len, uint8_t signature[ED25519_SIGNATURE_SIZE]) {
261 if (!public_key || !message || !signature) {
262 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: public_key=%p, message=%p, signature=%p", public_key, message, signature);
263 }
264
265 if (public_key->type != KEY_TYPE_ED25519) {
266 return SET_ERRNO(ERROR_CRYPTO_KEY, "Only Ed25519 keys are supported for SSH agent signing");
267 }
268
269 // SSH agent protocol limits message size (typical OpenSSH agent limit is around 1MB)
270 // Large messages can cause agent memory exhaustion or timeout
271 if (message_len > 1024 * 1024) {
272 return SET_ERRNO(ERROR_CRYPTO, "Message too large for SSH agent (max 1MB)");
273 }
274
275 // Connect to SSH agent
276 pipe_t pipe = ssh_agent_open_pipe();
277 if (pipe == INVALID_PIPE_VALUE) {
278 return SET_ERRNO(ERROR_CRYPTO, "Cannot connect to ssh-agent");
279 }
280
281 // Build SSH2_AGENTC_SIGN_REQUEST message (type 13)
282 // Format: uint32 length, byte type, string key_blob, string data, uint32 flags
283 // For Ed25519, key_blob is: string "ssh-ed25519", string public_key(32 bytes)
284
285 const char *key_type = "ssh-ed25519";
286 uint32_t key_type_len = (uint32_t)strlen(key_type);
287
288 // Calculate total message length
289 // 1 (type) + 4 (key_blob_len) + key_blob_size + 4 (data_len) + data_size + 4 (flags)
290 uint32_t key_blob_size = 4 + key_type_len + 4 + 32; // string(key_type) + string(pubkey)
291 uint32_t total_len = 1 + 4 + key_blob_size + 4 + message_len + 4;
292
293 uint8_t *buf = SAFE_MALLOC(total_len + 4, uint8_t *); // +4 for length prefix
294 if (!buf) {
295 platform_pipe_close(pipe);
296 return SET_ERRNO(ERROR_CRYPTO, "Out of memory for SSH agent sign request");
297 }
298
299 uint32_t offset = 0;
300
301 // Write total message length (excluding this 4-byte length field)
302 write_u32_be(buf + offset, total_len);
303 offset += 4;
304
305 // Write message type (13 = SSH2_AGENTC_SIGN_REQUEST)
306 buf[offset++] = 13;
307
308 // Write key_blob length
309 write_u32_be(buf + offset, key_blob_size);
310 offset += 4;
311
312 // Write key_blob: string(key_type)
313 write_u32_be(buf + offset, key_type_len);
314 offset += 4;
315 // NOLINTNEXTLINE(bugprone-not-null-terminated-result) - binary data
316 memcpy(buf + offset, key_type, key_type_len);
317 offset += key_type_len;
318
319 // Write key_blob: string(public_key)
320 write_u32_be(buf + offset, 32);
321 offset += 4;
322 memcpy(buf + offset, public_key->key, ED25519_PUBLIC_KEY_SIZE);
323 offset += 32;
324
325 // Write data to sign
326 write_u32_be(buf + offset, (uint32_t)message_len);
327 offset += 4;
328 memcpy(buf + offset, message, message_len);
329 offset += (uint32_t)message_len;
330
331 // Write flags (0 = default)
332 write_u32_be(buf + offset, 0);
333 offset += 4;
334
335 // Send request
336 ssize_t written = platform_pipe_write(pipe, buf, total_len + 4);
337 sodium_memzero(buf, total_len + 4);
338 SAFE_FREE(buf);
339
340 if (written < 0 || (size_t)written != total_len + 4) {
341 platform_pipe_close(pipe);
342 return SET_ERRNO(ERROR_CRYPTO, "Failed to write SSH agent sign request");
343 }
344
345 // Read response
347 ssize_t read_bytes = platform_pipe_read(pipe, response, sizeof(response));
348 platform_pipe_close(pipe);
349
350 if (read_bytes < 5) {
351 return SET_ERRNO(ERROR_CRYPTO, "Failed to read SSH agent sign response (read %zd bytes)", read_bytes);
352 }
353
354 // Response format: uint32 length, byte type, data...
355 // We validate length implicitly by checking read_bytes and parsing the full response
356 (void)read_u32_be(response); // Read but don't need explicit length check
357 uint8_t response_type = response[4];
358
359 // Check for SSH2_AGENT_SIGN_RESPONSE (14)
360 if (response_type != 14) {
361 if (response_type == 5) {
362 return SET_ERRNO(ERROR_CRYPTO, "ssh-agent refused to sign (SSH_AGENT_FAILURE)");
363 }
364 return SET_ERRNO(ERROR_CRYPTO, "ssh-agent returned unexpected response type: %d (expected 14)", response_type);
365 }
366
367 // Parse signature blob
368 // Response format: uint32 len, byte type(14), string signature_blob
369 if (read_bytes < 9) {
370 return SET_ERRNO(ERROR_CRYPTO, "SSH agent response too short (no signature blob length)");
371 }
372
373 uint32_t sig_blob_len = read_u32_be(response + 5);
374 uint32_t expected_total = 4 + 1 + 4 + sig_blob_len;
375
376 if ((size_t)read_bytes < expected_total) {
377 return SET_ERRNO(ERROR_CRYPTO, "SSH agent response truncated (expected %u bytes, got %zd)", expected_total, read_bytes);
378 }
379
380 // Signature blob format for Ed25519: string "ssh-ed25519", string signature(64 bytes)
381 uint32_t offset_sig = 9;
382 uint32_t sig_type_len = read_u32_be(response + offset_sig);
383 offset_sig += 4;
384
385 if (offset_sig + sig_type_len + 4 > (uint32_t)read_bytes) {
386 return SET_ERRNO(ERROR_CRYPTO, "SSH agent signature blob truncated at signature type");
387 }
388
389 // Verify signature type is "ssh-ed25519"
390 if (sig_type_len != 11 || memcmp(response + offset_sig, "ssh-ed25519", 11) != 0) {
391 return SET_ERRNO(ERROR_CRYPTO, "SSH agent returned non-Ed25519 signature");
392 }
393 offset_sig += sig_type_len;
394
395 // Read signature bytes
396 uint32_t sig_len = read_u32_be(response + offset_sig);
397 offset_sig += 4;
398
399 if (sig_len != 64) {
400 return SET_ERRNO(ERROR_CRYPTO, "SSH agent returned invalid Ed25519 signature length: %u (expected 64)", sig_len);
401 }
402
403 if (offset_sig + 64 > (uint32_t)read_bytes) {
404 return SET_ERRNO(ERROR_CRYPTO, "SSH agent signature blob truncated at signature bytes");
405 }
406
407 // Copy signature to output
408 memcpy(signature, response + offset_sig, ED25519_SIGNATURE_SIZE);
409
410 log_debug("SSH agent successfully signed %zu bytes with Ed25519 key", message_len);
411 return ASCIICHAT_OK;
412}
#define SET_ERRNO(code,...)
#define SET_ERRNO_SYS(code,...)
🔢 Byte-Level Access and Arithmetic Utilities
#define BUFFER_SIZE_XXXLARGE
Extra extra extra large buffer size (8192 bytes).
#define BUFFER_SIZE_XXLARGE
Extra extra large buffer size (4096 bytes).
#define BUFFER_SIZE_SMALL
Small buffer size (256 bytes).
unsigned int uint32_t
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
unsigned char uint8_t
bool ssh_agent_has_key(const public_key_t *public_key)
Check if a public key is already in ssh-agent.
Definition ssh_agent.c:54
bool ssh_agent_is_available(void)
Check if ssh-agent is running and available.
Definition ssh_agent.c:42
asciichat_error_t ssh_agent_add_key(const private_key_t *private_key, const char *key_path)
Add a private key to ssh-agent.
Definition ssh_agent.c:149
asciichat_error_t ssh_agent_sign(const public_key_t *public_key, const uint8_t *message, size_t message_len, uint8_t signature[64])
Sign data using SSH agent with the specified public key.
Definition ssh_agent.c:260
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_CRYPTO
Definition error_codes.h:97
@ ERROR_INVALID_PARAM
@ ERROR_BUFFER_OVERFLOW
uint8_t key[CRYPTO_PUBLIC_KEY_SIZE]
Definition key_types.h:78
uint8_t ed25519[ED25519_PRIVATE_KEY_SIZE]
Definition key_types.h:104
key_type_t type
Definition key_types.h:102
key_type_t type
Definition key_types.h:77
union private_key_t::@040247167361101132173265304166142033301213115260 key
@ KEY_TYPE_ED25519
Definition key_types.h:58
#define log_warn(...)
Log a WARN message.
Definition log/log.h:615
#define log_dev(...)
Log a DEV message (most verbose, development only).
Definition log/log.h:575
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:589
⚙️ Common definitions, error codes, macros, and types shared throughout the application
Capture stdout/stderr and redirect to logging system.
📝 Logging API with multiple log levels and terminal output control
atomic_t bytes_written
Definition mmap.c:45
#define ED25519_SIGNATURE_SIZE
Ed25519 signature size in bytes.
Definition sizes.h:41
#define ED25519_PUBLIC_KEY_SIZE
Ed25519 public key size in bytes.
Definition sizes.h:37
#define ED25519_SEED_SIZE
Definition sizes.h:169
#define ED25519_PRIVATE_KEY_SIZE
Ed25519 private key size (seed + public) in bytes.
Definition sizes.h:39
#define CRYPTO_SSH_SSH_AGENT_PIPE_PATH_BUFFER_SIZE
Definition ssh_agent.c:8
🔤 String Manipulation and Shell Escaping Utilities
Private identity-key material used for server authentication and signing.
Definition key_types.h:101
The normalized public identity used by ascii-chat's crypto and key-management code.
Definition key_types.h:76