ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
lib/crypto/crypto.c
Go to the documentation of this file.
1
6
7/* Storage capacities in elements; text buffers include the terminating NUL. */
8#define CRYPTO_ENCRYPTED_BUFFER_SIZE 32
9#define CRYPTO_DECRYPTED_BUFFER_SIZE 32
10
14#include <ascii-chat/otel.h>
15#include <ascii-chat/common.h>
21
22#include <string.h>
23#include <time.h>
24#include <inttypes.h>
25#include <libplatform/atomic.h>
27#include <libplatform/lifecycle.h>
28
29// Lifecycle state for libsodium initialization
30static lifecycle_t g_libsodium_lc = LIFECYCLE_INIT;
31
32// Internal packet type constants (for test helper functions only)
33// These are NOT part of the main network protocol - they're used for simple
34// packet serialization in crypto module test utilities
35static const uint32_t CRYPTO_PACKET_PUBLIC_KEY = 100;
36static const uint32_t CRYPTO_PACKET_ENCRYPTED_DATA = 102;
37static const uint32_t CRYPTO_PACKET_AUTH_CHALLENGE = 103;
38static const uint32_t CRYPTO_PACKET_AUTH_RESPONSE = 104;
39
40// =============================================================================
41// Internal helper functions
42// =============================================================================
43
44// Initialize libsodium (thread-safe, exactly-once via DCL pattern)
45static crypto_result_t init_libsodium(void) {
46 if (!lifecycle_init_once(&g_libsodium_lc)) {
47 return CRYPTO_OK; // Already initialized or in progress
48 }
49
50 // We won the initialization race
51 if (sodium_init() < 0) {
52 lifecycle_init_abort(&g_libsodium_lc);
53 SET_ERRNO(ERROR_CRYPTO, "Failed to initialize libsodium");
55 }
56
57 lifecycle_init_commit(&g_libsodium_lc);
58 return CRYPTO_OK;
59}
60
61// Generate secure nonce with session ID and counter to prevent reuse
62static void generate_nonce(crypto_context_t *ctx, uint8_t *nonce_out) {
63 // Nonce format (dynamic size based on algorithm):
64 // - Bytes 0-15: Session ID (constant per connection, random across connections)
65 // - Bytes 16+: Counter (increments per packet, prevents reuse within session)
66 //
67 // The prefix and counter avoid nonce reuse when calls are serialized.
68 // Replay detection requires separate authenticated receive state.
69
70 SAFE_MEMCPY(nonce_out, 16, ctx->session_id, 16);
71
72 // Counter MUST be in big-endian (network byte order) for cross-platform compatibility
73 // between browser (JavaScript/WASM) and native (C) implementations
74 uint64_t counter = ctx->nonce_counter++;
75 uint64_t counter_be = HOST_TO_NET_U64(counter); // Convert to big-endian
76 size_t counter_size = ctx->nonce_size - 16;
77 SAFE_MEMCPY(nonce_out + 16, counter_size, &counter_be, (counter_size < sizeof(counter_be)) ? counter_size : sizeof(counter_be));
78}
79
80// Securely clear memory
81static void secure_memzero(void *ptr, size_t len) {
82 sodium_memzero(ptr, len);
83}
84
85// =============================================================================
86// Core initialization and setup
87// =============================================================================
88
90 if (!ctx) {
91 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: ctx=%p", ctx);
93 }
94
95 // Initialize libsodium
96 crypto_result_t result = init_libsodium();
97 if (result != CRYPTO_OK) {
98 return result;
99 }
100
101 // Clear context
102 secure_memzero(ctx, sizeof(crypto_context_t));
103
104 // Generate key pair for X25519 key exchange
105 result = crypto_generate_keypair(ctx);
106 if (result != CRYPTO_OK) {
107 return result;
108 }
109
110 ctx->initialized = true;
111 ctx->has_password = false;
112 ctx->key_exchange_complete = false;
113 ctx->peer_key_received = false;
114 ctx->handshake_complete = false;
115 ctx->encrypt_data = true; // Default: enable payload encryption
116 ctx->nonce_counter = 1; // Start from 1 (0 reserved for testing)
117 ctx->bytes_encrypted = 0;
118 ctx->bytes_decrypted = 0;
119
120 // Set default algorithm-specific parameters (can be overridden during handshake)
130 // signature_size and auth_public_key_size remain 0 until set by CRYPTO_PARAMETERS
131 // (must be 0 for unauthenticated format detection in crypto_handshake_client_key_exchange)
132
133 // Generate a random nonce prefix for this connection.
134 randombytes_buf(ctx->session_id, sizeof(ctx->session_id));
135
136 // Initialize rekeying state
137 ctx->rekey_packet_count = 0;
138 ctx->rekey_last_time = time(NULL); // Initialize to current time
139 ctx->rekey_last_request_time = 0; // No rekey request yet
140 ctx->rekey_in_progress = false;
141 ctx->rekey_failure_count = 0;
142 ctx->has_temp_key = false;
143 ctx->rekey_count = 0;
144
145 // SECURITY: Use production-safe rekey thresholds by default
146 // Rekey every 1 hour OR 1 million packets (whichever comes first)
147 // Only use test mode if explicitly requested via environment variable
148 if (is_test_environment()) {
151 char duration_str[TIME_DURATION_BUFFER_SIZE];
152 time_pretty(ctx->rekey_time_threshold, -1, duration_str, sizeof(duration_str));
153 log_dev("Crypto context initialized with X25519 key exchange (TEST MODE rekey thresholds: %llu packets, %s)", (unsigned long long)ctx->rekey_packet_threshold, duration_str);
154 } else {
155 ctx->rekey_packet_threshold = REKEY_DEFAULT_PACKET_THRESHOLD; // 1 million packets
156 ctx->rekey_time_threshold = REKEY_DEFAULT_TIME_THRESHOLD; // already in nanoseconds (3600 * NS_PER_SEC_INT)
157 char duration_str[TIME_DURATION_BUFFER_SIZE];
158 time_pretty(ctx->rekey_time_threshold, -1, duration_str, sizeof(duration_str));
159 log_dev("Crypto context initialized with X25519 key exchange (rekey thresholds: %llu packets, %s)", (unsigned long long)ctx->rekey_packet_threshold, duration_str);
160 }
162}
163
165 if (!ctx || !password) {
166 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: ctx=%p, password=%p", ctx, password);
168 }
169
170 if (strlen(password) == 0) {
171 SET_ERRNO(ERROR_INVALID_PARAM, "Password cannot be empty");
173 }
174
175 // First initialize basic crypto
176 crypto_result_t result = crypto_init(ctx);
177 if (result != CRYPTO_OK) {
178 return result;
179 }
180
181 // Derive password key
182 result = crypto_derive_password_key(ctx, password);
183 if (result != CRYPTO_OK) {
184 crypto_destroy(ctx);
185 return result;
186 }
187
188 ctx->has_password = true;
189
190 log_dev("Crypto context initialized with password-based encryption");
191 return CRYPTO_OK;
192}
193
195 if (!ctx || !ctx->initialized) {
196 return;
197 }
198
200
201 // Securely wipe sensitive data
202 secure_memzero(ctx->private_key, sizeof(ctx->private_key));
203 secure_memzero(ctx->shared_key, sizeof(ctx->shared_key));
204 secure_memzero(ctx->password_key, sizeof(ctx->password_key));
205 secure_memzero(ctx->password_salt, sizeof(ctx->password_salt));
206
207 char encrypted_str[CRYPTO_ENCRYPTED_BUFFER_SIZE], decrypted_str[CRYPTO_DECRYPTED_BUFFER_SIZE];
208 format_bytes_pretty(ctx->bytes_encrypted, encrypted_str, sizeof(encrypted_str));
209 format_bytes_pretty(ctx->bytes_decrypted, decrypted_str, sizeof(decrypted_str));
210
211 log_debug("Crypto context cleaned up (encrypted: %s, decrypted: %s)", encrypted_str, decrypted_str);
212
213 // Clear entire context
214 secure_memzero(ctx, sizeof(crypto_context_t));
215}
216
218 if (!ctx) {
219 SET_ERRNO(ERROR_INVALID_PARAM, "NULL context");
221 }
222
223 log_debug("About to call crypto_box_keypair");
224 // Generate X25519 key pair for key exchange
225 if (crypto_box_keypair(ctx->public_key, ctx->private_key) != 0) {
226 SET_ERRNO(ERROR_CRYPTO, "Failed to generate X25519 key pair");
228 }
229
230 log_debug("Generated X25519 key pair for key exchange");
231 return CRYPTO_OK;
232}
233
234// =============================================================================
235// Key exchange protocol (automatic HTTPS-like key exchange)
236// =============================================================================
237
239 if (!ctx || !ctx->initialized || !public_key_out) {
240 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters (ctx=%p, initialized=%d, public_key_out=%p)", ctx, ctx ? ctx->initialized : 0, public_key_out);
242 }
243
244 // Bounds check to prevent buffer overflow
245 size_t copy_size = (ctx->public_key_size <= X25519_KEY_SIZE) ? ctx->public_key_size : X25519_KEY_SIZE;
246 SAFE_MEMCPY(public_key_out, copy_size, ctx->public_key, copy_size);
247 return CRYPTO_OK;
248}
249
251 if (!ctx || !ctx->initialized || !peer_public_key) {
252 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters (ctx=%p, initialized=%d, peer_public_key=%p)", ctx, ctx ? ctx->initialized : 0, peer_public_key);
254 }
255
256 // Store peer's public key
257 // Bounds check to prevent buffer overflow
258 size_t copy_size = (ctx->public_key_size <= X25519_KEY_SIZE) ? ctx->public_key_size : X25519_KEY_SIZE;
259 SAFE_MEMCPY(ctx->peer_public_key, copy_size, peer_public_key, copy_size);
260 ctx->peer_key_received = true;
261
262 // Compute shared secret using X25519 and crypto_scalarmult (compatible with secretbox)
263 // This produces a raw 32-byte shared secret suitable for crypto_secretbox
264 if (crypto_scalarmult(ctx->shared_key, ctx->private_key, peer_public_key) != 0) {
265 SET_ERRNO(ERROR_CRYPTO, "Failed to compute shared secret from peer public key");
267 }
268
269 ctx->key_exchange_complete = true;
270
271 log_debug("Key exchange complete");
272 return CRYPTO_OK;
273}
274
276 if (!ctx || !ctx->initialized) {
277 return false;
278 }
279
280 // Ready if either key exchange is complete OR password is set
281 return ctx->key_exchange_complete || ctx->has_password;
282}
283
284// =============================================================================
285// Password-based encryption (optional additional layer)
286// =============================================================================
287
289 if (!password) {
290 SET_ERRNO(ERROR_INVALID_PARAM, "Password is NULL");
292 }
293
294 size_t password_len = strlen(password);
295
296 if (password_len < MIN_PASSWORD_LENGTH) {
297 SET_ERRNO(ERROR_INVALID_PARAM, "Password too short (minimum %d characters, got %zu)", MIN_PASSWORD_LENGTH, password_len);
299 }
300
301 if (password_len > MAX_PASSWORD_LENGTH) {
302 SET_ERRNO(ERROR_INVALID_PARAM, "Password too long (maximum %d characters, got %zu)", MAX_PASSWORD_LENGTH, password_len);
304 }
305
306 return CRYPTO_OK;
307}
308
310 if (!ctx || !ctx->initialized || !password) {
311 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters (ctx=%p, initialized=%d, password=%p)", ctx, ctx ? ctx->initialized : 0, password);
313 }
314
315 // Validate password length requirements
316 crypto_result_t validation_result = crypto_validate_password(password);
317 if (validation_result != CRYPTO_OK) {
318 return validation_result;
319 }
320
321 // Use deterministic salt for consistent key derivation across client/server
322 // This ensures the same password produces the same key on both sides
323 // Salt must be exactly ARGON2ID_SALT_SIZE (32) bytes
324 const char *deterministic_salt = "ascii-chat-password-salt-v1";
325 size_t salt_str_len = strlen(deterministic_salt);
326
327 // Zero-initialize the salt buffer first
328 memset(ctx->password_salt, 0, ctx->salt_size);
329
330 // Copy the salt string (will be padded with zeros to ctx->salt_size)
331 memcpy(ctx->password_salt, deterministic_salt, (salt_str_len < ctx->salt_size) ? salt_str_len : ctx->salt_size);
332
333 // Derive key using Argon2id (memory-hard, secure against GPU attacks)
334 if (crypto_pwhash(ctx->password_key, ctx->encryption_key_size, password, strlen(password), ctx->password_salt,
335 crypto_pwhash_OPSLIMIT_INTERACTIVE, // ~0.1 seconds
336 crypto_pwhash_MEMLIMIT_INTERACTIVE, // ~64MB
337 crypto_pwhash_ALG_DEFAULT) != 0) {
338 SET_ERRNO(ERROR_CRYPTO, "Password key derivation failed - possibly out of memory");
340 }
341
342 log_dev("Password key derived successfully using Argon2id with deterministic salt");
343 return CRYPTO_OK;
344}
345
346bool crypto_verify_password(const crypto_context_t *ctx, const char *password) {
347 if (!ctx || !ctx->initialized || !ctx->has_password || !password) {
348 return false;
349 }
350
351 uint8_t test_key[SECRETBOX_KEY_SIZE]; // Use maximum size for buffer
352
353 // Use the same deterministic salt for verification
354 // Salt must be exactly ARGON2ID_SALT_SIZE (32) bytes
355 const char *deterministic_salt = "ascii-chat-password-salt-v1";
356 uint8_t salt[ARGON2ID_SALT_SIZE]; // Use maximum size for buffer
357 size_t salt_str_len = strlen(deterministic_salt);
358
359 // Zero-initialize the salt buffer first
360 memset(salt, 0, ARGON2ID_SALT_SIZE);
361
362 // Copy the salt string (will be padded with zeros to ctx->salt_size)
363 memcpy(salt, deterministic_salt, (salt_str_len < ctx->salt_size) ? salt_str_len : ctx->salt_size);
364
365 // Derive key with same salt
366 if (crypto_pwhash(test_key, ctx->encryption_key_size, password, strlen(password), salt, crypto_pwhash_OPSLIMIT_INTERACTIVE, crypto_pwhash_MEMLIMIT_INTERACTIVE, crypto_pwhash_ALG_DEFAULT) != 0) {
367 secure_memzero(test_key, sizeof(test_key));
368 return false;
369 }
370
371 // Constant-time comparison
372 bool match = (sodium_memcmp(test_key, ctx->password_key, ctx->encryption_key_size) == 0);
373
374 secure_memzero(test_key, sizeof(test_key));
375 return match;
376}
377
378// Derive a deterministic encryption key from password for handshake
380 if (!password || !encryption_key) {
381 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters (password=%p, encryption_key=%p)", password, encryption_key);
383 }
384
385 // Validate password length requirements
386 crypto_result_t validation_result = crypto_validate_password(password);
387 if (validation_result != CRYPTO_OK) {
388 return validation_result;
389 }
390
391 // Use deterministic salt for consistent key derivation across client/server
392 // Salt must be exactly ARGON2ID_SALT_SIZE (32) bytes
393 const char *deterministic_salt = "ascii-chat-password-salt-v1";
394 uint8_t salt[ARGON2ID_SALT_SIZE]; // Use maximum size for buffer
395 size_t salt_str_len = strlen(deterministic_salt);
396
397 // Zero-initialize the salt buffer first
398 memset(salt, 0, ARGON2ID_SALT_SIZE);
399
400 // Copy the salt string (will be padded with zeros to ARGON2ID_SALT_SIZE)
401 memcpy(salt, deterministic_salt, (salt_str_len < ARGON2ID_SALT_SIZE) ? salt_str_len : ARGON2ID_SALT_SIZE);
402
403 // Derive key using Argon2id (memory-hard, secure against GPU attacks)
404 if (crypto_pwhash(encryption_key, SECRETBOX_KEY_SIZE, password, strlen(password), salt,
405 crypto_pwhash_OPSLIMIT_INTERACTIVE, // ~0.1 seconds
406 crypto_pwhash_MEMLIMIT_INTERACTIVE, // ~64MB
407 crypto_pwhash_ALG_DEFAULT) != 0) {
408 SET_ERRNO(ERROR_CRYPTO, "Password encryption key derivation failed - possibly out of memory");
410 }
411
412 log_dev("Password encryption key derived successfully using Argon2id");
413 return CRYPTO_OK;
414}
415
416// =============================================================================
417// Encryption/Decryption operations
418// =============================================================================
419
420crypto_result_t crypto_encrypt(crypto_context_t *ctx, const uint8_t *plaintext, size_t plaintext_len, uint8_t *ciphertext_out, size_t ciphertext_out_size, size_t *ciphertext_len_out) {
421 ASCII_OTEL_SCOPE(CRYPTO_ENCRYPT);
422 ASCII_OTEL_ATTR_STRING("crypto.operation", "encrypt");
423 ASCII_OTEL_ATTR_STRING("crypto.algorithm", "xsalsa20-poly1305");
424 ASCII_OTEL_ATTR_INT("crypto.input.size", (int64_t)plaintext_len);
425 ASCII_OTEL_ATTR_INT("crypto.output.capacity", (int64_t)ciphertext_out_size);
426 if (!ctx || !ctx->initialized || !plaintext || !ciphertext_out || !ciphertext_len_out) {
427 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: ctx=%p, initialized=%d, plaintext=%p, ciphertext_out=%p, ciphertext_len_out=%p", ctx, ctx ? ctx->initialized : 0, plaintext, ciphertext_out,
428 ciphertext_len_out);
430 }
431
432 if (plaintext_len == 0 || plaintext_len > CRYPTO_MAX_PLAINTEXT_SIZE) {
433 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid plaintext length: %zu (max: %d)", plaintext_len, CRYPTO_MAX_PLAINTEXT_SIZE);
435 }
436
437 if (!crypto_is_ready(ctx)) {
438 SET_ERRNO(ERROR_CRYPTO, "Crypto context not ready for encryption");
440 }
441
442 ASCII_OTEL_ATTR_INT("crypto.nonce.size", ctx->nonce_size);
443 ASCII_OTEL_ATTR_INT("crypto.mac.size", ctx->mac_size);
444 ASCII_OTEL_ATTR_INT("crypto.key.size", ctx->encryption_key_size);
445 ASCII_OTEL_ATTR_STRING("crypto.key.source", ctx->key_exchange_complete ? "x25519" : "password");
446 // Check output buffer size
447 size_t required_size = plaintext_len + ctx->nonce_size + ctx->mac_size;
448 if (ciphertext_out_size < required_size) {
449 SET_ERRNO(ERROR_BUFFER, "Ciphertext buffer too small: %zu < %zu", ciphertext_out_size, required_size);
451 }
452
453 // Check for nonce counter exhaustion (extremely unlikely in practice)
454 // Starting from 1, reaching UINT64_MAX would require ~292 billion years at 60 FPS.
455 // With key rotation required at 1M packets (~16 seconds), exhaustion is virtually impossible.
456 // This check is a safety fallback that should never trigger in practice.
457 if (ctx->nonce_counter == 0 || ctx->nonce_counter == UINT64_MAX) {
458 SET_ERRNO(ERROR_CRYPTO, "Nonce counter exhausted - key rotation required");
460 }
461
462 // Choose encryption key BEFORE generating nonce (prevents nonce_counter increment on error)
463 const uint8_t *encryption_key = NULL;
464 if (ctx->key_exchange_complete) {
465 encryption_key = ctx->shared_key;
466 } else if (ctx->has_password) {
467 encryption_key = ctx->password_key;
468 } else {
469 SET_ERRNO(ERROR_CRYPTO, "No encryption key available");
471 }
472
473 // Generate nonce and place at beginning of ciphertext
474 uint8_t nonce[XSALSA20_NONCE_SIZE]; // Use maximum nonce size for buffer
475 generate_nonce(ctx, nonce);
476 SAFE_MEMCPY(ciphertext_out, ctx->nonce_size, nonce, ctx->nonce_size);
477
478 log_debug_every(US_PER_SEC_INT, "Encrypting packet: counter=%llu plaintext_len=%zu", (unsigned long long)(ctx->nonce_counter - 1), plaintext_len);
479
480 // Encrypt using NaCl secretbox (XSalsa20 + Poly1305)
481 if (crypto_secretbox_easy(ciphertext_out + ctx->nonce_size, plaintext, plaintext_len, nonce, encryption_key) != 0) {
482 SET_ERRNO(ERROR_CRYPTO, "Encryption failed");
484 }
485
486 *ciphertext_len_out = required_size;
487 ctx->bytes_encrypted += plaintext_len;
488
489 // Increment rekey packet counter for rekeying trigger detection
490 ctx->rekey_packet_count++;
491
492 ASCII_OTEL_ATTR_INT("crypto.output.size", (int64_t)*ciphertext_len_out);
493 ascii_otel_metric(ASCII_OTEL_METRIC_CRYPTO_ENCRYPT_BYTES, (double)plaintext_len);
494 return CRYPTO_OK;
495}
496
497crypto_result_t crypto_decrypt(crypto_context_t *ctx, const uint8_t *ciphertext, size_t ciphertext_len, uint8_t *plaintext_out, size_t plaintext_out_size, size_t *plaintext_len_out) {
498 ASCII_OTEL_SCOPE(CRYPTO_DECRYPT);
499 ASCII_OTEL_ATTR_STRING("crypto.operation", "decrypt");
500 ASCII_OTEL_ATTR_STRING("crypto.algorithm", "xsalsa20-poly1305");
501 ASCII_OTEL_ATTR_INT("crypto.input.size", (int64_t)ciphertext_len);
502 ASCII_OTEL_ATTR_INT("crypto.output.capacity", (int64_t)plaintext_out_size);
503 if (!ctx || !ctx->initialized || !ciphertext || !plaintext_out || !plaintext_len_out) {
504 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: ctx=%p, initialized=%d, ciphertext=%p, plaintext_out=%p, plaintext_len_out=%p", ctx, ctx ? ctx->initialized : 0, ciphertext, plaintext_out,
505 plaintext_len_out);
507 }
508
509 if (!crypto_is_ready(ctx)) {
510 SET_ERRNO(ERROR_CRYPTO, "Crypto context not ready for decryption");
512 }
513
514 ASCII_OTEL_ATTR_INT("crypto.nonce.size", ctx->nonce_size);
515 ASCII_OTEL_ATTR_INT("crypto.mac.size", ctx->mac_size);
516 ASCII_OTEL_ATTR_INT("crypto.key.size", ctx->encryption_key_size);
517 ASCII_OTEL_ATTR_STRING("crypto.key.source", ctx->key_exchange_complete ? "x25519" : "password");
518 // Check minimum ciphertext size (nonce + MAC)
519 size_t min_ciphertext_size = ctx->nonce_size + ctx->mac_size;
520 if (ciphertext_len < min_ciphertext_size) {
521 SET_ERRNO(ERROR_INVALID_PARAM, "Ciphertext too small: %zu < %zu", ciphertext_len, min_ciphertext_size);
523 }
524
525 size_t plaintext_len = ciphertext_len - ctx->nonce_size - ctx->mac_size;
526 if (plaintext_out_size < plaintext_len) {
527 SET_ERRNO(ERROR_BUFFER, "Plaintext buffer too small: %zu < %zu", plaintext_out_size, plaintext_len);
529 }
530
531 // Extract nonce from beginning of ciphertext
532 const uint8_t *nonce = ciphertext;
533 const uint8_t *encrypted_data = ciphertext + ctx->nonce_size;
534
535 // Choose decryption key (prefer shared key over password key)
536 const uint8_t *decryption_key = NULL;
537 if (ctx->key_exchange_complete) {
538 decryption_key = ctx->shared_key;
539 } else if (ctx->has_password) {
540 decryption_key = ctx->password_key;
541 } else {
542 SET_ERRNO(ERROR_CRYPTO, "No decryption key available");
544 }
545
546 // Decrypt using NaCl secretbox (XSalsa20 + Poly1305)
547 if (crypto_secretbox_open_easy(plaintext_out, encrypted_data, ciphertext_len - ctx->nonce_size, nonce, decryption_key) != 0) {
548 log_error_every(US_PER_SEC_INT, "Decryption failed: cipherlen=%zu key_exchange_complete=%d has_password=%d (invalid MAC)", ciphertext_len - ctx->nonce_size, ctx->key_exchange_complete,
549 ctx->has_password);
550 SET_ERRNO(ERROR_CRYPTO, "Decryption failed - invalid MAC or corrupted data");
552 }
553
554 *plaintext_len_out = plaintext_len;
555 ctx->bytes_decrypted += plaintext_len;
556
557 ASCII_OTEL_ATTR_INT("crypto.output.size", (int64_t)*plaintext_len_out);
558 ASCII_OTEL_ATTR_INT("crypto.authenticated", 1);
559 ascii_otel_metric(ASCII_OTEL_METRIC_CRYPTO_DECRYPT_BYTES, (double)ciphertext_len);
560 return CRYPTO_OK;
561}
562
563// =============================================================================
564// Utility functions
565// =============================================================================
566
567// O(1) array lookup for crypto result strings (indexed by -result)
568static const char *const g_crypto_result_strings[] = {
569 "Success", // 0: CRYPTO_OK
570 "Initialization failed", // 1: -CRYPTO_ERROR_INIT_FAILED
571 "Invalid parameters", // 2: -CRYPTO_ERROR_INVALID_PARAMS
572 "Memory allocation failed", // 3: -CRYPTO_ERROR_MEMORY
573 "Libsodium error", // 4: -CRYPTO_ERROR_LIBSODIUM
574 "Key generation failed", // 5: -CRYPTO_ERROR_KEY_GENERATION
575 "Password derivation failed", // 6: -CRYPTO_ERROR_PASSWORD_DERIVATION
576 "Encryption failed", // 7: -CRYPTO_ERROR_ENCRYPTION
577 "Decryption failed", // 8: -CRYPTO_ERROR_DECRYPTION
578 "Invalid MAC or corrupted data", // 9: -CRYPTO_ERROR_INVALID_MAC
579 "Buffer too small", // 10: -CRYPTO_ERROR_BUFFER_TOO_SMALL
580 "Key exchange not complete", // 11: -CRYPTO_ERROR_KEY_EXCHANGE_INCOMPLETE
581 "Nonce counter exhausted", // 12: -CRYPTO_ERROR_NONCE_EXHAUSTED
582 "Rekey already in progress", // 13: -CRYPTO_ERROR_REKEY_IN_PROGRESS
583 "Rekey failed", // 14: -CRYPTO_ERROR_REKEY_FAILED
584 "Rekey rate limited", // 15: -CRYPTO_ERROR_REKEY_RATE_LIMITED
585};
586#define CRYPTO_RESULT_STRING_COUNT (sizeof(g_crypto_result_strings) / sizeof(g_crypto_result_strings[0]))
587
589 int idx = -result; // CRYPTO_OK=0, errors are negative
590 if (idx >= 0 && (size_t)idx < CRYPTO_RESULT_STRING_COUNT) {
591 return g_crypto_result_strings[idx];
592 }
593 return "Unknown error";
594}
595
596void crypto_get_status(const crypto_context_t *ctx, char *status_buffer, size_t buffer_size) {
597 if (!ctx || !status_buffer || buffer_size == 0) {
598 return;
599 }
600
601 if (!ctx->initialized) {
602 SAFE_SNPRINTF(status_buffer, buffer_size, "Not initialized");
603 return;
604 }
605
606 SAFE_SNPRINTF(status_buffer, buffer_size,
607 "Initialized: %s, Password: %s, Key Exchange: %s, Ready: %s, "
608 "Encrypted: %" PRIu64 " bytes, Decrypted: %" PRIu64 " bytes, Nonce: %" PRIu64,
609 ctx->initialized ? "yes" : "no", ctx->has_password ? "yes" : "no", ctx->key_exchange_complete ? "complete" : "incomplete", crypto_is_ready(ctx) ? "yes" : "no", ctx->bytes_encrypted,
610 ctx->bytes_decrypted, ctx->nonce_counter);
611}
612
613bool crypto_secure_compare(const uint8_t *lhs, const uint8_t *rhs, size_t len) {
614 if (!lhs || !rhs) {
615 return false;
616 }
617 return sodium_memcmp(lhs, rhs, len) == 0;
618}
619
621 if (!buffer || len == 0) {
622 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters (buffer=%p, len=%zu)", buffer, len);
624 }
625
626 crypto_result_t result = init_libsodium();
627 if (result != CRYPTO_OK) {
628 return result;
629 }
630
631 randombytes_buf(buffer, len);
632 return CRYPTO_OK;
633}
634
635// =============================================================================
636// Network integration helpers
637// =============================================================================
638
639crypto_result_t crypto_create_public_key_packet(const crypto_context_t *ctx, uint8_t *packet_out, size_t packet_size, size_t *packet_len_out) {
640 if (!ctx || !ctx->initialized || !packet_out || !packet_len_out) {
642 "Invalid parameters (ctx=%p, initialized=%d, packet_out=%p, "
643 "packet_len_out=%p)",
644 ctx, ctx ? ctx->initialized : 0, packet_out, packet_len_out);
646 }
647
648 size_t required_size = sizeof(uint32_t) + ctx->public_key_size; // type + key
649 if (packet_size < required_size) {
650 SET_ERRNO(ERROR_BUFFER, "Buffer too small (size=%zu, required=%zu)", packet_size, required_size);
652 }
653
654 // Pack packet: [type:4][public_key:32]
655 uint32_t packet_type = CRYPTO_PACKET_PUBLIC_KEY;
656 SAFE_MEMCPY(packet_out, sizeof(packet_type), &packet_type, sizeof(packet_type));
657 // Bounds check to prevent buffer overflow
658 size_t copy_size = (ctx->public_key_size <= X25519_KEY_SIZE) ? ctx->public_key_size : X25519_KEY_SIZE;
659 SAFE_MEMCPY(packet_out + sizeof(packet_type), copy_size, ctx->public_key, copy_size);
660
661 *packet_len_out = required_size;
662 return CRYPTO_OK;
663}
664
666 if (!ctx || !ctx->initialized || !packet) {
667 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters (ctx=%p, initialized=%d, packet=%p)", ctx, ctx ? ctx->initialized : 0, packet);
669 }
670
671 size_t expected_size = sizeof(uint32_t) + ctx->public_key_size;
672 if (packet_len != expected_size) {
673 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid packet size (expected=%zu, got=%zu)", expected_size, packet_len);
675 }
676
677 // Unpack packet: [type:4][public_key:32]
678 uint32_t packet_type;
679 SAFE_MEMCPY(&packet_type, sizeof(packet_type), packet, sizeof(packet_type));
680
681 if (packet_type != CRYPTO_PACKET_PUBLIC_KEY) {
682 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid packet type (expected=%u, got=%u)", CRYPTO_PACKET_PUBLIC_KEY, packet_type);
684 }
685
686 const uint8_t *peer_public_key = packet + sizeof(packet_type);
687 return crypto_set_peer_public_key(ctx, peer_public_key);
688}
689
690crypto_result_t crypto_create_encrypted_packet(crypto_context_t *ctx, const uint8_t *data, size_t data_len, uint8_t *packet_out, size_t packet_size, size_t *packet_len_out) {
691 if (!ctx || !data || !packet_out || !packet_len_out) {
692 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters (ctx=%p, data=%p, packet_out=%p, packet_len_out=%p)", ctx, data, packet_out, packet_len_out);
694 }
695
696 if (!crypto_is_ready(ctx)) {
697 SET_ERRNO(ERROR_CRYPTO, "Crypto context not ready");
699 }
700
701 // Validate data_len to prevent integer overflow in size calculations.
702 if (data_len > CRYPTO_MAX_PLAINTEXT_SIZE) {
703 SET_ERRNO(ERROR_INVALID_PARAM, "data_len %zu exceeds max %d", data_len, CRYPTO_MAX_PLAINTEXT_SIZE);
705 }
706
707 // Check for integer overflow: data_len + nonce_size + mac_size
708 if (data_len > SIZE_MAX - ctx->nonce_size - ctx->mac_size) {
709 SET_ERRNO(ERROR_BUFFER, "encrypted_size overflow");
711 }
712 size_t encrypted_size = data_len + ctx->nonce_size + ctx->mac_size;
713
714 // Check for integer overflow: header + encrypted_size
715 size_t header_size = sizeof(uint32_t) + sizeof(uint32_t);
716 if (encrypted_size > SIZE_MAX - header_size) {
717 SET_ERRNO(ERROR_BUFFER, "required_size overflow");
719 }
720 size_t required_size = header_size + encrypted_size; // type + len + encrypted_data
721
722 if (packet_size < required_size) {
723 SET_ERRNO(ERROR_BUFFER, "Buffer too small (size=%zu, required=%zu)", packet_size, required_size);
725 }
726
727 // Encrypt the data
728 size_t ciphertext_len;
729 uint8_t *encrypted_data = packet_out + sizeof(uint32_t) + sizeof(uint32_t);
730 crypto_result_t result = crypto_encrypt(ctx, data, data_len, encrypted_data, packet_size - sizeof(uint32_t) - sizeof(uint32_t), &ciphertext_len);
731 if (result != CRYPTO_OK) {
732 return result;
733 }
734
735 // Pack packet: [type:4][length:4][encrypted_data:var]
736 uint32_t packet_type = CRYPTO_PACKET_ENCRYPTED_DATA;
737 uint32_t data_length = (uint32_t)ciphertext_len;
738
739 SAFE_MEMCPY(packet_out, sizeof(packet_type), &packet_type, sizeof(packet_type));
740 SAFE_MEMCPY(packet_out + sizeof(packet_type), sizeof(data_length), &data_length, sizeof(data_length));
741
742 *packet_len_out = required_size;
743 return CRYPTO_OK;
744}
745
746crypto_result_t crypto_process_encrypted_packet(crypto_context_t *ctx, const uint8_t *packet, size_t packet_len, uint8_t *data_out, size_t data_size, size_t *data_len_out) {
747 if (!ctx || !packet || !data_out || !data_len_out) {
748 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters (ctx=%p, packet=%p, data_out=%p, data_len_out=%p)", ctx, packet, data_out, data_len_out);
750 }
751
752 if (!crypto_is_ready(ctx)) {
753 SET_ERRNO(ERROR_CRYPTO, "Crypto context not ready");
755 }
756
757 if (packet_len < sizeof(uint32_t) + sizeof(uint32_t)) {
758 SET_ERRNO(ERROR_INVALID_PARAM, "Packet too small (size=%zu)", packet_len);
760 }
761
762 // Unpack packet: [type:4][length:4][encrypted_data:var]
763 uint32_t packet_type;
764 uint32_t data_length;
765 SAFE_MEMCPY(&packet_type, sizeof(packet_type), packet, sizeof(packet_type));
766 SAFE_MEMCPY(&data_length, sizeof(data_length), packet + sizeof(packet_type), sizeof(data_length));
767
768 if (packet_type != CRYPTO_PACKET_ENCRYPTED_DATA) {
769 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid packet type (expected=%u, got=%u)", CRYPTO_PACKET_ENCRYPTED_DATA, packet_type);
771 }
772
773 if (packet_len != sizeof(uint32_t) + sizeof(uint32_t) + data_length) {
774 SET_ERRNO(ERROR_INVALID_PARAM, "Packet length mismatch (expected=%zu, got=%zu)", sizeof(uint32_t) + sizeof(uint32_t) + data_length, packet_len);
776 }
777
778 const uint8_t *encrypted_data = packet + sizeof(uint32_t) + sizeof(uint32_t);
779 return crypto_decrypt(ctx, encrypted_data, data_length, data_out, data_size, data_len_out);
780}
781
782// =============================================================================
783// Authentication and handshake functions
784// =============================================================================
785
787 if (!nonce) {
788 SET_ERRNO(ERROR_INVALID_PARAM, "NULL nonce buffer");
790 }
791
792 crypto_result_t result = init_libsodium();
793 if (result != CRYPTO_OK) {
794 return result;
795 }
796
797 randombytes_buf(nonce, 32);
798 return CRYPTO_OK;
799}
800
802 if (!ctx || !key || !data || !hmac) {
803 return (crypto_result_t)SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters (ctx=%p, key=%p, data=%p, hmac=%p)", ctx, key, data, hmac);
804 }
805
806 crypto_result_t result = init_libsodium();
807 if (result != CRYPTO_OK) {
808 return result;
809 }
810
811 crypto_auth_hmacsha256(hmac, data, 32, key);
812 return CRYPTO_OK;
813}
814
816 if (!ctx || !key || !data || !hmac || data_len == 0) {
817 return (crypto_result_t)SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters (ctx=%p, key=%p, data=%p, data_len=%zu, hmac=%p)", ctx, key, data, data_len, hmac);
818 }
819
820 crypto_result_t result = init_libsodium();
821 if (result != CRYPTO_OK) {
822 return result;
823 }
824
825 crypto_auth_hmacsha256(hmac, data, data_len, key);
826 return CRYPTO_OK;
827}
828
830 if (!key || !data || !expected_hmac) {
831 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters (key=%p, data=%p, expected_hmac=%p)", key, data, expected_hmac);
832 return false;
833 }
834
835 uint8_t computed_hmac[HMAC_SHA256_SIZE];
836 if (crypto_auth_hmacsha256(computed_hmac, data, 32, key) != 0) {
837 return false;
838 }
839
840 return sodium_memcmp(computed_hmac, expected_hmac, 32) == 0;
841}
842
843bool crypto_verify_hmac_ex(const uint8_t key[HMAC_SHA256_KEY_SIZE], const uint8_t *data, size_t data_len, const uint8_t expected_hmac[HMAC_SHA256_SIZE]) {
844 if (!key || !data || !expected_hmac || data_len == 0) {
845 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters (key=%p, data=%p, data_len=%zu, expected_hmac=%p)", key, data, data_len, expected_hmac);
846 return false;
847 }
848
849 uint8_t computed_hmac[HMAC_SHA256_SIZE];
850 if (crypto_auth_hmacsha256(computed_hmac, data, data_len, key) != 0) {
851 return false;
852 }
853
854 return sodium_memcmp(computed_hmac, expected_hmac, 32) == 0;
855}
856
857// =============================================================================
858// High-level authentication helpers (shared between client and server)
859// =============================================================================
860
862 if (!ctx || !nonce || !hmac_out) {
863 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters (ctx=%p, nonce=%p, hmac_out=%p)", ctx, nonce, hmac_out);
865 }
866
867 // Ensure shared secret is derived before computing HMAC
868 // This is critical for password HMAC which binds to the shared secret
869 if (!ctx->key_exchange_complete) {
870 SET_ERRNO(ERROR_CRYPTO, "Cannot compute auth response - key exchange not complete");
872 }
873
874 // Bind password HMAC to DH shared_secret to prevent MITM
875 // Combined data: nonce || shared_secret
877 memcpy(combined_data, nonce, AUTH_CHALLENGE_SIZE);
878 memcpy(combined_data + AUTH_CHALLENGE_SIZE, ctx->shared_key, CRYPTO_SHARED_KEY_SIZE);
879
880 // Use password_key if available, otherwise use shared_key
881 const uint8_t *auth_key = ctx->has_password ? ctx->password_key : ctx->shared_key;
882
883 crypto_result_t result = crypto_compute_hmac_ex(ctx, auth_key, combined_data, 64, hmac_out);
884
885 // Securely zero sensitive data containing shared secret
886 sodium_memzero(combined_data, sizeof(combined_data));
887
888 return result;
889}
890
892 if (!ctx || !nonce || !expected_hmac) {
893 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters (ctx=%p, nonce=%p, expected_hmac=%p)", ctx, nonce, expected_hmac);
894 return false;
895 }
896
897 // Ensure shared secret is derived before verifying HMAC
898 // This is critical for password HMAC verification which binds to the shared secret
899 if (!ctx->key_exchange_complete) {
900 SET_ERRNO(ERROR_CRYPTO, "Cannot verify auth response - key exchange not complete");
901 return false;
902 }
903
904 // Bind password HMAC to DH shared_secret to prevent MITM
905 // Combined data: nonce || shared_secret
907 memcpy(combined_data, nonce, AUTH_CHALLENGE_SIZE);
908 memcpy(combined_data + AUTH_CHALLENGE_SIZE, ctx->shared_key, CRYPTO_SHARED_KEY_SIZE);
909
910 // Use password_key if available, otherwise use shared_key
911 const uint8_t *auth_key = ctx->has_password ? ctx->password_key : ctx->shared_key;
912
913 log_debug("Verifying auth response: has_password=%d, key_exchange_complete=%d, using_password_key=%d", ctx->has_password, ctx->key_exchange_complete, (auth_key == ctx->password_key));
914
915 bool result = crypto_verify_hmac_ex(auth_key, combined_data, 64, expected_hmac);
916
917 // Securely zero sensitive data containing shared secret
918 sodium_memzero(combined_data, sizeof(combined_data));
919
920 return result;
921}
922
923crypto_result_t crypto_create_auth_challenge(const crypto_context_t *ctx, uint8_t *packet_out, size_t packet_size, size_t *packet_len_out) {
924 if (!ctx || !ctx->initialized || !packet_out || !packet_len_out) {
925 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters (ctx=%p, initialized=%d, packet_out=%p, packet_len_out=%p)", ctx, ctx ? ctx->initialized : 0, packet_out, packet_len_out);
927 }
928
929 size_t required_size = sizeof(uint32_t) + ctx->auth_challenge_size; // type + nonce
930 if (packet_size < required_size) {
931 SET_ERRNO(ERROR_BUFFER, "Buffer too small (size=%zu, required=%zu)", packet_size, required_size);
933 }
934
935 // Generate random nonce (stores result in ctx->auth_nonce)
937 if (result != CRYPTO_OK) {
938 return result;
939 }
940
941 // Pack packet: [type:4][nonce:auth_challenge_size]
942 uint32_t packet_type = CRYPTO_PACKET_AUTH_CHALLENGE;
943 SAFE_MEMCPY(packet_out, sizeof(packet_type), &packet_type, sizeof(packet_type));
944 SAFE_MEMCPY(packet_out + sizeof(packet_type), ctx->auth_challenge_size, ctx->auth_nonce, ctx->auth_challenge_size);
945
946 *packet_len_out = required_size;
947 return CRYPTO_OK;
948}
949
951 if (!ctx || !ctx->initialized || !packet) {
952 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters (ctx=%p, initialized=%d, packet=%p)", ctx, ctx ? ctx->initialized : 0, packet);
954 }
955
956 size_t expected_size = sizeof(uint32_t) + ctx->auth_challenge_size; // type + nonce
957 if (packet_len != expected_size) {
958 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid packet size (expected=%zu, got=%zu)", expected_size, packet_len);
960 }
961
962 // Unpack packet: [type:4][nonce:auth_challenge_size]
963 uint32_t packet_type;
964 SAFE_MEMCPY(&packet_type, sizeof(packet_type), packet, sizeof(packet_type));
965
966 if (packet_type != CRYPTO_PACKET_AUTH_CHALLENGE) {
967 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid packet type (expected=%u, got=%u)", CRYPTO_PACKET_AUTH_CHALLENGE, packet_type);
969 }
970
971 // Store the nonce for HMAC computation (use buffer size for memcpy size, actual size from context)
972 SAFE_MEMCPY(ctx->auth_nonce, sizeof(ctx->auth_nonce), packet + sizeof(packet_type), ctx->auth_challenge_size);
973
974 log_debug("Auth challenge received and processed");
975 return CRYPTO_OK;
976}
977
979 if (!ctx || !ctx->initialized || !packet) {
980 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid context or packet (ctx=%p, initialized=%d, packet=%p)", ctx, ctx ? ctx->initialized : 0, packet);
982 }
983
984 size_t expected_size = sizeof(uint32_t) + 32; // type + hmac
985 if (packet_len != expected_size) {
986 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid packet size (expected=%zu, got=%zu)", expected_size, packet_len);
988 }
989
990 // Unpack packet: [type:4][hmac:32]
991 uint32_t packet_type;
992 SAFE_MEMCPY(&packet_type, sizeof(packet_type), packet, sizeof(packet_type));
993
994 if (packet_type != CRYPTO_PACKET_AUTH_RESPONSE) {
995 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid packet type (expected=0x%x, got=0x%x)", CRYPTO_PACKET_AUTH_RESPONSE, packet_type);
997 }
998
999 const uint8_t *received_hmac = packet + sizeof(packet_type);
1000
1001 // Verify HMAC using shared secret
1002 if (!crypto_verify_hmac(ctx->shared_key, ctx->auth_nonce, received_hmac)) {
1003 SET_ERRNO(ERROR_CRYPTO, "HMAC verification failed");
1005 }
1006
1007 ctx->handshake_complete = true;
1008 log_debug("Authentication successful - handshake complete");
1009 return CRYPTO_OK;
1010}
1011
1012// =============================================================================
1013// Shared Cryptographic Operations
1014// =============================================================================
1015
1016asciichat_error_t crypto_compute_password_hmac(crypto_context_t *ctx, const uint8_t *password_key, const uint8_t *nonce, const uint8_t *shared_secret, uint8_t *hmac_out) {
1017 if (!ctx || !password_key || !nonce || !shared_secret || !hmac_out) {
1018 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: ctx=%p, password_key=%p, nonce=%p, shared_secret=%p, hmac_out=%p", ctx, password_key, nonce, shared_secret, hmac_out);
1019 }
1020
1021 // Combine nonce and shared_secret for HMAC computation
1022 // This binds the password to the DH shared secret, preventing MITM attacks
1024 memcpy(combined_data, nonce, AUTH_CHALLENGE_SIZE);
1025 memcpy(combined_data + AUTH_CHALLENGE_SIZE, shared_secret, CRYPTO_SHARED_KEY_SIZE);
1026
1027 // Compute HMAC using the password-derived key
1028 if (crypto_compute_hmac_ex(ctx, password_key, combined_data, 64, hmac_out) != 0) {
1029 // Securely zero sensitive data containing shared secret even on error
1030 sodium_memzero(combined_data, sizeof(combined_data));
1031 return SET_ERRNO(ERROR_CRYPTO, "Failed to compute password HMAC");
1032 }
1033
1034 // Securely zero sensitive data containing shared secret
1035 sodium_memzero(combined_data, sizeof(combined_data));
1036
1037 return ASCIICHAT_OK;
1038}
1039
1040asciichat_error_t crypto_verify_peer_signature(const uint8_t *peer_public_key, const uint8_t *ephemeral_key, size_t ephemeral_key_size, const uint8_t *signature) {
1041 if (!peer_public_key || !ephemeral_key || !signature) {
1042 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: peer_public_key=%p, ephemeral_key=%p, signature=%p", peer_public_key, ephemeral_key, signature);
1043 }
1044
1045 if (ephemeral_key_size == 0) {
1046 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid ephemeral key size: %zu", ephemeral_key_size);
1047 }
1048
1049 // Verify the signature using Ed25519
1050 if (crypto_sign_verify_detached(signature, ephemeral_key, ephemeral_key_size, peer_public_key) != 0) {
1051 return SET_ERRNO(ERROR_CRYPTO, "Peer signature verification failed");
1052 }
1053
1054 return ASCIICHAT_OK;
1055}
1056
1057asciichat_error_t crypto_sign_ephemeral_key(const private_key_t *private_key, const uint8_t *ephemeral_key, size_t ephemeral_key_size, uint8_t *signature_out) {
1058 if (!private_key || !ephemeral_key || !signature_out) {
1059 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: private_key=%p, ephemeral_key=%p, signature_out=%p", private_key, ephemeral_key, signature_out);
1060 }
1061
1062 if (ephemeral_key_size == 0) {
1063 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid ephemeral key size: %zu", ephemeral_key_size);
1064 return ERROR_INVALID_PARAM;
1065 }
1066
1067 // Sign the ephemeral key with our Ed25519 private key
1068 if (private_key->type == KEY_TYPE_ED25519) {
1069 if (crypto_sign_detached(signature_out, NULL, ephemeral_key, ephemeral_key_size, private_key->key.ed25519) != 0) {
1070 return SET_ERRNO(ERROR_CRYPTO, "Failed to sign ephemeral key");
1071 }
1072 } else {
1073 return SET_ERRNO(ERROR_CRYPTO, "Unsupported private key type for signing");
1074 }
1075
1076 return ASCIICHAT_OK;
1077}
1078
1079void crypto_combine_auth_data(const uint8_t *hmac, const uint8_t *challenge_nonce, uint8_t *combined_out) {
1080 if (!hmac || !challenge_nonce || !combined_out) {
1081 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: hmac=%p, challenge_nonce=%p, combined_out=%p", hmac, challenge_nonce, combined_out);
1082 return;
1083 }
1084
1085 // Combine HMAC (32 bytes) + challenge nonce (32 bytes) = 64 bytes total
1086 memcpy(combined_out, hmac, HMAC_SHA256_SIZE);
1087 memcpy(combined_out + AUTH_HMAC_SIZE, challenge_nonce, AUTH_CHALLENGE_SIZE);
1088}
1089
1090void crypto_extract_auth_data(const uint8_t *combined_data, uint8_t *hmac_out, uint8_t *challenge_out) {
1091 if (!combined_data || !hmac_out || !challenge_out) {
1092 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: combined_data=%p, hmac_out=%p, challenge_out=%p", combined_data, hmac_out, challenge_out);
1093 return;
1094 }
1095
1096 // Extract HMAC (first 32 bytes) and challenge nonce (last 32 bytes)
1097 memcpy(hmac_out, combined_data, HMAC_SHA256_SIZE);
1098 memcpy(challenge_out, combined_data + AUTH_CHALLENGE_SIZE, AUTH_CHALLENGE_SIZE);
1099}
1100
1101// =============================================================================
1102// Session Rekeying Protocol Implementation
1103// =============================================================================
1104
1106 if (!ctx || !ctx->initialized) {
1107 return false;
1108 }
1109
1110 // Don't trigger rekey if one is already in progress
1111 if (ctx->rekey_in_progress) {
1112 return false;
1113 }
1114
1115 // Don't trigger rekey if handshake isn't complete yet
1116 if (!ctx->handshake_complete) {
1117 return false;
1118 }
1119
1120 // Check packet count threshold
1121 if (ctx->rekey_packet_count >= ctx->rekey_packet_threshold) {
1122 log_debug("Rekey triggered: packet count (%llu) >= threshold (%llu)", (unsigned long long)ctx->rekey_packet_count, (unsigned long long)ctx->rekey_packet_threshold);
1123 return true;
1124 }
1125
1126 // Check time threshold
1127 time_t now = time(NULL);
1128 time_t elapsed = now - ctx->rekey_last_time;
1129 if (elapsed >= ctx->rekey_time_threshold) {
1130 log_debug("Rekey triggered: time elapsed (%ld sec) >= threshold (%ld sec)", (long)elapsed, (long)ctx->rekey_time_threshold);
1131 return true;
1132 }
1133
1134 return false;
1135}
1136
1138 if (!ctx || !ctx->initialized) {
1139 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid context");
1141 }
1142
1143 if (ctx->rekey_in_progress) {
1144 SET_ERRNO(ERROR_CRYPTO, "Rekey already in progress");
1146 }
1147
1148 // Rate limiting: check minimum interval since last rekey
1149 time_t now = time(NULL);
1150 time_t since_last_rekey = now - ctx->rekey_last_time;
1151 time_t min_interval_seconds = (time_t)(REKEY_MIN_INTERVAL / NS_PER_SEC_INT);
1152 if (since_last_rekey < min_interval_seconds) {
1153 char elapsed_str[TIME_DURATION_BUFFER_SIZE], min_str[TIME_DURATION_BUFFER_SIZE];
1154 time_pretty((uint64_t)(since_last_rekey * 1e9), -1, elapsed_str, sizeof(elapsed_str));
1155 time_pretty((uint64_t)(min_interval_seconds * 1e9), -1, min_str, sizeof(min_str));
1156 log_warn("Rekey rate limited: %s since last rekey (minimum: %s)", elapsed_str, min_str);
1158 }
1159
1160 // Check if too many consecutive failures
1162 log_error("Too many consecutive rekey failures (%d), giving up", ctx->rekey_failure_count);
1164 }
1165
1166 // Generate new ephemeral X25519 keypair for rekeying
1167 if (crypto_box_keypair(ctx->temp_public_key, ctx->temp_private_key) != 0) {
1168 SET_ERRNO(ERROR_CRYPTO, "Failed to generate rekey ephemeral keypair");
1170 }
1171
1172 ctx->rekey_in_progress = true;
1173 ctx->has_temp_key = true;
1174
1175 log_debug("Rekey initiated (packets: %llu, time elapsed: %ld sec, attempt %d)", (unsigned long long)ctx->rekey_packet_count, (long)since_last_rekey, ctx->rekey_failure_count + 1);
1176
1177 return CRYPTO_OK;
1178}
1179
1181 if (!ctx || !ctx->initialized || !peer_new_public_key) {
1182 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters");
1184 }
1185
1186 // Generate our own new ephemeral keypair (responder side)
1187 if (crypto_box_keypair(ctx->temp_public_key, ctx->temp_private_key) != 0) {
1188 SET_ERRNO(ERROR_CRYPTO, "Failed to generate rekey ephemeral keypair");
1190 }
1191
1192 // Compute new shared secret: DH(our_new_private_key, peer_new_public_key)
1193 if (crypto_scalarmult(ctx->temp_shared_key, ctx->temp_private_key, peer_new_public_key) != 0) {
1194 SET_ERRNO(ERROR_CRYPTO, "Failed to compute rekey shared secret");
1195 secure_memzero(ctx->temp_private_key, sizeof(ctx->temp_private_key));
1196 secure_memzero(ctx->temp_public_key, sizeof(ctx->temp_public_key));
1198 }
1199
1200 ctx->rekey_in_progress = true;
1201 ctx->has_temp_key = true;
1202
1203 log_debug("Rekey request processed (responder side), new shared secret computed");
1204
1205 return CRYPTO_OK;
1206}
1207
1209 if (!ctx || !ctx->initialized || !peer_new_public_key) {
1210 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters");
1212 }
1213
1214 if (!ctx->rekey_in_progress || !ctx->has_temp_key) {
1215 SET_ERRNO(ERROR_CRYPTO, "No rekey in progress");
1217 }
1218
1219 // Compute new shared secret: DH(our_new_private_key, peer_new_public_key)
1220 // Use crypto_scalarmult to produce raw 32-byte shared secret for crypto_secretbox
1221 if (crypto_scalarmult(ctx->temp_shared_key, ctx->temp_private_key, peer_new_public_key) != 0) {
1222 SET_ERRNO(ERROR_CRYPTO, "Failed to compute rekey shared secret");
1223 crypto_rekey_abort(ctx);
1225 }
1226
1227 log_debug("Rekey response processed (initiator side), new shared secret computed");
1228
1229 return CRYPTO_OK;
1230}
1231
1233 if (!ctx || !ctx->initialized) {
1234 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid context");
1236 }
1237
1238 if (!ctx->rekey_in_progress || !ctx->has_temp_key) {
1239 SET_ERRNO(ERROR_CRYPTO, "No rekey in progress to commit");
1241 }
1242
1243 // Wipe old shared secret securely
1244 secure_memzero(ctx->shared_key, sizeof(ctx->shared_key));
1245
1246 // Switch to new shared secret
1247 SAFE_MEMCPY(ctx->shared_key, sizeof(ctx->shared_key), ctx->temp_shared_key, sizeof(ctx->temp_shared_key));
1248
1249 // Reset nonce counter to 1 (fresh start with new key)
1250 ctx->nonce_counter = 1;
1251
1252 // Generate a new random nonce prefix for this key epoch.
1253 randombytes_buf(ctx->session_id, sizeof(ctx->session_id));
1254
1255 // Reset rekey tracking
1256 ctx->rekey_packet_count = 0;
1257 ctx->rekey_last_time = time(NULL);
1258 ctx->rekey_count++;
1259
1260 // Clear rekey state
1261 secure_memzero(ctx->temp_public_key, sizeof(ctx->temp_public_key));
1262 secure_memzero(ctx->temp_private_key, sizeof(ctx->temp_private_key));
1263 secure_memzero(ctx->temp_shared_key, sizeof(ctx->temp_shared_key));
1264 ctx->has_temp_key = false;
1265 ctx->rekey_in_progress = false;
1266
1267 // Reset failure counter on successful rekey
1268 ctx->rekey_failure_count = 0;
1269
1270 log_debug("Rekey committed successfully (rekey #%llu, nonce reset to 1, new session_id generated)", (unsigned long long)ctx->rekey_count);
1271
1272 return CRYPTO_OK;
1273}
1274
1276 if (!ctx) {
1277 return;
1278 }
1279
1280 log_warn("Aborting rekey (attempt %d failed), keeping old encryption key", ctx->rekey_failure_count + 1);
1281
1282 // Wipe temporary keys securely
1283 secure_memzero(ctx->temp_public_key, sizeof(ctx->temp_public_key));
1284 secure_memzero(ctx->temp_private_key, sizeof(ctx->temp_private_key));
1285 secure_memzero(ctx->temp_shared_key, sizeof(ctx->temp_shared_key));
1286
1287 // Reset rekey state
1288 ctx->has_temp_key = false;
1289 ctx->rekey_in_progress = false;
1290
1291 // Increment failure counter for exponential backoff
1292 ctx->rekey_failure_count++;
1293
1294 // Continue using old key - no disruption to connection
1295}
1296
1297void crypto_get_rekey_status(const crypto_context_t *ctx, char *status_buffer, size_t buffer_size) {
1298 if (!ctx || !status_buffer || buffer_size == 0) {
1299 return;
1300 }
1301
1302 time_t now = time(NULL);
1303 time_t elapsed = now - ctx->rekey_last_time;
1304 time_t remaining_time = (ctx->rekey_time_threshold > elapsed) ? (ctx->rekey_time_threshold - elapsed) : 0;
1305 uint64_t remaining_packets = (ctx->rekey_packet_threshold > ctx->rekey_packet_count) ? (ctx->rekey_packet_threshold - ctx->rekey_packet_count) : 0;
1306
1307 safe_snprintf(status_buffer, buffer_size,
1308 "Rekey status: %s | "
1309 "Packets: %llu/%llu (%llu remaining) | "
1310 "Time: %ld/%ld sec (%ld sec remaining) | "
1311 "Rekeys: %llu | Failures: %d",
1312 ctx->rekey_in_progress ? "IN_PROGRESS" : "IDLE", (unsigned long long)ctx->rekey_packet_count, (unsigned long long)ctx->rekey_packet_threshold, (unsigned long long)remaining_packets,
1313 (long)elapsed, (long)ctx->rekey_time_threshold, (long)remaining_time, (unsigned long long)ctx->rekey_count, ctx->rekey_failure_count);
1314}
Synchronized per-thread pending error stacks and value snapshots. SET_ERRNO pushes,...
#define SET_ERRNO(code,...)
Platform initialization and static synchronization helpers.
🔄 Network byte order conversion helpers
#define HOST_TO_NET_U64(val)
Definition endian.h:217
int buffer_size
Size of circular buffer.
Definition grep.c:68
unsigned int uint32_t
#define SAFE_SNPRINTF(buffer, buffer_size,...)
unsigned long long uint64_t
unsigned char uint8_t
#define SAFE_MEMCPY(dest, dest_size, src, count)
crypto_result_t crypto_rekey_commit(crypto_context_t *ctx)
Commit to new keys after successful REKEY_COMPLETE.
crypto_result_t crypto_create_auth_challenge(const crypto_context_t *ctx, uint8_t *packet_out, size_t packet_size, size_t *packet_len_out)
Create authentication challenge packet.
crypto_result_t crypto_process_public_key_packet(crypto_context_t *ctx, const uint8_t *packet, size_t packet_len)
Process received public key packet from peer.
#define REKEY_MIN_INTERVAL
Minimum time interval between rekey requests (3 seconds in nanoseconds for testing,...
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).
crypto_result_t crypto_encrypt(crypto_context_t *ctx, const uint8_t *plaintext, size_t plaintext_len, uint8_t *ciphertext_out, size_t ciphertext_out_size, size_t *ciphertext_len_out)
Encrypt data using XSalsa20-Poly1305.
crypto_result_t crypto_init(crypto_context_t *ctx)
Initialize libsodium and crypto context.
asciichat_error_t crypto_compute_password_hmac(crypto_context_t *ctx, const uint8_t *password_key, const uint8_t *nonce, const uint8_t *shared_secret, uint8_t *hmac_out)
Compute password-based HMAC for authentication.
const char * crypto_result_to_string(crypto_result_t result)
Convert crypto result to human-readable string.
crypto_result_t
Cryptographic operation result codes.
#define REKEY_DEFAULT_TIME_THRESHOLD
Default rekey time threshold (1 hour in nanoseconds).
#define REKEY_MAX_FAILURE_COUNT
Maximum consecutive rekey failures before giving up.
asciichat_error_t crypto_verify_peer_signature(const uint8_t *peer_public_key, const uint8_t *ephemeral_key, size_t ephemeral_key_size, const uint8_t *signature)
Verify peer's signature on ephemeral key.
bool crypto_verify_password(const crypto_context_t *ctx, const char *password)
Verify password matches stored salt/key.
crypto_result_t crypto_get_public_key(const crypto_context_t *ctx, uint8_t *public_key_out)
Get public key for sending to peer (step 1 of handshake).
crypto_result_t crypto_create_encrypted_packet(crypto_context_t *ctx, const uint8_t *data, size_t data_len, uint8_t *packet_out, size_t packet_size, size_t *packet_len_out)
Create encrypted data packet for network transmission.
void crypto_get_rekey_status(const crypto_context_t *ctx, char *status_buffer, size_t buffer_size)
Get the current rekeying state for debugging/logging.
bool crypto_should_rekey(const crypto_context_t *ctx)
Check if rekeying should be triggered based on time or packet count thresholds.
crypto_result_t crypto_process_auth_response(crypto_context_t *ctx, const uint8_t *packet, size_t packet_len)
Process authentication response packet.
crypto_result_t crypto_generate_keypair(crypto_context_t *ctx)
Generate new X25519 key pair for key exchange.
void crypto_combine_auth_data(const uint8_t *hmac, const uint8_t *challenge_nonce, uint8_t *combined_out)
Combine HMAC and challenge nonce for transmission.
crypto_result_t crypto_process_auth_challenge(crypto_context_t *ctx, const uint8_t *packet, size_t packet_len)
Process authentication challenge packet.
void crypto_extract_auth_data(const uint8_t *combined_data, uint8_t *hmac_out, uint8_t *challenge_out)
Extract HMAC and challenge nonce from combined data.
void crypto_get_status(const crypto_context_t *ctx, char *status_buffer, size_t buffer_size)
Get crypto context status information for debugging.
void crypto_rekey_abort(crypto_context_t *ctx)
Abort rekeying and fallback to old keys.
bool crypto_is_ready(const crypto_context_t *ctx)
Check if key exchange is complete and ready for encryption.
crypto_result_t crypto_validate_password(const char *password)
Validate password length requirements.
crypto_result_t crypto_rekey_process_request(crypto_context_t *ctx, const uint8_t *peer_new_public_key)
Process REKEY_REQUEST from peer (responder side).
asciichat_error_t crypto_sign_ephemeral_key(const private_key_t *private_key, const uint8_t *ephemeral_key, size_t ephemeral_key_size, uint8_t *signature_out)
Sign ephemeral key with private key.
bool crypto_secure_compare(const uint8_t *lhs, const uint8_t *rhs, size_t len)
Secure constant-time comparison of byte arrays.
#define REKEY_TEST_PACKET_THRESHOLD
Test mode rekey packet threshold (1000 packets).
crypto_result_t crypto_derive_password_key(crypto_context_t *ctx, const char *password)
Derive key from password using Argon2id.
#define REKEY_TEST_TIME_THRESHOLD
Test mode rekey time threshold (30 seconds in nanoseconds).
crypto_result_t crypto_decrypt(crypto_context_t *ctx, const uint8_t *ciphertext, size_t ciphertext_len, uint8_t *plaintext_out, size_t plaintext_out_size, size_t *plaintext_len_out)
Decrypt data using XSalsa20-Poly1305.
crypto_result_t crypto_init_with_password(crypto_context_t *ctx, const char *password)
Initialize with password-based encryption.
crypto_result_t crypto_create_public_key_packet(const crypto_context_t *ctx, uint8_t *packet_out, size_t packet_size, size_t *packet_len_out)
Create public key packet for network transmission.
void crypto_destroy(crypto_context_t *ctx)
Cleanup crypto context with secure memory wiping.
#define REKEY_DEFAULT_PACKET_THRESHOLD
Default rekey packet threshold (1 million packets).
crypto_result_t crypto_rekey_init(crypto_context_t *ctx)
Initiate rekeying by generating new ephemeral keys.
crypto_result_t crypto_random_bytes(uint8_t *buffer, size_t len)
Generate cryptographically secure random bytes.
crypto_result_t crypto_process_encrypted_packet(crypto_context_t *ctx, const uint8_t *packet, size_t packet_len, uint8_t *data_out, size_t data_size, size_t *data_len_out)
Process received encrypted packet from peer.
crypto_result_t crypto_rekey_process_response(crypto_context_t *ctx, const uint8_t *peer_new_public_key)
Process REKEY_RESPONSE from peer (initiator side).
#define CRYPTO_MAX_PLAINTEXT_SIZE
Maximum plaintext size (1MB).
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_CRYPTO
Definition error_codes.h:97
@ ERROR_INVALID_PARAM
@ ERROR_BUFFER
uint8_t ed25519[ED25519_PRIVATE_KEY_SIZE]
Definition key_types.h:104
key_type_t type
Definition key_types.h:102
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_error(...)
Log an ERROR message.
Definition log/log.h:628
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:589
#define NS_PER_SEC_INT
Definition time.h:173
int time_pretty(uint64_t nanoseconds, int decimals, char *buffer, size_t buffer_size)
Format nanoseconds as a compact duration with configurable sub-minute precision.
Definition time.c:368
#define TIME_DURATION_BUFFER_SIZE
Definition time.h:40
#define US_PER_SEC_INT
Definition time.h:177
void format_bytes_pretty(size_t bytes, char *out, size_t out_capacity)
Format byte count into human-readable string.
Definition util/format.c:11
⚙️ Common definitions, error codes, macros, and types shared throughout the application
crypto_result_t crypto_compute_hmac(crypto_context_t *ctx, const uint8_t key[HMAC_SHA256_KEY_SIZE], const uint8_t data[AUTH_CHALLENGE_SIZE], uint8_t hmac[HMAC_SHA256_SIZE])
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])
#define CRYPTO_ENCRYPTED_BUFFER_SIZE
crypto_result_t crypto_generate_nonce(uint8_t nonce[AUTH_CHALLENGE_SIZE])
bool crypto_verify_hmac(const uint8_t key[HMAC_SHA256_KEY_SIZE], const uint8_t data[AUTH_CHALLENGE_SIZE], const uint8_t expected_hmac[HMAC_SHA256_SIZE])
crypto_result_t crypto_derive_password_encryption_key(const char *password, uint8_t encryption_key[SECRETBOX_KEY_SIZE])
#define CRYPTO_DECRYPTED_BUFFER_SIZE
crypto_result_t crypto_compute_hmac_ex(const crypto_context_t *ctx, const uint8_t key[HMAC_SHA256_KEY_SIZE], const uint8_t *data, size_t data_len, uint8_t hmac[HMAC_SHA256_SIZE])
bool crypto_verify_hmac_ex(const uint8_t key[HMAC_SHA256_KEY_SIZE], const uint8_t *data, size_t data_len, const uint8_t expected_hmac[HMAC_SHA256_SIZE])
#define CRYPTO_RESULT_STRING_COUNT
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_session_create(crypto_context_t *crypto)
void crypto_session_destroy(crypto_context_t *crypto)
#define log_debug_every(interval_us, fmt,...)
Rate-limited DEBUG logging.
Definition log/log.h:743
#define log_error_every(interval_us, fmt,...)
Rate-limited ERROR logging.
Definition log/log.h:752
void ascii_otel_metric(ascii_otel_metric_t metric, double value)
Definition otel.c:159
#define ASCII_OTEL_SCOPE(id)
Definition otel.h:77
#define ASCII_OTEL_ATTR_INT(key, value)
Definition otel.h:72
#define ASCII_OTEL_ATTR_STRING(key, value)
Definition otel.h:71
#define HMAC_SHA256_KEY_SIZE
Definition sizes.h:49
#define AUTH_CHALLENGE_SIZE
Challenge nonce size (32 bytes).
Definition sizes.h:103
#define HMAC_SHA256_SIZE
HMAC-SHA256 output size in bytes.
Definition sizes.h:47
#define SECRETBOX_KEY_SIZE
Secretbox key size in bytes.
Definition sizes.h:53
#define CRYPTO_SHARED_KEY_SIZE
Shared key size (X25519).
Definition sizes.h:75
#define MIN_PASSWORD_LENGTH
Minimum password length (8 characters).
Definition sizes.h:23
#define X25519_KEY_SIZE
X25519 key size in bytes.
Definition sizes.h:35
#define MAX_PASSWORD_LENGTH
Maximum password length (256 characters).
Definition sizes.h:25
#define XSALSA20_NONCE_SIZE
XSalsa20 nonce size in bytes.
Definition sizes.h:43
#define ARGON2ID_SALT_SIZE
Argon2id salt size in bytes.
Definition sizes.h:51
#define AUTH_HMAC_SIZE
HMAC size in authentication packets (32 bytes).
Definition sizes.h:101
#define POLY1305_MAC_SIZE
Poly1305 MAC size in bytes.
Definition sizes.h:45
🔤 String Manipulation and Shell Escaping Utilities
Endpoint cryptographic state for handshake, packet protection, authentication, and rekeying.
Private identity-key material used for server authentication and signing.
Definition key_types.h:101
Test environment detection utilities.
⏱️ High-precision timing utilities using sokol_time.h and uthash
📊 String Formatting Utilities