ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
crypto.c File Reference

🔐 Core cryptography: encryption/decryption, key exchange, authentication, and session rekeying with BearSSL More...

Go to the source code of this file.

Macros

#define CRYPTO_ENCRYPTED_BUFFER_SIZE   32
#define CRYPTO_DECRYPTED_BUFFER_SIZE   32
#define CRYPTO_RESULT_STRING_COUNT   (sizeof(g_crypto_result_strings) / sizeof(g_crypto_result_strings[0]))

Functions

crypto_result_t crypto_init (crypto_context_t *ctx)
 Initialize libsodium and crypto context.
crypto_result_t crypto_init_with_password (crypto_context_t *ctx, const char *password)
 Initialize with password-based encryption.
void crypto_destroy (crypto_context_t *ctx)
 Cleanup crypto context with secure memory wiping.
crypto_result_t crypto_generate_keypair (crypto_context_t *ctx)
 Generate new X25519 key pair for key exchange.
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_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).
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_derive_password_key (crypto_context_t *ctx, const char *password)
 Derive key from password using Argon2id.
bool crypto_verify_password (const crypto_context_t *ctx, const char *password)
 Verify password matches stored salt/key.
crypto_result_t crypto_derive_password_encryption_key (const char *password, uint8_t encryption_key[SECRETBOX_KEY_SIZE])
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_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.
const char * crypto_result_to_string (crypto_result_t result)
 Convert crypto result to human-readable string.
void crypto_get_status (const crypto_context_t *ctx, char *status_buffer, size_t buffer_size)
 Get crypto context status information for debugging.
bool crypto_secure_compare (const uint8_t *lhs, const uint8_t *rhs, size_t len)
 Secure constant-time comparison of byte arrays.
crypto_result_t crypto_random_bytes (uint8_t *buffer, size_t len)
 Generate cryptographically secure random bytes.
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.
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.
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.
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_generate_nonce (uint8_t nonce[AUTH_CHALLENGE_SIZE])
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])
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 (const uint8_t key[HMAC_SHA256_KEY_SIZE], const uint8_t data[AUTH_CHALLENGE_SIZE], const uint8_t expected_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])
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])
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_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_auth_challenge (crypto_context_t *ctx, const uint8_t *packet, size_t packet_len)
 Process authentication challenge packet.
crypto_result_t crypto_process_auth_response (crypto_context_t *ctx, const uint8_t *packet, size_t packet_len)
 Process authentication response packet.
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.
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.
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.
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.
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.
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_rekey_init (crypto_context_t *ctx)
 Initiate rekeying by generating new ephemeral keys.
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).
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).
crypto_result_t crypto_rekey_commit (crypto_context_t *ctx)
 Commit to new keys after successful REKEY_COMPLETE.
void crypto_rekey_abort (crypto_context_t *ctx)
 Abort rekeying and fallback to old keys.
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.

Detailed Description

🔐 Core cryptography: encryption/decryption, key exchange, authentication, and session rekeying with BearSSL

Definition in file lib/crypto/crypto.c.

Macro Definition Documentation

◆ CRYPTO_DECRYPTED_BUFFER_SIZE

#define CRYPTO_DECRYPTED_BUFFER_SIZE   32

Definition at line 9 of file lib/crypto/crypto.c.

Referenced by crypto_destroy().

◆ CRYPTO_ENCRYPTED_BUFFER_SIZE

#define CRYPTO_ENCRYPTED_BUFFER_SIZE   32

Definition at line 8 of file lib/crypto/crypto.c.

Referenced by crypto_destroy().

◆ CRYPTO_RESULT_STRING_COUNT

#define CRYPTO_RESULT_STRING_COUNT   (sizeof(g_crypto_result_strings) / sizeof(g_crypto_result_strings[0]))

Definition at line 586 of file lib/crypto/crypto.c.

Referenced by crypto_result_to_string().

Function Documentation

◆ crypto_compute_auth_response()

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] )

Definition at line 861 of file lib/crypto/crypto.c.

861 {
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}
#define SET_ERRNO(code,...)
unsigned char uint8_t
crypto_result_t
Cryptographic operation result codes.
@ ERROR_CRYPTO
Definition error_codes.h:97
@ ERROR_INVALID_PARAM
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])
#define AUTH_CHALLENGE_SIZE
Challenge nonce size (32 bytes).
Definition sizes.h:103
#define CRYPTO_SHARED_KEY_SIZE
Shared key size (X25519).
Definition sizes.h:75

References AUTH_CHALLENGE_SIZE, crypto_compute_hmac_ex(), CRYPTO_ERROR_INVALID_PARAMS, CRYPTO_SHARED_KEY_SIZE, ERROR_CRYPTO, ERROR_INVALID_PARAM, crypto_context_t::has_password, HMAC_SHA256_SIZE, crypto_context_t::key_exchange_complete, crypto_context_t::password_key, SET_ERRNO, and crypto_context_t::shared_key.

Referenced by crypto_handshake_server_complete().

◆ crypto_compute_hmac()

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] )

Definition at line 801 of file lib/crypto/crypto.c.

801 {
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}

References AUTH_CHALLENGE_SIZE, CRYPTO_OK, ERROR_INVALID_PARAM, HMAC_SHA256_KEY_SIZE, HMAC_SHA256_SIZE, and SET_ERRNO.

◆ crypto_compute_hmac_ex()

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] )

Definition at line 815 of file lib/crypto/crypto.c.

815 {
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}

References CRYPTO_OK, ERROR_INVALID_PARAM, HMAC_SHA256_KEY_SIZE, HMAC_SHA256_SIZE, and SET_ERRNO.

Referenced by crypto_compute_auth_response(), and crypto_compute_password_hmac().

◆ crypto_derive_password_encryption_key()

crypto_result_t crypto_derive_password_encryption_key ( const char * password,
uint8_t encryption_key[SECRETBOX_KEY_SIZE] )

Definition at line 379 of file lib/crypto/crypto.c.

379 {
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}
crypto_result_t crypto_validate_password(const char *password)
Validate password length requirements.
#define log_dev(...)
Log a DEV message (most verbose, development only).
Definition log/log.h:575
#define SECRETBOX_KEY_SIZE
Secretbox key size in bytes.
Definition sizes.h:53
#define ARGON2ID_SALT_SIZE
Argon2id salt size in bytes.
Definition sizes.h:51

References ARGON2ID_SALT_SIZE, CRYPTO_ERROR_INVALID_PARAMS, CRYPTO_ERROR_PASSWORD_DERIVATION, CRYPTO_OK, crypto_validate_password(), ERROR_CRYPTO, ERROR_INVALID_PARAM, log_dev, SECRETBOX_KEY_SIZE, and SET_ERRNO.

◆ crypto_generate_nonce()

crypto_result_t crypto_generate_nonce ( uint8_t nonce[AUTH_CHALLENGE_SIZE])

Definition at line 786 of file lib/crypto/crypto.c.

786 {
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}

References AUTH_CHALLENGE_SIZE, CRYPTO_ERROR_INVALID_PARAMS, CRYPTO_OK, ERROR_INVALID_PARAM, and SET_ERRNO.

Referenced by crypto_create_auth_challenge(), and crypto_handshake_server_auth_challenge().

◆ crypto_verify_auth_response()

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] )

Definition at line 891 of file lib/crypto/crypto.c.

891 {
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}
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:589
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])

References AUTH_CHALLENGE_SIZE, CRYPTO_SHARED_KEY_SIZE, crypto_verify_hmac_ex(), ERROR_CRYPTO, ERROR_INVALID_PARAM, crypto_context_t::has_password, HMAC_SHA256_SIZE, crypto_context_t::key_exchange_complete, log_debug, crypto_context_t::password_key, SET_ERRNO, and crypto_context_t::shared_key.

Referenced by crypto_handshake_client_complete(), and crypto_handshake_server_complete().

◆ crypto_verify_hmac()

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] )

Definition at line 829 of file lib/crypto/crypto.c.

829 {
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}
#define HMAC_SHA256_SIZE
HMAC-SHA256 output size in bytes.
Definition sizes.h:47

References AUTH_CHALLENGE_SIZE, ERROR_INVALID_PARAM, HMAC_SHA256_KEY_SIZE, HMAC_SHA256_SIZE, and SET_ERRNO.

Referenced by crypto_process_auth_response().

◆ crypto_verify_hmac_ex()

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] )

Definition at line 843 of file lib/crypto/crypto.c.

843 {
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}

References ERROR_INVALID_PARAM, HMAC_SHA256_KEY_SIZE, HMAC_SHA256_SIZE, and SET_ERRNO.

Referenced by crypto_verify_auth_response().