-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcrypto.c
More file actions
518 lines (447 loc) · 16.3 KB
/
crypto.c
File metadata and controls
518 lines (447 loc) · 16.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
#ifndef _WIN32
#define _POSIX_C_SOURCE 200809L
#endif
#include "crypto.h"
#include "compat.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <unistd.h>
#include <openssl/evp.h>
#include <openssl/rand.h>
#include <openssl/sha.h>
/*
* Declare the one symbol we need from libargon2 without relying on the dev
* package header (libargon2-1 is installed; libargon2-dev is not).
* ARGON2_OK is 0 in the reference implementation.
*/
extern int argon2id_hash_raw(uint32_t t_cost, uint32_t m_cost, uint32_t parallelism,
const void *pwd, size_t pwdlen,
const void *salt, size_t saltlen,
void *hash, size_t hashlen);
/* -------------------------------------------------------------------------
* Byte-order helpers (big-endian)
* ---------------------------------------------------------------------- */
static void write_be32(uint8_t *b, uint32_t v) {
b[0] = (uint8_t)(v >> 24);
b[1] = (uint8_t)(v >> 16);
b[2] = (uint8_t)(v >> 8);
b[3] = (uint8_t)(v );
}
static void write_be64(uint8_t *b, uint64_t v) {
for (int i = 7; i >= 0; i--) {
b[i] = (uint8_t)(v & 0xff);
v >>= 8;
}
}
static uint32_t read_be32(const uint8_t *b) {
return ((uint32_t)b[0] << 24) | ((uint32_t)b[1] << 16) |
((uint32_t)b[2] << 8) | (uint32_t)b[3];
}
static uint64_t read_be64(const uint8_t *b) {
uint64_t v = 0;
for (int i = 0; i < 8; i++)
v = (v << 8) | b[i];
return v;
}
/* -------------------------------------------------------------------------
* Key derivation
* ---------------------------------------------------------------------- */
/* Argon2id: time=1, memory=69*1024 KiB, parallelism=4 — matches Go parameters. */
static int derive_key(const uint8_t *pw, size_t pw_len,
const uint8_t *salt, uint8_t *key) {
/* ARGON2_OK == 0 in the reference implementation. */
int rc = argon2id_hash_raw(1, 69 * 1024, 4,
pw, pw_len, salt, SALT_LEN,
key, KEY_LEN);
return rc == 0 ? 0 : -1;
}
/* Derive chunk nonce by XORing base_nonce with chunk_index (little-endian, 8 bytes). */
static void derive_chunk_nonce(const uint8_t *base, uint64_t idx, uint8_t *nonce) {
memcpy(nonce, base, NONCE_LEN);
for (int i = 0; i < 8; i++)
nonce[i] ^= (uint8_t)(idx >> (i * 8));
}
/*
* staticPair: deterministic salt + nonce from password via SHA-256.
* salt = SHA256("cryp-salt-decoy:" + password)[:16]
* nonce = SHA256("decoy-cryp-nonce:" + password)[:12]
* Returns 0 on success, -1 on allocation failure.
*/
static int static_pair(const uint8_t *pw, size_t pw_len,
uint8_t salt[SALT_LEN], uint8_t nonce[NONCE_LEN]) {
const char *sp = "cryp-salt-decoy:";
size_t sl = strlen(sp);
uint8_t *tmp = malloc(sl + pw_len);
if (!tmp) return -1;
memcpy(tmp, sp, sl);
memcpy(tmp + sl, pw, pw_len);
uint8_t h[SHA256_DIGEST_LENGTH];
SHA256(tmp, sl + pw_len, h);
free(tmp);
memcpy(salt, h, SALT_LEN);
const char *np = "decoy-cryp-nonce:";
size_t nl = strlen(np);
tmp = malloc(nl + pw_len);
if (!tmp) return -1;
memcpy(tmp, np, nl);
memcpy(tmp + nl, pw, pw_len);
SHA256(tmp, nl + pw_len, h);
free(tmp);
memcpy(nonce, h, NONCE_LEN);
return 0;
}
/* -------------------------------------------------------------------------
* AES-256-GCM helpers
* ---------------------------------------------------------------------- */
/*
* Encrypt plaintext with AES-256-GCM.
* Output layout: [ciphertext][tag:16]
* Returns total output length (pt_len + GCM_TAG_LEN) or -1 on error.
*/
static int gcm_encrypt(const uint8_t *key, const uint8_t *iv,
const uint8_t *pt, int pt_len, uint8_t *ct) {
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
if (!ctx) return -1;
int len = 0, ct_len = 0, ok = -1;
if (EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL) != 1) goto done;
if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, NONCE_LEN, NULL) != 1) goto done;
if (EVP_EncryptInit_ex(ctx, NULL, NULL, key, iv) != 1) goto done;
if (EVP_EncryptUpdate(ctx, ct, &len, pt, pt_len) != 1) goto done;
ct_len = len;
if (EVP_EncryptFinal_ex(ctx, ct + ct_len, &len) != 1) goto done;
ct_len += len;
if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, GCM_TAG_LEN, ct + ct_len) != 1) goto done;
ct_len += GCM_TAG_LEN;
ok = ct_len;
done:
EVP_CIPHER_CTX_free(ctx);
return ok;
}
/*
* Decrypt AES-256-GCM chunk.
* ciphertext layout: [ciphertext][tag:16]
* Returns plaintext length or -1 on error (including authentication failure).
*/
static int gcm_decrypt(const uint8_t *key, const uint8_t *iv,
const uint8_t *ct, int ct_len, uint8_t *pt) {
if (ct_len < GCM_TAG_LEN) return -1;
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
if (!ctx) return -1;
int len = 0, pt_len = 0, ok = -1;
int data_len = ct_len - GCM_TAG_LEN;
if (EVP_DecryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL) != 1) goto done;
if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, NONCE_LEN, NULL) != 1) goto done;
if (EVP_DecryptInit_ex(ctx, NULL, NULL, key, iv) != 1) goto done;
if (EVP_DecryptUpdate(ctx, pt, &len, ct, data_len) != 1) goto done;
pt_len = len;
/* Set expected tag (last GCM_TAG_LEN bytes) */
if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, GCM_TAG_LEN,
(void *)(ct + data_len)) != 1) goto done;
/* Returns <= 0 on authentication failure */
if (EVP_DecryptFinal_ex(ctx, pt + pt_len, &len) <= 0) goto done;
pt_len += len;
ok = pt_len;
done:
EVP_CIPHER_CTX_free(ctx);
return ok;
}
/* -------------------------------------------------------------------------
* Decoy output (wrong-password behaviour)
* ---------------------------------------------------------------------- */
/*
* Re-encrypt the post-header payload of src with a key/nonce derived
* deterministically from the (wrong) password, and write raw ciphertext to dst.
* Streams through the file to avoid loading the entire payload into memory.
*/
static int produce_decoy(const char *src, const char *dst,
const uint8_t *pw, size_t pw_len) {
FILE *f = fopen(src, "rb");
if (!f) return -1;
/* Seek past the header — caller guarantees src is a valid ccryp file */
if (fseek(f, HEADER_SIZE, SEEK_SET) != 0) { fclose(f); return -1; }
uint8_t ssalt[SALT_LEN], snonce[NONCE_LEN];
if (static_pair(pw, pw_len, ssalt, snonce) != 0) { fclose(f); return -1; }
uint8_t key[KEY_LEN];
if (derive_key(pw, pw_len, ssalt, key) != 0) { fclose(f); return -1; }
FILE *out = fopen(dst, "wb");
if (!out) { fclose(f); return -1; }
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
if (!ctx) { fclose(f); fclose(out); return -1; }
int ok = -1;
if (EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL) != 1) goto done;
if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, NONCE_LEN, NULL) != 1) goto done;
if (EVP_EncryptInit_ex(ctx, NULL, NULL, key, snonce) != 1) goto done;
{
uint8_t pt[65536];
uint8_t ct[65536];
size_t n;
while ((n = fread(pt, 1, sizeof(pt), f)) > 0) {
int len = 0;
if (EVP_EncryptUpdate(ctx, ct, &len, pt, (int)n) != 1) goto done;
if (len > 0 && fwrite(ct, 1, (size_t)len, out) != (size_t)len) goto done;
}
if (ferror(f)) goto done;
int len = 0;
uint8_t final_ct[32];
if (EVP_EncryptFinal_ex(ctx, final_ct, &len) != 1) goto done;
if (len > 0 && fwrite(final_ct, 1, (size_t)len, out) != (size_t)len) goto done;
uint8_t tag[GCM_TAG_LEN];
if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, GCM_TAG_LEN, tag) != 1) goto done;
if (fwrite(tag, 1, GCM_TAG_LEN, out) != GCM_TAG_LEN) goto done;
}
ok = 0;
done:
EVP_CIPHER_CTX_free(ctx);
fclose(f);
fclose(out);
if (ok != 0) remove(dst);
return ok;
}
/* -------------------------------------------------------------------------
* Public API
* ---------------------------------------------------------------------- */
int encrypt_file(const char *src, const char *dst,
const uint8_t *pw, size_t pw_len, int chunk_size) {
if (chunk_size <= 0) {
fprintf(stderr, "error: invalid chunk size\n");
return -1;
}
FILE *fsrc = fopen(src, "rb");
if (!fsrc) { fprintf(stderr, "error: cannot open %s\n", src); return -1; }
if (fseek(fsrc, 0, SEEK_END) != 0) {
fprintf(stderr, "error: cannot seek %s\n", src);
fclose(fsrc); return -1;
}
long raw_size = ftell(fsrc);
if (raw_size < 0) {
fprintf(stderr, "error: cannot ftell %s\n", src);
fclose(fsrc); return -1;
}
int64_t file_size = (int64_t)raw_size;
if (fseek(fsrc, 0, SEEK_SET) != 0) {
fprintf(stderr, "error: cannot seek %s\n", src);
fclose(fsrc); return -1;
}
FILE *fdst = fopen(dst, "wb");
if (!fdst) {
fprintf(stderr, "error: cannot create %s\n", dst);
fclose(fsrc);
return -1;
}
uint8_t salt[SALT_LEN], base_nonce[NONCE_LEN], key[KEY_LEN];
if (RAND_bytes(salt, SALT_LEN) != 1 || RAND_bytes(base_nonce, NONCE_LEN) != 1) {
fprintf(stderr, "error: generating random bytes\n");
goto fail;
}
if (derive_key(pw, pw_len, salt, key) != 0) {
fprintf(stderr, "error: key derivation failed\n");
goto fail;
}
uint64_t num_chunks = 0;
if (file_size > 0)
num_chunks = (uint64_t)((file_size + chunk_size - 1) / chunk_size);
/* Write header */
uint8_t hdr[HEADER_SIZE];
memcpy(hdr, salt, SALT_LEN);
memcpy(hdr + SALT_LEN, base_nonce, NONCE_LEN);
write_be32(hdr + SALT_LEN + NONCE_LEN, (uint32_t)chunk_size);
write_be64(hdr + SALT_LEN + NONCE_LEN + 4, (uint64_t)file_size);
write_be64(hdr + SALT_LEN + NONCE_LEN + 12, num_chunks);
if (fwrite(hdr, 1, HEADER_SIZE, fdst) != HEADER_SIZE) {
fprintf(stderr, "error: writing header\n");
goto fail;
}
uint8_t *pt_buf = malloc((size_t)chunk_size);
uint8_t *ct_buf = malloc((size_t)chunk_size + GCM_TAG_LEN);
if (!pt_buf || !ct_buf) {
fprintf(stderr, "error: out of memory\n");
free(pt_buf); free(ct_buf);
goto fail;
}
uint64_t chunk_idx = 0;
size_t n;
while ((n = fread(pt_buf, 1, (size_t)chunk_size, fsrc)) > 0) {
uint8_t nonce[NONCE_LEN];
derive_chunk_nonce(base_nonce, chunk_idx, nonce);
int ct_len = gcm_encrypt(key, nonce, pt_buf, (int)n, ct_buf);
if (ct_len < 0) {
fprintf(stderr, "error: encryption failed\n");
free(pt_buf); free(ct_buf);
goto fail;
}
uint8_t lbuf[4];
write_be32(lbuf, (uint32_t)ct_len);
if (fwrite(lbuf, 1, 4, fdst) != 4 ||
fwrite(ct_buf, 1, (size_t)ct_len, fdst) != (size_t)ct_len) {
fprintf(stderr, "error: writing chunk\n");
free(pt_buf); free(ct_buf);
goto fail;
}
chunk_idx++;
}
if (ferror(fsrc)) {
fprintf(stderr, "error: reading source file\n");
free(pt_buf); free(ct_buf);
goto fail;
}
free(pt_buf);
free(ct_buf);
fclose(fsrc);
fclose(fdst);
return 0;
fail:
fclose(fsrc);
fclose(fdst);
remove(dst);
return -1;
}
int decrypt_file(const char *src, const char *dst,
const uint8_t *pw, size_t pw_len) {
FILE *fsrc = fopen(src, "rb");
if (!fsrc) { fprintf(stderr, "error: cannot open %s\n", src); return -1; }
/* Read and parse header */
uint8_t hdr[HEADER_SIZE];
if (fread(hdr, 1, HEADER_SIZE, fsrc) != HEADER_SIZE) {
fprintf(stderr, "error: file too short or not encrypted by ccryp\n");
fclose(fsrc);
return -1;
}
uint8_t salt[SALT_LEN], base_nonce[NONCE_LEN];
memcpy(salt, hdr, SALT_LEN);
memcpy(base_nonce, hdr + SALT_LEN, NONCE_LEN);
uint32_t chunk_size = read_be32(hdr + SALT_LEN + NONCE_LEN);
uint64_t file_size = read_be64(hdr + SALT_LEN + NONCE_LEN + 4);
uint64_t num_chunks = read_be64(hdr + SALT_LEN + NONCE_LEN + 12);
if (chunk_size == 0 || chunk_size > 1024u * 1024u * 1024u) {
fprintf(stderr, "error: corrupt encryption header\n");
fclose(fsrc);
return -1;
}
uint8_t key[KEY_LEN];
if (derive_key(pw, pw_len, salt, key) != 0) {
fprintf(stderr, "error: key derivation failed\n");
fclose(fsrc);
return -1;
}
/* Create temp file in same directory as dst for atomic rename */
char dir[4096];
const char *last_sep = strrchr(dst, '/');
#ifdef _WIN32
{
const char *bs = strrchr(dst, '\\');
if (!last_sep || (bs && bs > last_sep)) last_sep = bs;
}
#endif
if (!last_sep) {
dir[0] = '.'; dir[1] = '\0';
} else if (last_sep == dst) {
dir[0] = dst[0]; dir[1] = '\0';
} else {
size_t dlen = (size_t)(last_sep - dst);
if (dlen >= sizeof(dir)) dlen = sizeof(dir) - 1;
memcpy(dir, dst, dlen);
dir[dlen] = '\0';
}
char tmp_path[4096 + 32];
int tmp_fd = mkstemp_in_dir(tmp_path, sizeof(tmp_path), dir);
if (tmp_fd < 0) {
fprintf(stderr, "error: mkstemp failed\n");
fclose(fsrc);
return -1;
}
FILE *ftmp = fdopen(tmp_fd, "wb");
if (!ftmp) {
close(tmp_fd);
remove(tmp_path);
fclose(fsrc);
return -1;
}
size_t ct_cap = (size_t)chunk_size + GCM_TAG_LEN;
uint8_t *ct_buf = malloc(ct_cap);
uint8_t *pt_buf = malloc(ct_cap);
if (!ct_buf || !pt_buf) {
free(ct_buf); free(pt_buf);
fclose(ftmp); remove(tmp_path);
fclose(fsrc);
return -1;
}
int64_t total_written = 0;
int auth_fail = 0;
int io_err = 0;
for (uint64_t ci = 0; ci < num_chunks; ci++) {
uint8_t lbuf[4];
if (fread(lbuf, 1, 4, fsrc) != 4) {
fprintf(stderr, "error: reading chunk size (chunk %llu)\n",
(unsigned long long)ci);
io_err = 1;
break;
}
uint32_t ct_len = read_be32(lbuf);
if (ct_len == 0 || ct_len > 1024u * 1024u * 1024u) {
fprintf(stderr, "error: corrupt chunk length\n");
io_err = 1;
break;
}
/* Grow buffer if needed (chunk_size from header may differ) */
if ((size_t)ct_len > ct_cap) {
ct_cap = (size_t)ct_len;
uint8_t *tmp = realloc(ct_buf, ct_cap);
uint8_t *tmp2 = realloc(pt_buf, ct_cap);
if (!tmp || !tmp2) {
free(tmp ? tmp : ct_buf);
free(tmp2 ? tmp2 : pt_buf);
ct_buf = pt_buf = NULL;
io_err = 1;
break;
}
ct_buf = tmp;
pt_buf = tmp2;
}
if (fread(ct_buf, 1, ct_len, fsrc) != ct_len) {
fprintf(stderr, "error: reading chunk data\n");
io_err = 1;
break;
}
uint8_t nonce[NONCE_LEN];
derive_chunk_nonce(base_nonce, ci, nonce);
int pt_len = gcm_decrypt(key, nonce, ct_buf, (int)ct_len, pt_buf);
if (pt_len < 0) {
auth_fail = 1;
break;
}
if (fwrite(pt_buf, 1, (size_t)pt_len, ftmp) != (size_t)pt_len) {
fprintf(stderr, "error: writing plaintext\n");
io_err = 1;
break;
}
total_written += pt_len;
}
free(ct_buf);
free(pt_buf);
fclose(ftmp);
fclose(fsrc);
if (auth_fail) {
remove(tmp_path);
/* Wrong password: produce deterministic decoy instead of an error */
return produce_decoy(src, dst, pw, pw_len);
}
if (io_err) {
remove(tmp_path);
return -1;
}
if (total_written != (int64_t)file_size) {
fprintf(stderr, "error: size mismatch: expected %llu got %lld\n",
(unsigned long long)file_size, (long long)total_written);
remove(tmp_path);
return -1;
}
/* Atomic rename */
if (rename(tmp_path, dst) != 0) {
fprintf(stderr, "error: rename %s → %s failed\n", tmp_path, dst);
remove(tmp_path);
return -1;
}
return 0;
}