ascii-chat
Binary v0.16.85-2-g17e7930f4
Library lib/v0.3.2-3021-g17e7930f4
Video chat in your terminal
Loading...
Searching...
No Matches
lib/crypto/handshake/server.c
Go to the documentation of this file.
1
6
7/* Storage capacities in elements; text buffers include the terminating NUL. */
8#define CRYPTO_HANDSHAKE_SERVER_HEX_IDENTITY_BUFFER_SIZE 65
9
10#include <recast/defer.h>
12#include <ascii-chat/otel.h>
14
17#include <ascii-chat/buffer.h>
18#include <ascii-chat/common.h>
24#include <stdio.h>
25#include <string.h>
26
27// Server: Send CRYPTO_PARAMETERS packet and set context sizes
29 if (!ctx || !transport) {
30 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: ctx=%p, transport=%p", (void *)ctx, (void *)transport);
31 }
32
33 bool has_identity_key = (ctx->server_private_key.type == KEY_TYPE_ED25519);
34
36 memset(&params, 0, sizeof(params));
37
39 params.selected_auth = has_identity_key ? AUTH_ALGO_ED25519 : AUTH_ALGO_NONE;
41 params.verification_enabled = ctx->require_client_auth ? 1 : 0;
46 params.hmac_size = 32; // SHA256 output size
47
48 if (has_identity_key) {
51 }
52
53 // Set context sizes to match what we send (host byte order)
55
56 // Convert to network byte order for the wire
57 params.kex_public_key_size = htons(params.kex_public_key_size);
58 params.auth_public_key_size = htons(params.auth_public_key_size);
59 params.signature_size = htons(params.signature_size);
60 params.shared_secret_size = htons(params.shared_secret_size);
61
62 int result = packet_send_via_transport(transport, PACKET_TYPE_CRYPTO_PARAMETERS, (uint8_t *)&params, sizeof(params), 0);
63 if (result != ASCIICHAT_OK) {
64 return SET_ERRNO(ERROR_NETWORK, "Failed to send CRYPTO_PARAMETERS packet");
65 }
66
67 log_debug("[HANDSHAKE] CRYPTO_PARAMETERS sent: auth=%s, cipher=XSALSA20_POLY1305", has_identity_key ? "ED25519" : "NONE");
68 return ASCIICHAT_OK;
69}
70
71// Server: Start crypto handshake by sending public key
73 ASCII_OTEL_SCOPE(CRYPTO_HANDSHAKE_SERVER_START);
74 log_debug("[HANDSHAKE_START] ctx=%p, transport=%p", (void *)ctx, (void *)transport);
75
76 if (!ctx || ctx->state != CRYPTO_HANDSHAKE_INIT) {
77 log_error("[HANDSHAKE_START] FAILED: Invalid state - ctx=%p, state=%d", (void *)ctx, ctx ? (int)ctx->state : -1);
78 return SET_ERRNO(ERROR_INVALID_STATE, "Invalid state: ctx=%p, state=%d", (void *)ctx, ctx ? (int)ctx->state : -1);
79 }
80 log_debug("[HANDSHAKE_START] State check OK: state=%d (CRYPTO_HANDSHAKE_INIT)", ctx->state);
81
82 int result;
83
84 // Caller is responsible for sending CRYPTO_PARAMETERS and calling
85 // crypto_handshake_set_parameters() before this function. This function
86 // only handles KEY_EXCHANGE_INIT.
87
88 // Calculate packet size based on negotiated crypto parameters
89 size_t expected_packet_size = ctx->crypto_ctx.public_key_size + ctx->crypto_ctx.auth_public_key_size + ctx->crypto_ctx.signature_size;
90
91 log_debug("SERVER_KEY_EXCHANGE: kex_size=%u, auth_size=%u, sig_size=%u, expected_size=%zu", ctx->crypto_ctx.public_key_size, ctx->crypto_ctx.auth_public_key_size, ctx->crypto_ctx.signature_size,
92 expected_packet_size);
93
94 // Check if we have an identity key to send authenticated packet
96 // Extended packet format:
97 // [ephemeral_key:kex_size][identity_key:auth_size][signature:sig_size]
98 uint8_t *extended_packet;
99 extended_packet = SAFE_MALLOC(expected_packet_size, uint8_t *);
100 if (!extended_packet) {
101 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate memory for extended packet");
102 }
103
104 // Copy ephemeral public key
105 memcpy(extended_packet, ctx->crypto_ctx.public_key, ctx->crypto_ctx.public_key_size);
106
107 // Copy identity public key
108 memcpy(extended_packet + ctx->crypto_ctx.public_key_size, ctx->server_public_key.key, ctx->crypto_ctx.auth_public_key_size);
109
110 // DEBUG: Print identity key being sent
111 char hex[HEX_STRING_SIZE_32];
112 for (int i = 0; i < ED25519_PUBLIC_KEY_SIZE; i++) {
113 safe_snprintf(hex + i * 2, 3, "%02x", ctx->server_public_key.key[i]);
114 }
115 hex[HEX_STRING_SIZE_32 - 1] = '\0';
116
117 // Sign the ephemeral key with our identity key
118 log_debug("Signing ephemeral key with server identity key");
119
120 // Log key details in debug mode
122 for (int i = 0; i < 32; i++) {
123 safe_snprintf(hex_ephemeral + i * 2, 3, "%02x", ctx->crypto_ctx.public_key[i]);
124 safe_snprintf(hex_identity + i * 2, 3, "%02x", ctx->server_public_key.key[i]);
125 }
126 hex_ephemeral[64] = hex_identity[64] = '\0';
127 log_debug("SERVER: Ephemeral key (32 bytes): %s", hex_ephemeral);
128 log_debug("SERVER: Identity public key: %s", hex_identity);
129
131 extended_packet + ctx->crypto_ctx.public_key_size + ctx->crypto_ctx.auth_public_key_size) != 0) {
132 SAFE_FREE(extended_packet);
133 return SET_ERRNO(ERROR_CRYPTO, "Failed to sign ephemeral key with identity key");
134 }
135
136 log_debug("Sending authenticated KEY_EXCHANGE_INIT (%zu bytes: ephemeral + "
137 "identity + signature)",
138 expected_packet_size);
139 log_debug("[HANDSHAKE_START] Calling packet_send_via_transport(type=%d, payload_len=%zu, 0)...", PACKET_TYPE_CRYPTO_KEY_EXCHANGE_INIT, expected_packet_size);
140 result = packet_send_via_transport(transport, PACKET_TYPE_CRYPTO_KEY_EXCHANGE_INIT, extended_packet, expected_packet_size, 0);
141 log_debug("[HANDSHAKE_START] packet_send_via_transport returned %d", result);
142 SAFE_FREE(extended_packet);
143 } else {
144 // No identity key - send just the ephemeral key
145 log_debug("Sending simple KEY_EXCHANGE_INIT (%zu bytes: ephemeral key only)", ctx->crypto_ctx.public_key_size);
146 log_debug("[HANDSHAKE_START] Calling packet_send_via_transport(type=%d, payload_len=%zu, 0)...", PACKET_TYPE_CRYPTO_KEY_EXCHANGE_INIT, ctx->crypto_ctx.public_key_size);
148 log_debug("[HANDSHAKE_START] packet_send_via_transport returned %d", result);
149 }
150
151 if (result != ASCIICHAT_OK) {
152 log_error("[HANDSHAKE_START] FAILED: packet_send returned %d", result);
153 return SET_ERRNO(ERROR_NETWORK, "Failed to send KEY_EXCHANGE_INIT packet");
154 }
155 log_debug("[HANDSHAKE_START] ===== SUCCESS: KEY_EXCHANGE_INIT sent =====");
156
158
159 return ASCIICHAT_OK;
160}
161// Server: Process client's public key and send auth challenge
163 ASCII_OTEL_SCOPE(CRYPTO_HANDSHAKE_SERVER_AUTH_CHALLENGE);
164 if (!ctx || ctx->state != CRYPTO_HANDSHAKE_KEY_EXCHANGE) {
165 return SET_ERRNO(ERROR_INVALID_STATE, "Invalid state: ctx=%p, state=%d", ctx, ctx ? (int)ctx->state : -1);
166 }
167 if (!transport) {
168 return SET_ERRNO(ERROR_INVALID_PARAM, "transport is NULL");
169 }
170
171 // Note: Packet already received by ACIP handler
172 int result;
173
174 // Check if client sent NO_ENCRYPTION response
175 if (packet_type == PACKET_TYPE_CRYPTO_NO_ENCRYPTION) {
176
177 // Send AUTH_FAILED to inform client (though they already know)
178 auth_failure_packet_t failure = {0};
179 failure.reason_flags = 0; // No specific auth failure, just encryption mismatch
180 int send_result = packet_send_via_transport(transport, PACKET_TYPE_CRYPTO_AUTH_FAILED, &failure, sizeof(failure), 0);
181 if (send_result != 0) {
182 return SET_ERRNO(ERROR_NETWORK, "Failed to send AUTH_FAILED packet");
183 }
184
185 return SET_ERRNO(ERROR_CRYPTO, "SECURITY: Client sent NO_ENCRYPTION response - encryption mode "
186 "mismatch. Server requires encryption, but "
187 "client has --no-encrypt. Use matching encryption settings on "
188 "both client and server");
189 }
190
191 // Verify packet type
192 if (packet_type != PACKET_TYPE_CRYPTO_KEY_EXCHANGE_RESP) {
193 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Expected KEY_EXCHANGE_RESPONSE, got packet type %d", packet_type);
194 }
195
196 // Verify payload size - client can send either simple or authenticated format
197 // Simple: kex_public_key_size bytes
198 // Authenticated: public_key_size + client_auth_key_size + client_sig_size bytes
199 size_t simple_size = ctx->crypto_ctx.public_key_size;
200 // Ed25519 public key is always 32 bytes
201 // Ed25519 signature is always 64 bytes
203
204 bool client_sent_identity = false;
205 const size_t identity_size = ED25519_PUBLIC_KEY_SIZE;
206 const size_t signature_size = ED25519_SIGNATURE_SIZE;
207 SAFE_MALLOC_DEFER_FREE(client_ephemeral_key, ctx->crypto_ctx.public_key_size, uint8_t *);
208 SAFE_MALLOC_DEFER_FREE(client_identity_key, identity_size, uint8_t *);
209 SAFE_MALLOC_DEFER_FREE(client_signature, signature_size, uint8_t *);
210
211 if (!client_ephemeral_key || !client_identity_key || !client_signature) {
212 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate memory for client keys");
213 }
214
215 // Validate packet size using session parameters
217 if (validation_result != ASCIICHAT_OK) {
218 // Payload ownership remains with caller
219
220 return validation_result;
221 }
222
223 // Handle both authenticated and non-authenticated responses
224 // authenticated_size is now a minimum - packet may be larger with GPG key ID
225 if (payload_len >= authenticated_size) {
226 // Authenticated format (may have optional GPG key ID):
227 // [ephemeral:kex_size][identity:auth_size][signature:sig_size][gpg_key_id_len:1][gpg_key_id:0-16]
228 memcpy(client_ephemeral_key, payload, ctx->crypto_ctx.public_key_size);
229 memcpy(client_identity_key, payload + ctx->crypto_ctx.public_key_size, ED25519_PUBLIC_KEY_SIZE);
230 memcpy(client_signature, payload + ctx->crypto_ctx.public_key_size + ED25519_PUBLIC_KEY_SIZE, ED25519_SIGNATURE_SIZE);
231 client_sent_identity = true;
232 ctx->client_sent_identity = true;
233
234 // Extract GPG key ID if present
235 const char *client_gpg_key_id = NULL;
236 char gpg_key_id_buffer[GPG_FINGERPRINT_HEX_BUFFER_SIZE] = {0};
238 if (payload_len > gpg_offset) {
239 uint8_t gpg_key_id_len = payload[gpg_offset];
240 if (gpg_key_id_len > 0 && gpg_key_id_len <= 40 && payload_len >= gpg_offset + 1 + gpg_key_id_len) {
241 memcpy(gpg_key_id_buffer, payload + gpg_offset + 1, gpg_key_id_len);
242 gpg_key_id_buffer[gpg_key_id_len] = '\0';
243 client_gpg_key_id = gpg_key_id_buffer;
244 log_debug("Extracted client GPG key ID from KEY_EXCHANGE_RESPONSE: %s", client_gpg_key_id);
245 }
246 }
247
248 // Check if client sent a null identity key (all zeros)
249 bool client_has_null_identity = true;
250 for (size_t i = 0; i < ED25519_PUBLIC_KEY_SIZE; i++) {
251 if (client_identity_key[i] != 0) {
252 client_has_null_identity = false;
253 break;
254 }
255 }
256
257 if (client_has_null_identity) {
258 // Client has no identity key - this is allowed for servers without client authentication
259 log_debug("Client sent null identity key - no client authentication required");
260 client_sent_identity = false;
261 ctx->client_sent_identity = false;
262 NOTICE(WARNING, "UNVERIFIED CLIENT IDENTITY", "Client connected without identity authentication");
263 } else {
264 // Client has a real identity key
265 // If server didn't specify --client-keys, skip signature verification
266 // (server doesn't care about client identity verification)
267 if (!ctx->require_client_auth) {
268 log_info("Skipping client signature verification (no --client-keys specified)");
269 NOTICE(WARNING, "UNVERIFIED CLIENT IDENTITY", "Connection is encrypted but client identity is NOT verified");
270 } else {
271 // Verify client's signature
272 log_debug("Verifying client's signature");
273 // Pass client's GPG key ID if available
274 if (ed25519_verify_signature(client_identity_key, client_ephemeral_key, ctx->crypto_ctx.public_key_size, client_signature, client_gpg_key_id) != 0) {
275 // Send AUTH_FAILED with specific reason
276 auth_failure_packet_t failure = {0};
278 int send_result = packet_send_via_transport(transport, PACKET_TYPE_CRYPTO_AUTH_FAILED, &failure, sizeof(failure), 0);
279 if (send_result != 0) {
280 return SET_ERRNO(ERROR_NETWORK, "Failed to send AUTH_FAILED packet");
281 }
282
283 return SET_ERRNO(ERROR_CRYPTO, "Client signature verification FAILED - rejecting connection");
284 }
285 }
286 }
287
288 // Store the verified client identity for whitelist checking (only if client has identity)
289 if (client_sent_identity) {
291 memcpy(ctx->client_ed25519_key.key, client_identity_key, ctx->crypto_ctx.public_key_size);
292 }
293 } else if (payload_len == simple_size) {
294 // Non-authenticated format: [ephemeral:public_key_size] only
295 log_debug("Client sent non-authenticated response (%zu bytes)", payload_len);
296 memcpy(client_ephemeral_key, payload, ctx->crypto_ctx.public_key_size);
297 client_sent_identity = false;
298 ctx->client_sent_identity = false;
299 NOTICE(WARNING, "UNVERIFIED CLIENT IDENTITY", "Client connected without identity authentication");
300 } else {
301 // Payload ownership remains with caller
302
304 "Invalid client key response size: %zu bytes (expected %zu for "
305 "authenticated or %zu for simple)",
306 payload_len, authenticated_size, simple_size);
307 }
308
309 // Extract pointers for compatibility with existing code
310 const uint8_t *client_x25519 = client_ephemeral_key;
311 const uint8_t *client_ed25519 = client_sent_identity ? client_identity_key : NULL;
312
313 // Check client Ed25519 key against whitelist if client provided one and
314 // whitelist is enabled
315 if (client_sent_identity && ctx->require_client_auth && ctx->client_whitelist && ctx->num_whitelisted_clients > 0) {
316 bool key_found = false;
317
318 // Debug: print client's Ed25519 identity key
319 char client_ed25519_hex[HEX_STRING_SIZE_32];
320 for (int i = 0; i < ED25519_PUBLIC_KEY_SIZE; i++) {
321 safe_snprintf(client_ed25519_hex + i * 2, 3, "%02x", client_ed25519[i]);
322 }
323 log_debug("Client Ed25519 identity key: %s", client_ed25519_hex);
324
325 // Compare against whitelist (direct Ed25519 comparison - no conversion!)
326 for (size_t i = 0; i < ctx->num_whitelisted_clients; i++) {
327 // Debug: print whitelist Ed25519 key
328 char whitelist_ed25519_hex[HEX_STRING_SIZE_32];
329 for (int j = 0; j < ED25519_PUBLIC_KEY_SIZE; j++) {
330 safe_snprintf(whitelist_ed25519_hex + j * 2, 3, "%02x", ctx->client_whitelist[i].key[j]);
331 }
332 log_debug("Whitelist[%zu] Ed25519 key: %s", i, whitelist_ed25519_hex);
333
334 // Direct comparison of Ed25519 keys (constant-time to prevent timing
335 // attacks)
336 if (sodium_memcmp(client_ed25519, ctx->client_whitelist[i].key, ED25519_PUBLIC_KEY_SIZE) == 0) {
337 key_found = true;
338 ctx->client_ed25519_key_verified = true;
339
340 // Store the client's Ed25519 key for signature verification
341 memcpy(&ctx->client_ed25519_key, &ctx->client_whitelist[i], sizeof(public_key_t));
342
343 log_debug("Client Ed25519 key authorized (whitelist entry %zu)", i);
344 if (strlen(ctx->client_whitelist[i].comment) > 0) {
345 log_info("Client identity: %s", ctx->client_whitelist[i].comment);
346 }
347 break;
348 }
349 }
350
351 if (!key_found) {
352 SET_ERRNO(ERROR_CRYPTO_AUTH, "Client Ed25519 key not in whitelist - rejecting connection");
353 // Don't send AUTH_FAILED here - wait until server_complete
354 // Just mark that the key was rejected
355 ctx->client_ed25519_key_verified = false;
356 }
357 } else if (client_sent_identity) {
358 // No whitelist checking - just store the client's Ed25519 key for later
359 // (Already stored at line 313-314, but keep this for clarity)
360 // Discovery can require proof of identity without restricting which identities may join.
361 // require_client_auth ensured that the signature was verified above.
363 }
364
365 // Set peer's X25519 encryption key - this also derives the shared secret
366 crypto_result_t crypto_result = crypto_set_peer_public_key(&ctx->crypto_ctx, client_x25519);
367 if (crypto_result != CRYPTO_OK) {
368 return SET_ERRNO(ERROR_CRYPTO, "Failed to set peer public key and derive shared secret: %s", crypto_result_to_string(crypto_result));
369 }
370
371 // Do authentication challenge if client provided identity key OR server
372 // requires password
373 if (client_sent_identity || ctx->crypto_ctx.has_password || ctx->require_client_auth) {
374 // Generate nonce and store it in the context
375 crypto_result = crypto_generate_nonce(ctx->crypto_ctx.auth_nonce);
376 if (crypto_result != CRYPTO_OK) {
377 return SET_ERRNO(ERROR_CRYPTO, "Failed to generate nonce: %s", crypto_result_to_string(crypto_result));
378 }
379
380 // Prepare AUTH_CHALLENGE packet: 1 byte flags + auth_challenge_size byte nonce
381 size_t challenge_packet_size = AUTH_CHALLENGE_FLAGS_SIZE + ctx->crypto_ctx.auth_challenge_size;
382 uint8_t challenge_packet[1 + HMAC_SHA256_SIZE]; // Maximum size buffer
383 uint8_t auth_flags = 0;
384
385 // Set flags based on server requirements
386 if (ctx->crypto_ctx.has_password) {
387 auth_flags |= AUTH_REQUIRE_PASSWORD;
388 }
389 if (ctx->require_client_auth) {
390 auth_flags |= AUTH_REQUIRE_CLIENT_KEY;
391 }
392
393 challenge_packet[0] = auth_flags;
394 memcpy(challenge_packet + 1, ctx->crypto_ctx.auth_nonce, ctx->crypto_ctx.auth_challenge_size);
395
396 // Send AUTH_CHALLENGE with flags + nonce (challenge_packet_size bytes)
397 result = packet_send_via_transport(transport, PACKET_TYPE_CRYPTO_AUTH_CHALLENGE, challenge_packet, challenge_packet_size, 0);
398 if (result != 0) {
399 return SET_ERRNO(ERROR_NETWORK, "Failed to send AUTH_CHALLENGE packet");
400 }
401
403 } else {
404 // No authentication needed - skip to completion
405 log_debug("Skipping authentication (no password and client has no identity key)");
406
407 // Send HANDSHAKE_COMPLETE immediately
409 if (result != 0) {
410 return SET_ERRNO(ERROR_NETWORK, "Failed to send HANDSHAKE_COMPLETE packet");
411 }
412
414 ctx->crypto_ctx.handshake_complete = true; // Mark crypto context as ready for rekeying
415 log_debug("Crypto handshake completed successfully (no authentication)");
416 }
417
418 return ASCIICHAT_OK;
419}
420// Server: Process auth response and complete handshake
422 ASCII_OTEL_SCOPE(CRYPTO_HANDSHAKE_SERVER_COMPLETE);
423 if (!ctx || ctx->state != CRYPTO_HANDSHAKE_AUTHENTICATING) {
424 return SET_ERRNO(ERROR_INVALID_STATE, "Invalid state: ctx=%p, state=%d", ctx, ctx ? (int)ctx->state : -1);
425 }
426 if (!transport) {
427 return SET_ERRNO(ERROR_INVALID_PARAM, "transport is NULL");
428 }
429
430 // Note: Packet already received by ACIP handler
431 int result;
432
433 // Verify packet type
434 if (packet_type != PACKET_TYPE_CRYPTO_AUTH_RESPONSE) {
435 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Expected AUTH_RESPONSE, got packet type %d", packet_type);
436 }
437
438 // Verify password if required
439 if (ctx->crypto_ctx.has_password) {
440 // Validate packet size using session parameters
442 if (validation_result != ASCIICHAT_OK) {
443 return validation_result;
444 }
445
446 // Ensure shared secret is derived before password verification
447 // This is critical for password HMAC verification which binds to the shared secret
449 SET_ERRNO(ERROR_CRYPTO, "Password authentication failed - key exchange not complete");
450
451 // Send AUTH_FAILED with specific reason
452 auth_failure_packet_t failure = {0};
454 if (ctx->require_client_auth) {
456 }
457 packet_send_via_transport(transport, PACKET_TYPE_CRYPTO_AUTH_FAILED, &failure, sizeof(failure), 0);
458 return ERROR_NETWORK;
459 }
460
461 // Verify password HMAC (binds to DH shared_secret to prevent MITM)
462 log_debug("Verifying password HMAC: has_password=%d, key_exchange_complete=%d", ctx->crypto_ctx.has_password, ctx->crypto_ctx.key_exchange_complete);
463 if (!payload) {
464 SET_ERRNO(ERROR_INVALID_PARAM, "Payload is NULL in password authentication");
465 return ERROR_CRYPTO;
466 }
467 if (!crypto_verify_auth_response(&ctx->crypto_ctx, ctx->crypto_ctx.auth_nonce, payload)) {
468 log_debug("Password HMAC verification failed");
469 // Enhanced error message when both password and whitelist are required
470 if (ctx->require_client_auth) {
471 SET_ERRNO(ERROR_CRYPTO, "Password authentication failed - incorrect password (server also requires whitelisted client key)");
472 } else {
473 SET_ERRNO(ERROR_CRYPTO, "Password authentication failed - incorrect password");
474 }
475
476 // Send AUTH_FAILED with specific reason
477 auth_failure_packet_t failure = {0};
479 if (ctx->require_client_auth) {
481 }
482 packet_send_via_transport(transport, PACKET_TYPE_CRYPTO_AUTH_FAILED, &failure, sizeof(failure), 0);
483 return ERROR_NETWORK;
484 }
485
486 // Extract client challenge nonce for mutual authentication
487 // Use ctx->crypto_ctx.hmac_size and ctx->crypto_ctx.auth_challenge_size (negotiated during handshake)
489 log_info("Password authentication successful");
490 } else {
491 // Ed25519 signature auth (payload format: signature + client_nonce + gpg_key_id_len + gpg_key_id)
492 size_t expected_min_signature_size = ctx->crypto_ctx.signature_size + ctx->crypto_ctx.auth_challenge_size + 1; // +1 for gpg_key_id_len byte
493 size_t expected_password_size = ctx->crypto_ctx.hmac_size + ctx->crypto_ctx.auth_challenge_size;
494 if (!payload) {
495 SET_ERRNO(ERROR_INVALID_PARAM, "Payload is NULL in signature authentication");
496 return ERROR_CRYPTO;
497 }
498 if (payload_len >= expected_min_signature_size) {
499 // Signature + client nonce + optional GPG key ID - VERIFY the signature on the challenge nonce
500 const uint8_t *signature = payload;
501 const uint8_t *client_nonce = payload + ctx->crypto_ctx.signature_size;
502
503 // Extract GPG key ID if present
504 size_t gpg_offset = ctx->crypto_ctx.signature_size + ctx->crypto_ctx.auth_challenge_size;
505 uint8_t gpg_key_id_len = payload[gpg_offset];
506 const char *client_gpg_key_id = NULL;
507 char gpg_key_id_buffer[GPG_FINGERPRINT_HEX_BUFFER_SIZE] = {0};
508
509 if (gpg_key_id_len > 0 && gpg_key_id_len <= 40) {
510 // Validate packet has enough bytes for GPG key ID
511 if (payload_len >= gpg_offset + 1 + gpg_key_id_len) {
512 memcpy(gpg_key_id_buffer, payload + gpg_offset + 1, gpg_key_id_len);
513 gpg_key_id_buffer[gpg_key_id_len] = '\0';
514 client_gpg_key_id = gpg_key_id_buffer;
515 log_debug("Extracted client GPG key ID from AUTH_RESPONSE: %s", client_gpg_key_id);
516 }
517 }
518
519 // Actually verify the Ed25519/GPG signature on the challenge nonce
520 // This was missing, allowing authentication bypass
522 // Use unified verification function that handles both Ed25519 and GPG keys
523 // This matches the KEY_EXCHANGE verification path
524 log_debug("Verifying %s signature on challenge nonce", ctx->client_ed25519_key.type == KEY_TYPE_GPG ? "GPG" : "Ed25519");
525
527 client_gpg_key_id // GPG key ID for fallback verification
528 );
529
530 if (verify_result != ASCIICHAT_OK) {
531 auth_failure_packet_t failure = {0};
533 SET_ERRNO(ERROR_CRYPTO_AUTH, "%s signature verification failed on challenge nonce", ctx->client_ed25519_key.type == KEY_TYPE_GPG ? "GPG" : "Ed25519");
534 packet_send_via_transport(transport, PACKET_TYPE_CRYPTO_AUTH_FAILED, &failure, sizeof(failure), 0);
535 return ERROR_CRYPTO_AUTH;
536 }
537 log_debug("%s signature on challenge nonce verified successfully", ctx->client_ed25519_key.type == KEY_TYPE_GPG ? "GPG" : "Ed25519");
538 }
539
540 memcpy(ctx->client_challenge_nonce, client_nonce, ctx->crypto_ctx.auth_challenge_size);
541 } else if (payload_len == expected_password_size) {
542 // Just client nonce (legacy or password-only mode without password enabled)
543 // Use ctx->crypto_ctx.hmac_size and ctx->crypto_ctx.auth_challenge_size (negotiated during handshake)
545 } else {
546 // Validate packet size using session parameters
548 if (validation_result != ASCIICHAT_OK) {
549 return validation_result;
550 }
551 }
552 }
553
554 // Verify client key if required (whitelist)
555 if (ctx->require_client_auth) {
556 if (!ctx->client_ed25519_key_verified) {
557 // Send AUTH_FAILED with specific reason
558 auth_failure_packet_t failure = {0};
559
560 // Check if client provided a key but it wasn't in whitelist
561 if (ctx->client_sent_identity) {
562 SET_ERRNO(ERROR_CRYPTO_AUTH, "Client key authentication failed - your key is not in the server's whitelist");
564 } else {
565 SET_ERRNO(ERROR_CRYPTO_AUTH, "Client key authentication failed - client did not provide a key");
567 }
568
569 if (ctx->crypto_ctx.has_password) {
570 // Password was verified, but key was not
571 SET_ERRNO(ERROR_CRYPTO_AUTH, "Note: Password was correct, but client key is required");
572 }
573 packet_send_via_transport(transport, PACKET_TYPE_CRYPTO_AUTH_FAILED, &failure, sizeof(failure), 0);
574 return ERROR_NETWORK;
575 }
576 log_info("Client key authentication successful (whitelist verified)");
577 if (strlen(ctx->client_ed25519_key.comment) > 0) {
578 log_info("Authenticated client: %s", ctx->client_ed25519_key.comment);
579 }
580 }
581
582 // Send SERVER_AUTH_RESPONSE with server's HMAC for mutual authentication
583 // Bind to DH shared_secret to prevent MITM (even if attacker knows password)
584 // Allocate buffer using negotiated hmac_size (should match AUTH_HMAC_SIZE)
585 uint8_t server_hmac[HMAC_SHA256_SIZE]; // Maximum size, actual size is ctx->hmac_size
586 crypto_result_t crypto_result = crypto_compute_auth_response(&ctx->crypto_ctx, ctx->client_challenge_nonce, server_hmac);
587 if (crypto_result != CRYPTO_OK) {
588 SET_ERRNO(ERROR_CRYPTO, "Failed to compute server HMAC for mutual authentication: %s", crypto_result_to_string(crypto_result));
589 return ERROR_NETWORK;
590 }
591
592 log_debug("Sending SERVER_AUTH_RESPONSE packet with server HMAC (%u bytes) "
593 "for mutual authentication",
594 ctx->crypto_ctx.hmac_size);
596 if (result != ASCIICHAT_OK) {
597 SET_ERRNO(ERROR_NETWORK, "Failed to send SERVER_AUTH_RESPONSE packet");
598 return ERROR_NETWORK;
599 }
600
602 ctx->crypto_ctx.handshake_complete = true;
603 log_debug("Crypto handshake completed successfully (mutual authentication)");
604
605 return ASCIICHAT_OK;
606}
Synchronized per-thread pending error stacks and value snapshots. SET_ERRNO pushes,...
#define SET_ERRNO(code,...)
asciichat_error_t crypto_handshake_validate_packet_size(const crypto_handshake_context_t *ctx, uint16_t packet_type, size_t packet_size)
Validate crypto packet size based on session parameters.
asciichat_error_t crypto_handshake_set_parameters(crypto_handshake_context_t *ctx, const crypto_parameters_packet_t *params)
Set crypto parameters from crypto_parameters_packet_t.
GPG operations - main header.
#define SAFE_FREE(ptr)
#define SAFE_MALLOC_DEFER_FREE(name, size, cast)
#define SAFE_MALLOC(size, cast)
unsigned char uint8_t
crypto_result_t crypto_set_peer_public_key(crypto_context_t *ctx, const uint8_t *peer_public_key)
Set peer's public key and compute shared secret (step 2 of handshake).
const char * crypto_result_to_string(crypto_result_t result)
Convert crypto result to human-readable string.
crypto_result_t
Cryptographic operation result codes.
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_INVALID_STATE
@ ERROR_NETWORK
Definition error_codes.h:76
@ ERROR_NETWORK_PROTOCOL
Definition error_codes.h:80
@ ERROR_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_CRYPTO_AUTH
Definition error_codes.h:99
@ ERROR_CRYPTO
Definition error_codes.h:97
@ ERROR_INVALID_PARAM
uint8_t key[CRYPTO_PUBLIC_KEY_SIZE]
Definition key_types.h:78
key_type_t type
Definition key_types.h:102
char comment[MAX_COMMENT_LEN]
Definition key_types.h:79
key_type_t type
Definition key_types.h:77
@ KEY_TYPE_ED25519
Definition key_types.h:58
@ KEY_TYPE_GPG
Definition key_types.h:60
#define log_error(...)
Log an ERROR message.
Definition log/log.h:604
#define log_info(...)
Log an INFO message.
Definition log/log.h:578
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:565
#define AUTH_ALGO_ED25519
Ed25519 authentication (Edwards-curve signatures).
Definition packet.h:1144
#define KEX_ALGO_X25519
X25519 key exchange (Curve25519).
Definition packet.h:1143
packet_type_t
Network protocol packet type enumeration.
Definition packet.h:315
#define AUTH_ALGO_NONE
No authentication (plaintext mode).
Definition packet.h:1145
#define CIPHER_ALGO_NONE
No encryption (plaintext mode).
Definition packet.h:1147
#define CIPHER_ALGO_XSALSA20_POLY1305
XSalsa20-Poly1305 authenticated encryption.
Definition packet.h:1146
@ AUTH_FAIL_PASSWORD_INCORRECT
Password verification failed (incorrect password).
Definition packet.h:816
@ AUTH_FAIL_CLIENT_KEY_REQUIRED
Server requires client key but client didn't provide one.
Definition packet.h:818
@ AUTH_FAIL_CLIENT_KEY_REJECTED
Client key not in whitelist (access denied).
Definition packet.h:820
@ AUTH_FAIL_SIGNATURE_INVALID
Client signature verification failed (invalid signature).
Definition packet.h:822
@ PACKET_TYPE_CRYPTO_AUTH_RESPONSE
Client -> Server: {HMAC[32]} (UNENCRYPTED).
Definition packet.h:346
@ PACKET_TYPE_CRYPTO_HANDSHAKE_COMPLETE
Server -> Client: "encryption ready" (UNENCRYPTED).
Definition packet.h:352
@ PACKET_TYPE_CRYPTO_KEY_EXCHANGE_INIT
Server -> Client: {server_pubkey[32]} (UNENCRYPTED).
Definition packet.h:340
@ PACKET_TYPE_CRYPTO_KEY_EXCHANGE_RESP
Client -> Server: {client_pubkey[32]} (UNENCRYPTED).
Definition packet.h:342
@ PACKET_TYPE_CRYPTO_AUTH_FAILED
Server -> Client: "authentication failed" (UNENCRYPTED).
Definition packet.h:348
@ PACKET_TYPE_CRYPTO_SERVER_AUTH_RESP
Server -> Client: {HMAC[32]} server proves knowledge (UNENCRYPTED).
Definition packet.h:350
@ PACKET_TYPE_CRYPTO_NO_ENCRYPTION
Client -> Server: "I want to proceed without encryption" (UNENCRYPTED).
Definition packet.h:354
@ PACKET_TYPE_CRYPTO_AUTH_CHALLENGE
Server -> Client: {nonce[32]} (UNENCRYPTED).
Definition packet.h:344
@ PACKET_TYPE_CRYPTO_PARAMETERS
Server -> Client: Chosen algorithms + data sizes (UNENCRYPTED).
Definition packet.h:338
struct acip_transport acip_transport_t
Forward declaration of ACIP transport.
Definition host.h:508
⚙️ Common definitions, error codes, macros, and types shared throughout the application
#define AUTH_REQUIRE_PASSWORD
Server requires password authentication.
#define AUTH_REQUIRE_CLIENT_KEY
Server requires client key authentication (whitelist).
Server-side handshake functions.
Transport abstraction layer for ACIP protocol.
bool crypto_verify_auth_response(const crypto_context_t *ctx, const uint8_t nonce[AUTH_CHALLENGE_SIZE], const uint8_t expected_hmac[HMAC_SHA256_SIZE])
crypto_result_t crypto_generate_nonce(uint8_t nonce[AUTH_CHALLENGE_SIZE])
crypto_result_t crypto_compute_auth_response(const crypto_context_t *ctx, const uint8_t nonce[AUTH_CHALLENGE_SIZE], uint8_t hmac_out[HMAC_SHA256_SIZE])
asciichat_error_t crypto_handshake_server_send_parameters(crypto_handshake_context_t *ctx, acip_transport_t *transport)
Server: Send CRYPTO_PARAMETERS and set handshake context sizes.
#define CRYPTO_HANDSHAKE_SERVER_HEX_IDENTITY_BUFFER_SIZE
asciichat_error_t crypto_handshake_server_complete(crypto_handshake_context_t *ctx, acip_transport_t *transport, packet_type_t packet_type, const uint8_t *payload, size_t payload_len)
Server: Process auth response and complete handshake.
asciichat_error_t crypto_handshake_server_auth_challenge(crypto_handshake_context_t *ctx, acip_transport_t *transport, packet_type_t packet_type, const uint8_t *payload, size_t payload_len)
Server: Process client's public key and send auth challenge.
asciichat_error_t crypto_handshake_server_start(crypto_handshake_context_t *ctx, acip_transport_t *transport)
Server: Start crypto handshake by sending public key.
#define NOTICE(severity, title,...)
Definition notice.h:56
#define ASCII_OTEL_SCOPE(id)
Definition otel.h:81
asciichat_error_t packet_send_via_transport(acip_transport_t *transport, packet_type_t type, const void *payload, size_t payload_len, uint32_t client_id)
Definition send.c:183
ACIP shared/bidirectional packet sending functions.
#define ED25519_SIGNATURE_SIZE
Ed25519 signature size in bytes.
Definition sizes.h:41
#define HMAC_SHA256_SIZE
HMAC-SHA256 output size in bytes.
Definition sizes.h:47
#define GPG_FINGERPRINT_HEX_BUFFER_SIZE
Definition sizes.h:172
#define ED25519_PUBLIC_KEY_SIZE
Ed25519 public key size in bytes.
Definition sizes.h:37
#define CRYPTO_SHARED_KEY_SIZE
Shared key size (X25519).
Definition sizes.h:75
#define XSALSA20_NONCE_SIZE
XSalsa20 nonce size in bytes.
Definition sizes.h:43
#define HEX_STRING_SIZE_32
Hex string size for 32-byte values (64 hex chars + null terminator).
Definition sizes.h:158
#define AUTH_CHALLENGE_FLAGS_SIZE
Authentication flags size (1 byte).
Definition sizes.h:119
#define POLY1305_MAC_SIZE
Poly1305 MAC size in bytes.
Definition sizes.h:45
asciichat_error_t ed25519_sign_message(const private_key_t *key, const uint8_t *message, size_t message_len, uint8_t signature[ED25519_SIGNATURE_SIZE])
Definition ssh_keys.c:1109
asciichat_error_t ed25519_verify_signature(const uint8_t public_key[ED25519_PUBLIC_KEY_SIZE], const uint8_t *message, size_t message_len, const uint8_t signature[ED25519_SIGNATURE_SIZE], const char *gpg_key_id)
Definition ssh_keys.c:1209
🔤 String Manipulation and Shell Escaping Utilities
Authentication failure packet structure.
Definition packet.h:833
uint8_t reason_flags
Bitmask of auth_failure_reason_t values indicating failure causes.
Definition packet.h:835
Cryptographic handshake context structure.
bool allow_unlisted_client_identity
Require proof of key possession without whitelist membership (discovery).
Crypto parameters packet structure (Packet Type 15).
Definition packet.h:1060
uint8_t hmac_size
HMAC size in bytes (e.g., 32 for HMAC-SHA256).
Definition packet.h:1082
uint8_t selected_kex
Selected key exchange algorithm (KEX_ALGO_*).
Definition packet.h:1062
uint8_t selected_cipher
Selected cipher algorithm (CIPHER_ALGO_*).
Definition packet.h:1066
uint16_t auth_public_key_size
Authentication public key size in bytes (e.g., 32 for Ed25519, 1952 for Dilithium3).
Definition packet.h:1072
uint8_t selected_auth
Selected authentication algorithm (AUTH_ALGO_*).
Definition packet.h:1064
uint8_t verification_enabled
Server verification enabled flag (1=enabled, 0=disabled).
Definition packet.h:1068
uint16_t signature_size
Signature size in bytes (e.g., 64 for Ed25519, 3309 for Dilithium3).
Definition packet.h:1074
uint8_t nonce_size
Nonce size in bytes (e.g., 24 for XSalsa20).
Definition packet.h:1078
uint8_t mac_size
MAC size in bytes (e.g., 16 for Poly1305).
Definition packet.h:1080
uint16_t shared_secret_size
Shared secret size in bytes (e.g., 32 for X25519).
Definition packet.h:1076
uint16_t kex_public_key_size
Key exchange public key size in bytes (e.g., 32 for X25519, 1568 for Kyber1024).
Definition packet.h:1070
The normalized public identity used by ascii-chat's crypto and key-management code.
Definition key_types.h:76