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/handshake/common.c
Go to the documentation of this file.
1
2/* Existing buffer budgets in bytes, including NUL for text storage. */
3#define HANDSHAKE_ERROR_PLAINTEXT_CAPACITY 256
4
5#include <ascii-chat/otel.h>
11
12#include <ascii-chat/common.h>
14#include <ascii-chat/buffer.h>
21#include <stdio.h>
22#include <string.h>
23
24// Initialize named crypto handshake context
26 if (!name) {
27 return SET_ERRNO(ERROR_INVALID_PARAM, "Crypto context name is required");
28 }
29
30 if (!ctx) {
31 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: ctx=%p", ctx);
32 }
33
34 // Register crypto context with debug naming system
35 NAMED_REGISTER_CRYPTO_CONTEXT(ctx, name, NULL);
36
37 // Zero out the context
38 memset(ctx, 0, sizeof(crypto_handshake_context_t));
39
40 // Initialize core crypto context
42 if (result != CRYPTO_OK) {
43 return SET_ERRNO(ERROR_CRYPTO, "Failed to initialize crypto context: %s", crypto_result_to_string(result));
44 }
45
47 ctx->is_server = is_server;
48 ctx->crypto_ctx.server_role = is_server;
49 ctx->crypto_ctx.server_role_known = true;
50 ctx->verify_server_key = false;
51 ctx->require_client_auth = false;
52 ctx->server_uses_client_auth = false; // Set to true only if authenticated packet received
53
54 // Load server keys if this is a server
55 if (is_server) {
56 log_dev("Server crypto handshake initialized (ephemeral keys)");
57 } else {
58 log_dev("Client crypto handshake initialized");
59 }
60
61 return ASCIICHAT_OK;
62}
63
64// Set crypto parameters from crypto_parameters_packet_t
66 if (!ctx || !params) {
67 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: ctx=%p, params=%p", ctx, params);
68 }
69
71
72 // Client receives network byte order and must convert
73 // Server uses host byte order and must NOT convert
74 if (ctx->is_server) {
75 // Server: values are already in host byte order
76 // Update crypto context with negotiated parameters directly
81 } else {
82 ctx->require_client_auth = params->verification_enabled != 0;
83 // Client: convert from network byte order
84 // Update crypto context with negotiated parameters directly
89 }
90 // Update crypto context with negotiated parameters directly
91 ctx->crypto_ctx.nonce_size = params->nonce_size;
92 ctx->crypto_ctx.mac_size = params->mac_size;
93 ctx->crypto_ctx.hmac_size = params->hmac_size;
94 ctx->crypto_ctx.auth_challenge_size = AUTH_CHALLENGE_SIZE; // Auth challenge size is fixed for now, could be negotiated later
95 ctx->crypto_ctx.encryption_key_size = (uint8_t)ctx->crypto_ctx.shared_key_size; // Use shared key size as encryption key size
96 ctx->crypto_ctx.private_key_size = ctx->crypto_ctx.public_key_size; // Same as public key for X25519
97 ctx->crypto_ctx.salt_size = ARGON2ID_SALT_SIZE; // Salt size doesn't change
98
99 log_debug("Crypto parameters set: kex_key=%u, auth_key=%u, sig=%u, "
100 "secret=%u, nonce=%u, mac=%u, hmac=%u",
103
104 return ASCIICHAT_OK;
105}
106
107// Validate crypto packet size based on session parameters
109 if (!ctx) {
110 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: ctx=%p", ctx);
111 }
112
113 switch (packet_type) {
115 if (packet_size != sizeof(crypto_capabilities_packet_t)) {
116 // Don't return an error code, just set the errno and return the error code
117 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Invalid crypto capabilities packet size: %zu (expected %zu)", packet_size, sizeof(crypto_capabilities_packet_t));
118 }
119 break;
120
122 if (packet_size != sizeof(crypto_parameters_packet_t)) {
123 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Invalid crypto parameters packet size: %zu (expected %zu)", packet_size, sizeof(crypto_parameters_packet_t));
124 }
125 break;
126
128 // Server can send either:
129 // 1. Simple format: kex_public_key_size (when server has no identity key)
130 // 2. Authenticated format: kex_public_key_size + auth_public_key_size + signature_size
131 {
132 size_t simple_size = ctx->crypto_ctx.public_key_size;
133 size_t authenticated_size = ctx->crypto_ctx.public_key_size + ctx->crypto_ctx.auth_public_key_size + ctx->crypto_ctx.signature_size;
134
135 if (packet_size != simple_size && packet_size != authenticated_size) {
137 "Invalid KEY_EXCHANGE_INIT size: %zu (expected %zu for simple or %zu for authenticated: "
138 "kex=%u + auth=%u + sig=%u)",
139 packet_size, simple_size, authenticated_size, ctx->crypto_ctx.public_key_size, ctx->crypto_ctx.auth_public_key_size, ctx->crypto_ctx.signature_size);
140 }
141 }
142 break;
143
145 // Client can send either:
146 // 1. Simple format: kex_public_key_size (when server has no identity key)
147 // 2. Authenticated format: kex_public_key_size + client_auth_key_size + client_sig_size + [gpg_key_id_len:1] +
148 // [gpg_key_id:0-16]
149 {
150 size_t simple_size = ctx->crypto_ctx.public_key_size;
151 // For authenticated format, use Ed25519 sizes since client has Ed25519 key
152 size_t ed25519_auth_size = ED25519_PUBLIC_KEY_SIZE; // Ed25519 public key is always 32 bytes
153 size_t ed25519_sig_size = ED25519_SIGNATURE_SIZE; // Ed25519 signature is always 64 bytes
154 size_t authenticated_min_size = ctx->crypto_ctx.public_key_size + ed25519_auth_size + ed25519_sig_size;
155 size_t authenticated_max_size = authenticated_min_size + 1 + 40; // +1 for length, +40 for max GPG key ID
156
157 if (packet_size != simple_size && (packet_size < authenticated_min_size || packet_size > authenticated_max_size)) {
159 "Invalid KEY_EXCHANGE_RESP size: %zu (expected %zu for simple or %zu-%zu for authenticated: "
160 "kex=%u + auth=%u + sig=%u + optional GPG key ID)",
161 packet_size, simple_size, authenticated_min_size, authenticated_max_size, ctx->crypto_ctx.public_key_size, ed25519_auth_size, ed25519_sig_size);
162 }
163 }
164 break;
165
167 // Server sends: 1 byte auth_flags + auth_challenge_size byte nonce
168 {
169 size_t expected_size = AUTH_CHALLENGE_FLAGS_SIZE + ctx->crypto_ctx.auth_challenge_size;
170 if (packet_size != expected_size) {
171 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Invalid AUTH_CHALLENGE size: %zu (expected %zu: flags=%d + nonce=%u)", packet_size, expected_size, AUTH_CHALLENGE_FLAGS_SIZE,
173 }
174 }
175 break;
176
178 // Client sends: hmac_size + auth_challenge_size bytes client_nonce + [gpg_key_id_len:1] + [gpg_key_id:0-40]
179 {
180 size_t min_size = ctx->crypto_ctx.hmac_size + ctx->crypto_ctx.auth_challenge_size;
181 size_t max_size = min_size + 1 + 40; // +1 for length, +40 for max GPG key ID
182 if (packet_size < min_size || packet_size > max_size) {
184 "Invalid AUTH_RESPONSE size: %zu (expected %zu-%zu: hmac=%u + "
185 "nonce=%u + optional GPG key ID)",
186 packet_size, min_size, max_size, ctx->crypto_ctx.hmac_size, ctx->crypto_ctx.auth_challenge_size);
187 }
188 }
189 break;
190
192 // Variable size - just check reasonable limits
193 if (packet_size > MAX_AUTH_FAILED_PACKET_SIZE) {
194 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Invalid AUTH_FAILED size: %zu (max %d)", packet_size, MAX_AUTH_FAILED_PACKET_SIZE);
195 }
196 break;
197
199 // Server sends: hmac_size bytes
200 if (packet_size != ctx->crypto_ctx.hmac_size) {
201 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Invalid SERVER_AUTH_RESP size: %zu (expected %u)", packet_size, ctx->crypto_ctx.hmac_size);
202 }
203 break;
204
206 // Empty packet
207 if (packet_size != 0) {
208 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Invalid HANDSHAKE_COMPLETE size: %zu (expected 0)", packet_size);
209 }
210 break;
211
213 // Empty packet
214 if (packet_size != 0) {
215 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Invalid NO_ENCRYPTION size: %zu (expected 0)", packet_size);
216 }
217 break;
218
220 // Variable size - check reasonable limits
221 if (packet_size > MAX_ENCRYPTED_PACKET_SIZE) { // 64KB max for encrypted packets
222 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Invalid ENCRYPTED size: %zu (max %d)", packet_size, MAX_ENCRYPTED_PACKET_SIZE);
223 }
224 break;
225
226 default:
227 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Unknown crypto packet type: %u", packet_type);
228 }
229
230 return ASCIICHAT_OK;
231}
232
233// Initialize named crypto handshake context with password authentication
234asciichat_error_t crypto_handshake_init_with_password(const char *name, crypto_handshake_context_t *ctx, bool is_server, const char *password) {
235 if (!name) {
236 return SET_ERRNO(ERROR_INVALID_PARAM, "Crypto context name is required");
237 }
238
239 if (!ctx || !password) {
240 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: ctx=%p, password=%p", ctx, password);
241 }
242
243 // Register crypto context with debug naming system
244 NAMED_REGISTER_CRYPTO_CONTEXT(ctx, name, NULL);
245
246 // Zero out the context
247 memset(ctx, 0, sizeof(crypto_handshake_context_t));
248
249 // Initialize core crypto context with password
250 crypto_result_t result = crypto_init_with_password(&ctx->crypto_ctx, password);
251 if (result != CRYPTO_OK) {
252 return SET_ERRNO(ERROR_CRYPTO, "Failed to initialize crypto context with password: %s", crypto_result_to_string(result));
253 }
254
256 ctx->is_server = is_server;
257 ctx->crypto_ctx.server_role = is_server;
258 ctx->crypto_ctx.server_role_known = true;
259 ctx->verify_server_key = false;
260 ctx->require_client_auth = false;
261 ctx->server_uses_client_auth = false; // Set to true only if authenticated packet received
262 ctx->has_password = true;
263
264 // Store password temporarily (will be cleared after key derivation)
265 SAFE_STRNCPY(ctx->password, password, sizeof(ctx->password) - 1);
266
267 return ASCIICHAT_OK;
268}
269
270// Cleanup crypto handshake context
272 if (!ctx)
273 return;
274
275 // Cleanup core crypto context
277
278 // Zero out sensitive data
279 sodium_memzero(ctx, sizeof(crypto_handshake_context_t));
280}
281
282// Check if handshake is complete and encryption is ready
284 if (!ctx)
285 return false;
287}
288
289// Get the crypto context for encryption/decryption
291 if (!ctx || !crypto_handshake_is_ready(ctx))
292 return NULL;
293 return &ctx->crypto_ctx;
294}
Synchronized per-thread pending error stacks and value snapshots. SET_ERRNO pushes,...
#define SET_ERRNO(code,...)
asciichat_error_t crypto_handshake_init(const char *name, crypto_handshake_context_t *ctx, bool is_server)
Initialize named crypto handshake context.
const crypto_context_t * crypto_handshake_get_context(const crypto_handshake_context_t *ctx)
Get the crypto context for encryption/decryption.
asciichat_error_t crypto_handshake_init_with_password(const char *name, crypto_handshake_context_t *ctx, bool is_server, const char *password)
Initialize named crypto handshake context with password authentication.
void crypto_handshake_destroy(crypto_handshake_context_t *ctx)
Cleanup crypto handshake context with secure memory wiping.
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.
bool crypto_handshake_is_ready(const crypto_handshake_context_t *ctx)
Check if handshake is complete and encryption is ready.
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.
Named object registry for debugging — log identifiable resource names.
🔄 Network byte order conversion helpers
#define NET_TO_HOST_U16(val)
Definition endian.h:115
unsigned short uint16_t
#define SAFE_STRNCPY(dst, src, size)
unsigned char uint8_t
crypto_result_t crypto_init(crypto_context_t *ctx)
Initialize libsodium and crypto context.
const char * crypto_result_to_string(crypto_result_t result)
Convert crypto result to human-readable string.
crypto_result_t
Cryptographic operation result codes.
bool crypto_is_ready(const crypto_context_t *ctx)
Check if key exchange is complete and ready for encryption.
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.
#define NAMED_REGISTER_CRYPTO_CONTEXT(ctx, name, parent_ptr)
Register a crypto context with automatic format specifier.
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_NETWORK_PROTOCOL
Definition error_codes.h:80
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_CRYPTO
Definition error_codes.h:97
@ ERROR_INVALID_PARAM
#define log_dev(...)
Log a DEV message (most verbose, development only).
Definition log/log.h:575
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:589
#define CIPHER_ALGO_NONE
No encryption (plaintext mode).
Definition packet.h:1143
@ 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_ENCRYPTED
Encrypted packet (after handshake completion).
Definition packet.h:369
@ 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
@ PACKET_TYPE_CRYPTO_CAPABILITIES
Client -> Server: Supported crypto algorithms (UNENCRYPTED).
Definition packet.h:336
⚙️ Common definitions, error codes, macros, and types shared throughout the application
Common declarations and data structures for cryptographic handshake.
Transport abstraction layer for ACIP protocol.
ACIP shared/bidirectional packet sending functions.
#define ED25519_SIGNATURE_SIZE
Ed25519 signature size in bytes.
Definition sizes.h:41
#define AUTH_CHALLENGE_SIZE
Challenge nonce size (32 bytes).
Definition sizes.h:103
#define MAX_AUTH_FAILED_PACKET_SIZE
Maximum AUTH_FAILED packet size (256 bytes).
Definition sizes.h:146
#define MAX_ENCRYPTED_PACKET_SIZE
Maximum encrypted packet size (64KB).
Definition sizes.h:148
#define ED25519_PUBLIC_KEY_SIZE
Ed25519 public key size in bytes.
Definition sizes.h:37
#define ARGON2ID_SALT_SIZE
Argon2id salt size in bytes.
Definition sizes.h:51
#define AUTH_CHALLENGE_FLAGS_SIZE
Authentication flags size (1 byte).
Definition sizes.h:119
🔤 String Manipulation and Shell Escaping Utilities
Crypto capabilities packet structure (Packet Type 14).
Definition packet.h:1027
Endpoint cryptographic state for handshake, packet protection, authentication, and rekeying.
Cryptographic handshake context structure.
Crypto parameters packet structure (Packet Type 15).
Definition packet.h:1056
uint8_t hmac_size
HMAC size in bytes (e.g., 32 for HMAC-SHA256).
Definition packet.h:1078
uint8_t selected_cipher
Selected cipher algorithm (CIPHER_ALGO_*).
Definition packet.h:1062
uint16_t auth_public_key_size
Authentication public key size in bytes (e.g., 32 for Ed25519, 1952 for Dilithium3).
Definition packet.h:1068
uint8_t verification_enabled
Server verification enabled flag (1=enabled, 0=disabled).
Definition packet.h:1064
uint16_t signature_size
Signature size in bytes (e.g., 64 for Ed25519, 3309 for Dilithium3).
Definition packet.h:1070
uint8_t nonce_size
Nonce size in bytes (e.g., 24 for XSalsa20).
Definition packet.h:1074
uint8_t mac_size
MAC size in bytes (e.g., 16 for Poly1305).
Definition packet.h:1076
uint16_t shared_secret_size
Shared secret size in bytes (e.g., 32 for X25519).
Definition packet.h:1072
uint16_t kex_public_key_size
Key exchange public key size in bytes (e.g., 32 for X25519, 1568 for Kyber1024).
Definition packet.h:1066