ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
keys_validation.c
Go to the documentation of this file.
1
6
9#include <ascii-chat/common.h>
12#include <ascii-chat/crypto/crypto.h> // Includes <sodium.h>
13#include <libplatform/filesystem.h>
14#include <string.h>
15#include <stdlib.h>
16#include <stdio.h>
17#include <ctype.h>
18#include <sys/stat.h>
19
20// =============================================================================
21// Key Validation Implementation
22// =============================================================================
23
25 if (!key) {
26 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: key=%p", key);
28 }
29
30 // Check key type
31 if (key->type == KEY_TYPE_UNKNOWN) {
32 SET_ERRNO(ERROR_CRYPTO_KEY, "Key type is unknown");
33 return ERROR_CRYPTO_KEY;
34 }
35
36 if (key->type != KEY_TYPE_ED25519 && key->type != KEY_TYPE_X25519 && key->type != KEY_TYPE_GPG) {
37 SET_ERRNO(ERROR_CRYPTO_KEY, "Unsupported key type: %d", key->type);
38 return ERROR_CRYPTO_KEY;
39 }
40
41 // Check key data is not all zeros
42 bool is_zero = true;
43 for (int i = 0; i < 32; i++) {
44 if (key->key[i] != 0) {
45 is_zero = false;
46 break;
47 }
48 }
49
50 if (is_zero) {
51 SET_ERRNO(ERROR_CRYPTO_KEY, "Key data is all zeros");
52 return ERROR_CRYPTO_KEY;
53 }
54
55 // Check comment length
56 if (strlen(key->comment) >= MAX_COMMENT_LEN) {
57 SET_ERRNO(ERROR_CRYPTO_KEY, "Key comment too long: %zu (maximum %d)", strlen(key->comment), MAX_COMMENT_LEN - 1);
58 return ERROR_CRYPTO_KEY;
59 }
60
61 // Validate comment is valid UTF-8 (user-provided text in key files)
62 if (key->comment[0] != '\0' && !utf8_is_valid(key->comment)) {
63 SET_ERRNO(ERROR_CRYPTO_KEY, "Key comment contains invalid UTF-8 sequence");
64 return ERROR_CRYPTO_KEY;
65 }
66
67 return ASCIICHAT_OK;
68}
69
71 if (!key) {
72 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: key=%p", key);
74 }
75
76 // Check key type
77 if (key->type == KEY_TYPE_UNKNOWN) {
78 SET_ERRNO(ERROR_CRYPTO_KEY, "Private key type is unknown");
79 return ERROR_CRYPTO_KEY;
80 }
81
82 if (key->type != KEY_TYPE_ED25519 && key->type != KEY_TYPE_X25519) {
83 SET_ERRNO(ERROR_CRYPTO_KEY, "Unsupported private key type: %d", key->type);
84 return ERROR_CRYPTO_KEY;
85 }
86
87 // Check key data is not all zeros
88 bool is_zero = true;
89 size_t key_size = (key->type == KEY_TYPE_ED25519) ? 64 : 32;
90
91 for (size_t i = 0; i < key_size; i++) {
92 if (key->key.ed25519[i] != 0) {
93 is_zero = false;
94 break;
95 }
96 }
97
98 if (is_zero) {
99 SET_ERRNO(ERROR_CRYPTO_KEY, "Private key data is all zeros");
100 return ERROR_CRYPTO_KEY;
101 }
102
103 // Check comment length
104 if (strlen(key->key_comment) >= MAX_COMMENT_LEN) {
105 SET_ERRNO(ERROR_CRYPTO_KEY, "Private key comment too long: %zu (maximum %d)", strlen(key->key_comment), MAX_COMMENT_LEN - 1);
106 return ERROR_CRYPTO_KEY;
107 }
108
109 // Validate comment is valid UTF-8 (user-provided text in key files)
110 if (key->key_comment[0] != '\0' && !utf8_is_valid(key->key_comment)) {
111 SET_ERRNO(ERROR_CRYPTO_KEY, "Private key comment contains invalid UTF-8 sequence");
112 return ERROR_CRYPTO_KEY;
113 }
114
115 return ASCIICHAT_OK;
116}
117
118asciichat_error_t check_key_expiry(const public_key_t *key, bool *is_expired) {
119 if (!key || !is_expired) {
120 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: key=%p, is_expired=%p", key, is_expired);
121 return ERROR_INVALID_PARAM;
122 }
123
124 // For now, we don't implement key expiry checking
125 // This would require parsing key creation dates and expiration times
126 *is_expired = false;
127
128 return ASCIICHAT_OK;
129}
130
132 if (!key_path) {
133 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: key_path=%p", key_path);
134 return ERROR_INVALID_PARAM;
135 }
136
137 // Check file permissions
138 asciichat_error_t perm_result = platform_validate_key_file_permissions(key_path);
139 if (perm_result != ASCIICHAT_OK) {
140 return perm_result;
141 }
142
143 // Additional security checks have been implemented in check_key_strength()
144 // and check_key_patterns() functions. File permissions check is the critical one.
145 // Known weak keys database would require periodic updates and is beyond scope.
146
147 return ASCIICHAT_OK;
148}
149
150// =============================================================================
151// Key Format Validation
152// =============================================================================
153
155 if (!key_text) {
156 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: key_text=%p", key_text);
157 return ERROR_INVALID_PARAM;
158 }
159
160 // Check for SSH key format
161 if (strncmp(key_text, "ssh-ed25519 ", 12) != 0) {
162 SET_ERRNO(ERROR_CRYPTO_KEY, "SSH key does not start with 'ssh-ed25519 '");
163 return ERROR_CRYPTO_KEY;
164 }
165
166 // Check for base64 data
167 const char *base64_start = key_text + 12;
168 while (*base64_start == ' ' || *base64_start == '\t') {
169 base64_start++;
170 }
171
172 if (*base64_start == '\0' || *base64_start == '\n' || *base64_start == '\r') {
173 SET_ERRNO(ERROR_CRYPTO_KEY, "SSH key has no base64 data");
174 return ERROR_CRYPTO_KEY;
175 }
176
177 // Additional comprehensive SSH key validation (base64, blob structure, etc.)
178 // would require full OpenSSH format parsing. Basic format check above is sufficient
179 // to catch malformed keys. Full validation happens during key loading.
180
181 return ASCIICHAT_OK;
182}
183
185 if (!key_text) {
186 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: key_text=%p", key_text);
187 return ERROR_INVALID_PARAM;
188 }
189
190 // Check for GPG armor header
191 if (strncmp(key_text, "-----BEGIN PGP", 14) != 0) {
192 SET_ERRNO(ERROR_CRYPTO_KEY, "GPG key does not start with armor header");
193 return ERROR_CRYPTO_KEY;
194 }
195
196 // Check for GPG armor footer
197 if (strstr(key_text, "-----END PGP") == NULL) {
198 SET_ERRNO(ERROR_CRYPTO_KEY, "GPG key does not contain armor footer");
199 return ERROR_CRYPTO_KEY;
200 }
201
202 // Additional GPG key validation
203 // Validate armor format (should have valid armor headers)
204 bool has_version_header = (strstr(key_text, "Version:") != NULL);
205 bool has_charset_header = (strstr(key_text, "Charset:") != NULL || strstr(key_text, "Version:") != NULL);
206
207 if (!has_version_header && !has_charset_header) {
208 // Missing common armor headers - might be incomplete
209 log_warn("GPG armor missing version/charset headers - key might be incomplete");
210 }
211
212 // Validate base64 content (keys must have non-empty body between headers and footer)
213 const char *start_pos = strstr(key_text, "\n\n");
214 const char *end_pos = strstr(key_text, "\n-----END");
215 if (start_pos && end_pos && start_pos < end_pos) {
216 // -2 for \n\n at start_pos; check for underflow before casting to size_t
217 ptrdiff_t diff = end_pos - start_pos - 2;
218 if (diff <= 0) {
219 SET_ERRNO(ERROR_CRYPTO_KEY, "GPG key has empty or malformed body content");
220 return ERROR_CRYPTO_KEY;
221 }
222 }
223
224 return ASCIICHAT_OK;
225}
226
228 if (!key_hex) {
229 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: key_hex=%p", key_hex);
230 return ERROR_INVALID_PARAM;
231 }
232
233 // Check hex string length (32 bytes = 64 hex characters)
234 size_t hex_len = strlen(key_hex);
235 if (hex_len != 64) {
236 SET_ERRNO(ERROR_CRYPTO_KEY, "X25519 key has invalid length: %zu (expected 64)", hex_len);
237 return ERROR_CRYPTO_KEY;
238 }
239
240 // Check that all characters are valid hex
241 for (size_t i = 0; i < hex_len; i++) {
242 if (!isxdigit(key_hex[i])) {
243 SET_ERRNO(ERROR_CRYPTO_KEY, "X25519 key contains invalid hex character at position %zu: '%c'", i, key_hex[i]);
244 return ERROR_CRYPTO_KEY;
245 }
246 }
247
248 return ASCIICHAT_OK;
249}
250
251// =============================================================================
252// Key Security Checks
253// =============================================================================
254
256 if (!key || !is_weak) {
257 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: key=%p, is_weak=%p", key, is_weak);
258 return ERROR_INVALID_PARAM;
259 }
260
261 *is_weak = false;
262
263 // Check for all zeros (already checked in validate_public_key)
264 // Check for all ones
265 bool is_ones = true;
266 for (int i = 0; i < 32; i++) {
267 if (key->key[i] != 0xFF) {
268 is_ones = false;
269 break;
270 }
271 }
272
273 if (is_ones) {
274 *is_weak = true;
275 return ASCIICHAT_OK;
276 }
277
278 // Check for low entropy: Count unique bytes
279 // A properly random 32-byte key should have ~24-32 unique values
280 // Low entropy keys will have very few unique bytes
281 bool byte_seen[256] = {0};
282 int unique_bytes = 0;
283 for (int i = 0; i < 32; i++) {
284 uint8_t byte_val = key->key[i];
285 if (!byte_seen[byte_val]) {
286 byte_seen[byte_val] = true;
287 unique_bytes++;
288 }
289 }
290
291 // If less than 8 unique bytes in 32 bytes, entropy is very low
292 // This indicates non-random key generation (e.g., PRNG seed not properly initialized)
293 if (unique_bytes < 8) {
294 *is_weak = true;
295 return ASCIICHAT_OK;
296 }
297
298 // Additional weak key pattern detection:
299 // - Check for repeated patterns (handled in check_key_patterns)
300 // - Check for known weak sequences (see check_key_patterns)
301
302 return ASCIICHAT_OK;
303}
304
305asciichat_error_t check_key_patterns(const public_key_t *key, bool *has_weak_patterns) {
306 if (!key || !has_weak_patterns) {
307 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: key=%p, has_weak_patterns=%p", key, has_weak_patterns);
308 return ERROR_INVALID_PARAM;
309 }
310
311 *has_weak_patterns = false;
312
313 // Check for sequential patterns
314 bool is_sequential = true;
315 for (int i = 1; i < 32; i++) {
316 if (key->key[i] != key->key[i - 1] + 1) {
317 is_sequential = false;
318 break;
319 }
320 }
321
322 if (is_sequential) {
323 *has_weak_patterns = true;
324 return ASCIICHAT_OK;
325 }
326
327 // Check for repeated byte patterns (e.g., all 0xAA, all 0x55)
328 // Common weak patterns to check
329 const uint8_t weak_bytes[] = {0x00, 0xFF, 0xAA, 0x55, 0x11, 0x22, 0x33, 0x44, 0x66, 0x77, 0x88, 0x99, 0xBB, 0xCC, 0xDD, 0xEE};
330 for (size_t pattern_idx = 0; pattern_idx < sizeof(weak_bytes); pattern_idx++) {
331 uint8_t pattern_byte = weak_bytes[pattern_idx];
332 bool is_repeated = true;
333 for (size_t j = 0; j < 32; j++) {
334 // CORRECT: Compare against pattern_byte, not key->key[0]
335 if (key->key[j] != pattern_byte) {
336 is_repeated = false;
337 break;
338 }
339 }
340 if (is_repeated) {
341 *has_weak_patterns = true;
342 return ASCIICHAT_OK;
343 }
344 }
345
346 // Check for alternating bit patterns (e.g., 0xAA 0xBB 0xAA 0xBB or 0x55 0xAA 0x55 0xAA)
347 // A proper alternating pattern has at most 2 unique byte values that truly alternate
348 bool byte_appeared[256] = {0};
349 int unique_values = 0;
350 for (size_t i = 0; i < 32; i++) {
351 if (!byte_appeared[key->key[i]]) {
352 byte_appeared[key->key[i]] = true;
353 unique_values++;
354 }
355 }
356
357 // Only consider it weak if there are 2 or fewer unique values AND they properly alternate
358 if (unique_values <= 2) {
359 bool is_alternating = true;
360 for (size_t i = 1; i < 32; i++) {
361 // In a true alternating pattern:
362 // 1. Adjacent bytes must be different
363 // 2. Pattern must repeat every 2 bytes (byte[i] == byte[i-2])
364 if (key->key[i] == key->key[i - 1] || (i >= 2 && key->key[i] != key->key[i - 2])) {
365 is_alternating = false;
366 break;
367 }
368 }
369 if (is_alternating) {
370 *has_weak_patterns = true;
371 return ASCIICHAT_OK;
372 }
373 }
374
375 // Check for common cryptographic initialization patterns
376 // OpenSSL weak keys, old Debian SSH keys, etc.
377 uint32_t *words = (uint32_t *)key->key;
378 // Check if all 32-bit words are identical
379 bool all_words_same = true;
380 for (size_t i = 1; i < 8; i++) {
381 if (words[i] != words[0]) {
382 all_words_same = false;
383 break;
384 }
385 }
386 if (all_words_same) {
387 *has_weak_patterns = true;
388 return ASCIICHAT_OK;
389 }
390
391 return ASCIICHAT_OK;
392}
393
394// =============================================================================
395// Key Comparison and Matching
396// =============================================================================
397
398asciichat_error_t compare_public_keys(const public_key_t *key1, const public_key_t *key2, bool *are_equal) {
399 if (!key1 || !key2 || !are_equal) {
400 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: key1=%p, key2=%p, are_equal=%p", key1, key2, are_equal);
401 return ERROR_INVALID_PARAM;
402 }
403
404 *are_equal = false;
405
406 // Compare key types
407 if (key1->type != key2->type) {
408 return ASCIICHAT_OK;
409 }
410
411 // Compare key data using constant-time comparison
412 if (sodium_memcmp(key1->key, key2->key, 32) == 0) {
413 *are_equal = true;
414 }
415
416 return ASCIICHAT_OK;
417}
418
419asciichat_error_t check_key_fingerprint(const public_key_t *key, const uint8_t *fingerprint, size_t fingerprint_len, bool *matches) {
420 if (!key || !fingerprint || !matches) {
421 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: key=%p, fingerprint=%p, matches=%p", key, fingerprint, matches);
422 return ERROR_INVALID_PARAM;
423 }
424
425 *matches = false;
426
427 // Generate fingerprint for the key
428 uint8_t key_fingerprint[crypto_hash_sha256_BYTES];
429 asciichat_error_t fingerprint_result = generate_key_fingerprint(key, key_fingerprint, 32);
430 if (fingerprint_result != ASCIICHAT_OK) {
431 return fingerprint_result;
432 }
433
434 // Compare fingerprints
435 size_t compare_len = (fingerprint_len < 32) ? fingerprint_len : 32;
436 if (sodium_memcmp(key_fingerprint, fingerprint, compare_len) == 0) {
437 *matches = true;
438 }
439
440 return ASCIICHAT_OK;
441}
442
443asciichat_error_t generate_key_fingerprint(const public_key_t *key, uint8_t *fingerprint_out, size_t fingerprint_size) {
444 if (!key || !fingerprint_out) {
445 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: key=%p, fingerprint_out=%p", key, fingerprint_out);
446 return ERROR_INVALID_PARAM;
447 }
448
449 if (fingerprint_size < 32) {
450 SET_ERRNO(ERROR_INVALID_PARAM, "Fingerprint buffer too small: %zu (minimum 32)", fingerprint_size);
451 return ERROR_INVALID_PARAM;
452 }
453
454 // Generate SHA-256 fingerprint of the key
455 if (key_fingerprint_digest(key->key, fingerprint_out) != ASCIICHAT_OK) {
456 SET_ERRNO(ERROR_CRYPTO, "Failed to generate key fingerprint");
457 return ERROR_CRYPTO;
458 }
459
460 return ASCIICHAT_OK;
461}
Synchronized per-thread pending error stacks and value snapshots. SET_ERRNO pushes,...
#define SET_ERRNO(code,...)
unsigned int uint32_t
unsigned char uint8_t
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_CRYPTO_KEY
Definition error_codes.h:98
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_CRYPTO
Definition error_codes.h:97
@ ERROR_INVALID_PARAM
uint8_t key[CRYPTO_PUBLIC_KEY_SIZE]
Definition key_types.h:78
asciichat_error_t check_key_expiry(const public_key_t *key, bool *is_expired)
Check if a key is expired.
uint8_t ed25519[ED25519_PRIVATE_KEY_SIZE]
Definition key_types.h:104
asciichat_error_t validate_gpg_key_format(const char *key_text)
Validate GPG key format.
asciichat_error_t validate_ssh_key_format(const char *key_text)
Validate SSH key format.
key_type_t type
Definition key_types.h:102
asciichat_error_t validate_key_security(const char *key_path)
Validate key permissions and security.
char comment[MAX_COMMENT_LEN]
Definition key_types.h:79
asciichat_error_t validate_private_key(const private_key_t *key)
Validate a private key structure.
asciichat_error_t validate_public_key(const public_key_t *key)
Validate a public key structure.
char key_comment[MAX_COMMENT_LEN]
Definition key_types.h:110
asciichat_error_t check_key_fingerprint(const public_key_t *key, const uint8_t *fingerprint, size_t fingerprint_len, bool *matches)
Check if key matches a fingerprint.
asciichat_error_t check_key_patterns(const public_key_t *key, bool *has_weak_patterns)
Check for key reuse or weak patterns.
asciichat_error_t check_key_strength(const public_key_t *key, bool *is_weak)
Check if key has weak parameters.
asciichat_error_t validate_x25519_key_format(const char *key_hex)
Validate X25519 key format.
asciichat_error_t compare_public_keys(const public_key_t *key1, const public_key_t *key2, bool *are_equal)
Compare two public keys for equality.
asciichat_error_t generate_key_fingerprint(const public_key_t *key, uint8_t *fingerprint_out, size_t fingerprint_size)
Generate key fingerprint.
key_type_t type
Definition key_types.h:77
union private_key_t::@040247167361101132173265304166142033301213115260 key
@ KEY_TYPE_UNKNOWN
Definition key_types.h:57
@ KEY_TYPE_ED25519
Definition key_types.h:58
@ KEY_TYPE_GPG
Definition key_types.h:60
@ KEY_TYPE_X25519
Definition key_types.h:59
#define log_warn(...)
Log a WARN message.
Definition log/log.h:615
bool utf8_is_valid(const char *str)
Check if a string is valid UTF-8.
Definition utf8.c:128
⚙️ Common definitions, error codes, macros, and types shared throughout the application
asciichat_error_t key_fingerprint_digest(const uint8_t public_key[ED25519_PUBLIC_KEY_SIZE], uint8_t digest[KEYMASK_DIGEST_SIZE])
Definition keymask.c:11
#define MAX_COMMENT_LEN
Definition sizes.h:176
🔤 String Manipulation and Shell Escaping Utilities
Private identity-key material used for server authentication and signing.
Definition key_types.h:101
The normalized public identity used by ascii-chat's crypto and key-management code.
Definition key_types.h:76
🔤 UTF-8 Encoding and Decoding Utilities