1/*
2 *  \brief  Generic file encryption program using generic wrappers for configured
3 *          security.
4 *
5 *  Copyright The Mbed TLS Contributors
6 *  SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
7 */
8
9/* Enable definition of fileno() even when compiling with -std=c99. Must be
10 * set before mbedtls_config.h, which pulls in glibc's features.h indirectly.
11 * Harmless on other platforms. */
12#define _POSIX_C_SOURCE 200112L
13
14#include "mbedtls/build_info.h"
15
16#include "mbedtls/platform.h"
17
18#if defined(MBEDTLS_CIPHER_C) && defined(MBEDTLS_MD_C) && \
19    defined(MBEDTLS_FS_IO)
20#include "mbedtls/cipher.h"
21#include "mbedtls/md.h"
22#include "mbedtls/platform_util.h"
23
24#include <stdio.h>
25#include <stdlib.h>
26#include <string.h>
27#endif
28
29#if defined(_WIN32)
30#include <windows.h>
31#if !defined(_WIN32_WCE)
32#include <io.h>
33#endif
34#else
35#include <sys/types.h>
36#include <unistd.h>
37#endif
38
39#define MODE_ENCRYPT    0
40#define MODE_DECRYPT    1
41
42#define USAGE   \
43    "\n  crypt_and_hash <mode> <input filename> <output filename> <cipher> <mbedtls_md> <key>\n" \
44    "\n   <mode>: 0 = encrypt, 1 = decrypt\n" \
45    "\n  example: crypt_and_hash 0 file file.aes AES-128-CBC SHA1 hex:E76B2413958B00E193\n" \
46    "\n"
47
48#if !defined(MBEDTLS_CIPHER_C) || !defined(MBEDTLS_MD_C) || \
49    !defined(MBEDTLS_FS_IO)
50int main(void)
51{
52    mbedtls_printf("MBEDTLS_CIPHER_C and/or MBEDTLS_MD_C and/or MBEDTLS_FS_IO not defined.\n");
53    mbedtls_exit(0);
54}
55#else
56
57
58int main(int argc, char *argv[])
59{
60    int ret = 1, i;
61    unsigned n;
62    int exit_code = MBEDTLS_EXIT_FAILURE;
63    int mode;
64    size_t keylen, ilen, olen;
65    FILE *fkey, *fin = NULL, *fout = NULL;
66
67    char *p;
68    unsigned char IV[16];
69    unsigned char key[512];
70    unsigned char digest[MBEDTLS_MD_MAX_SIZE];
71    unsigned char buffer[1024];
72    unsigned char output[1024];
73    unsigned char diff;
74
75    const mbedtls_cipher_info_t *cipher_info;
76    const mbedtls_md_info_t *md_info;
77    mbedtls_cipher_context_t cipher_ctx;
78    mbedtls_md_context_t md_ctx;
79    mbedtls_cipher_mode_t cipher_mode;
80    unsigned int cipher_block_size;
81    unsigned char md_size;
82#if defined(_WIN32_WCE)
83    long filesize, offset;
84#elif defined(_WIN32)
85    LARGE_INTEGER li_size;
86    __int64 filesize, offset;
87#else
88    off_t filesize, offset;
89#endif
90
91    mbedtls_cipher_init(&cipher_ctx);
92    mbedtls_md_init(&md_ctx);
93
94    /*
95     * Parse the command-line arguments.
96     */
97    if (argc != 7) {
98        const int *list;
99
100        mbedtls_printf(USAGE);
101
102        mbedtls_printf("Available ciphers:\n");
103        list = mbedtls_cipher_list();
104        while (*list) {
105            cipher_info = mbedtls_cipher_info_from_type(*list);
106            const char *name = mbedtls_cipher_info_get_name(cipher_info);
107
108            if (name) {
109                mbedtls_printf("  %s\n", mbedtls_cipher_info_get_name(cipher_info));
110            }
111            list++;
112        }
113
114        mbedtls_printf("\nAvailable message digests:\n");
115        list = mbedtls_md_list();
116        while (*list) {
117            md_info = mbedtls_md_info_from_type(*list);
118            mbedtls_printf("  %s\n", mbedtls_md_get_name(md_info));
119            list++;
120        }
121
122        goto exit;
123    }
124
125    mode = atoi(argv[1]);
126
127    if (mode != MODE_ENCRYPT && mode != MODE_DECRYPT) {
128        mbedtls_fprintf(stderr, "invalid operation mode\n");
129        goto exit;
130    }
131
132    if (strcmp(argv[2], argv[3]) == 0) {
133        mbedtls_fprintf(stderr, "input and output filenames must differ\n");
134        goto exit;
135    }
136
137    if ((fin = fopen(argv[2], "rb")) == NULL) {
138        mbedtls_fprintf(stderr, "fopen(%s,rb) failed\n", argv[2]);
139        goto exit;
140    }
141
142    if ((fout = fopen(argv[3], "wb+")) == NULL) {
143        mbedtls_fprintf(stderr, "fopen(%s,wb+) failed\n", argv[3]);
144        goto exit;
145    }
146
147    /* Ensure no stdio buffering of secrets, as such buffers cannot be wiped. */
148    mbedtls_setbuf(fin, NULL);
149    mbedtls_setbuf(fout, NULL);
150
151    /*
152     * Read the Cipher and MD from the command line
153     */
154    cipher_info = mbedtls_cipher_info_from_string(argv[4]);
155    if (cipher_info == NULL) {
156        mbedtls_fprintf(stderr, "Cipher '%s' not found\n", argv[4]);
157        goto exit;
158    }
159    if ((ret = mbedtls_cipher_setup(&cipher_ctx, cipher_info)) != 0) {
160        mbedtls_fprintf(stderr, "mbedtls_cipher_setup failed\n");
161        goto exit;
162    }
163
164    md_info = mbedtls_md_info_from_string(argv[5]);
165    if (md_info == NULL) {
166        mbedtls_fprintf(stderr, "Message Digest '%s' not found\n", argv[5]);
167        goto exit;
168    }
169
170    if (mbedtls_md_setup(&md_ctx, md_info, 1) != 0) {
171        mbedtls_fprintf(stderr, "mbedtls_md_setup failed\n");
172        goto exit;
173    }
174
175    /*
176     * Read the secret key from file or command line
177     */
178    if ((fkey = fopen(argv[6], "rb")) != NULL) {
179        keylen = fread(key, 1, sizeof(key), fkey);
180        fclose(fkey);
181    } else {
182        if (memcmp(argv[6], "hex:", 4) == 0) {
183            p = &argv[6][4];
184            keylen = 0;
185
186            while (sscanf(p, "%02X", (unsigned int *) &n) > 0 &&
187                   keylen < (int) sizeof(key)) {
188                key[keylen++] = (unsigned char) n;
189                p += 2;
190            }
191        } else {
192            keylen = strlen(argv[6]);
193
194            if (keylen > (int) sizeof(key)) {
195                keylen = (int) sizeof(key);
196            }
197
198            memcpy(key, argv[6], keylen);
199        }
200    }
201
202#if defined(_WIN32_WCE)
203    filesize = fseek(fin, 0L, SEEK_END);
204#else
205#if defined(_WIN32)
206    /*
207     * Support large files (> 2Gb) on Win32
208     */
209    li_size.QuadPart = 0;
210    li_size.LowPart  =
211        SetFilePointer((HANDLE) _get_osfhandle(_fileno(fin)),
212                       li_size.LowPart, &li_size.HighPart, FILE_END);
213
214    if (li_size.LowPart == 0xFFFFFFFF && GetLastError() != NO_ERROR) {
215        mbedtls_fprintf(stderr, "SetFilePointer(0,FILE_END) failed\n");
216        goto exit;
217    }
218
219    filesize = li_size.QuadPart;
220#else
221    if ((filesize = lseek(fileno(fin), 0, SEEK_END)) < 0) {
222        perror("lseek");
223        goto exit;
224    }
225#endif
226#endif
227
228    if (fseek(fin, 0, SEEK_SET) < 0) {
229        mbedtls_fprintf(stderr, "fseek(0,SEEK_SET) failed\n");
230        goto exit;
231    }
232
233    md_size = mbedtls_md_get_size(md_info);
234    cipher_block_size = mbedtls_cipher_get_block_size(&cipher_ctx);
235
236    if (mode == MODE_ENCRYPT) {
237        /*
238         * Generate the initialization vector as:
239         * IV = MD( filesize || filename )[0..15]
240         */
241        for (i = 0; i < 8; i++) {
242            buffer[i] = (unsigned char) (filesize >> (i << 3));
243        }
244
245        p = argv[2];
246
247        if (mbedtls_md_starts(&md_ctx) != 0) {
248            mbedtls_fprintf(stderr, "mbedtls_md_starts() returned error\n");
249            goto exit;
250        }
251        if (mbedtls_md_update(&md_ctx, buffer, 8) != 0) {
252            mbedtls_fprintf(stderr, "mbedtls_md_update() returned error\n");
253            goto exit;
254        }
255        if (mbedtls_md_update(&md_ctx, (unsigned char *) p, strlen(p))
256            != 0) {
257            mbedtls_fprintf(stderr, "mbedtls_md_update() returned error\n");
258            goto exit;
259        }
260        if (mbedtls_md_finish(&md_ctx, digest) != 0) {
261            mbedtls_fprintf(stderr, "mbedtls_md_finish() returned error\n");
262            goto exit;
263        }
264
265        memcpy(IV, digest, 16);
266
267        /*
268         * Append the IV at the beginning of the output.
269         */
270        if (fwrite(IV, 1, 16, fout) != 16) {
271            mbedtls_fprintf(stderr, "fwrite(%d bytes) failed\n", 16);
272            goto exit;
273        }
274
275        /*
276         * Hash the IV and the secret key together 8192 times
277         * using the result to setup the AES context and HMAC.
278         */
279        memset(digest, 0,  32);
280        memcpy(digest, IV, 16);
281
282        for (i = 0; i < 8192; i++) {
283            if (mbedtls_md_starts(&md_ctx) != 0) {
284                mbedtls_fprintf(stderr,
285                                "mbedtls_md_starts() returned error\n");
286                goto exit;
287            }
288            if (mbedtls_md_update(&md_ctx, digest, 32) != 0) {
289                mbedtls_fprintf(stderr,
290                                "mbedtls_md_update() returned error\n");
291                goto exit;
292            }
293            if (mbedtls_md_update(&md_ctx, key, keylen) != 0) {
294                mbedtls_fprintf(stderr,
295                                "mbedtls_md_update() returned error\n");
296                goto exit;
297            }
298            if (mbedtls_md_finish(&md_ctx, digest) != 0) {
299                mbedtls_fprintf(stderr,
300                                "mbedtls_md_finish() returned error\n");
301                goto exit;
302            }
303
304        }
305
306        if (mbedtls_cipher_setkey(&cipher_ctx,
307                                  digest,
308                                  (int) mbedtls_cipher_info_get_key_bitlen(cipher_info),
309                                  MBEDTLS_ENCRYPT) != 0) {
310            mbedtls_fprintf(stderr, "mbedtls_cipher_setkey() returned error\n");
311            goto exit;
312        }
313        if (mbedtls_cipher_set_iv(&cipher_ctx, IV, 16) != 0) {
314            mbedtls_fprintf(stderr, "mbedtls_cipher_set_iv() returned error\n");
315            goto exit;
316        }
317        if (mbedtls_cipher_reset(&cipher_ctx) != 0) {
318            mbedtls_fprintf(stderr, "mbedtls_cipher_reset() returned error\n");
319            goto exit;
320        }
321
322        if (mbedtls_md_hmac_starts(&md_ctx, digest, 32) != 0) {
323            mbedtls_fprintf(stderr, "mbedtls_md_hmac_starts() returned error\n");
324            goto exit;
325        }
326
327        /*
328         * Encrypt and write the ciphertext.
329         */
330        for (offset = 0; offset < filesize; offset += cipher_block_size) {
331            ilen = ((unsigned int) filesize - offset > cipher_block_size) ?
332                   cipher_block_size : (unsigned int) (filesize - offset);
333
334            if (fread(buffer, 1, ilen, fin) != ilen) {
335                mbedtls_fprintf(stderr, "fread(%ld bytes) failed\n", (long) ilen);
336                goto exit;
337            }
338
339            if (mbedtls_cipher_update(&cipher_ctx, buffer, ilen, output, &olen) != 0) {
340                mbedtls_fprintf(stderr, "mbedtls_cipher_update() returned error\n");
341                goto exit;
342            }
343
344            if (mbedtls_md_hmac_update(&md_ctx, output, olen) != 0) {
345                mbedtls_fprintf(stderr, "mbedtls_md_hmac_update() returned error\n");
346                goto exit;
347            }
348
349            if (fwrite(output, 1, olen, fout) != olen) {
350                mbedtls_fprintf(stderr, "fwrite(%ld bytes) failed\n", (long) olen);
351                goto exit;
352            }
353        }
354
355        if (mbedtls_cipher_finish(&cipher_ctx, output, &olen) != 0) {
356            mbedtls_fprintf(stderr, "mbedtls_cipher_finish() returned error\n");
357            goto exit;
358        }
359        if (mbedtls_md_hmac_update(&md_ctx, output, olen) != 0) {
360            mbedtls_fprintf(stderr, "mbedtls_md_hmac_update() returned error\n");
361            goto exit;
362        }
363
364        if (fwrite(output, 1, olen, fout) != olen) {
365            mbedtls_fprintf(stderr, "fwrite(%ld bytes) failed\n", (long) olen);
366            goto exit;
367        }
368
369        /*
370         * Finally write the HMAC.
371         */
372        if (mbedtls_md_hmac_finish(&md_ctx, digest) != 0) {
373            mbedtls_fprintf(stderr, "mbedtls_md_hmac_finish() returned error\n");
374            goto exit;
375        }
376
377        if (fwrite(digest, 1, md_size, fout) != md_size) {
378            mbedtls_fprintf(stderr, "fwrite(%d bytes) failed\n", md_size);
379            goto exit;
380        }
381    }
382
383    if (mode == MODE_DECRYPT) {
384        /*
385         *  The encrypted file must be structured as follows:
386         *
387         *        00 .. 15              Initialization Vector
388         *        16 .. 31              Encrypted Block #1
389         *           ..
390         *      N*16 .. (N+1)*16 - 1    Encrypted Block #N
391         *  (N+1)*16 .. (N+1)*16 + n    Hash(ciphertext)
392         */
393        if (filesize < 16 + md_size) {
394            mbedtls_fprintf(stderr, "File too short to be encrypted.\n");
395            goto exit;
396        }
397
398        if (cipher_block_size == 0) {
399            mbedtls_fprintf(stderr, "Invalid cipher block size: 0. \n");
400            goto exit;
401        }
402
403        /*
404         * Check the file size.
405         */
406        cipher_mode = mbedtls_cipher_info_get_mode(cipher_info);
407        if (cipher_mode != MBEDTLS_MODE_GCM &&
408            cipher_mode != MBEDTLS_MODE_CTR &&
409            cipher_mode != MBEDTLS_MODE_CFB &&
410            cipher_mode != MBEDTLS_MODE_OFB &&
411            ((filesize - md_size) % cipher_block_size) != 0) {
412            mbedtls_fprintf(stderr, "File content not a multiple of the block size (%u).\n",
413                            cipher_block_size);
414            goto exit;
415        }
416
417        /*
418         * Subtract the IV + HMAC length.
419         */
420        filesize -= (16 + md_size);
421
422        /*
423         * Read the IV and original filesize modulo 16.
424         */
425        if (fread(buffer, 1, 16, fin) != 16) {
426            mbedtls_fprintf(stderr, "fread(%d bytes) failed\n", 16);
427            goto exit;
428        }
429
430        memcpy(IV, buffer, 16);
431
432        /*
433         * Hash the IV and the secret key together 8192 times
434         * using the result to setup the AES context and HMAC.
435         */
436        memset(digest, 0,  32);
437        memcpy(digest, IV, 16);
438
439        for (i = 0; i < 8192; i++) {
440            if (mbedtls_md_starts(&md_ctx) != 0) {
441                mbedtls_fprintf(stderr, "mbedtls_md_starts() returned error\n");
442                goto exit;
443            }
444            if (mbedtls_md_update(&md_ctx, digest, 32) != 0) {
445                mbedtls_fprintf(stderr, "mbedtls_md_update() returned error\n");
446                goto exit;
447            }
448            if (mbedtls_md_update(&md_ctx, key, keylen) != 0) {
449                mbedtls_fprintf(stderr, "mbedtls_md_update() returned error\n");
450                goto exit;
451            }
452            if (mbedtls_md_finish(&md_ctx, digest) != 0) {
453                mbedtls_fprintf(stderr, "mbedtls_md_finish() returned error\n");
454                goto exit;
455            }
456        }
457
458        if (mbedtls_cipher_setkey(&cipher_ctx,
459                                  digest,
460                                  (int) mbedtls_cipher_info_get_key_bitlen(cipher_info),
461                                  MBEDTLS_DECRYPT) != 0) {
462            mbedtls_fprintf(stderr, "mbedtls_cipher_setkey() returned error\n");
463            goto exit;
464        }
465
466        if (mbedtls_cipher_set_iv(&cipher_ctx, IV, 16) != 0) {
467            mbedtls_fprintf(stderr, "mbedtls_cipher_set_iv() returned error\n");
468            goto exit;
469        }
470
471        if (mbedtls_cipher_reset(&cipher_ctx) != 0) {
472            mbedtls_fprintf(stderr, "mbedtls_cipher_reset() returned error\n");
473            goto exit;
474        }
475
476        if (mbedtls_md_hmac_starts(&md_ctx, digest, 32) != 0) {
477            mbedtls_fprintf(stderr, "mbedtls_md_hmac_starts() returned error\n");
478            goto exit;
479        }
480
481        /*
482         * Decrypt and write the plaintext.
483         */
484        for (offset = 0; offset < filesize; offset += cipher_block_size) {
485            ilen = ((unsigned int) filesize - offset > cipher_block_size) ?
486                   cipher_block_size : (unsigned int) (filesize - offset);
487
488            if (fread(buffer, 1, ilen, fin) != ilen) {
489                mbedtls_fprintf(stderr, "fread(%u bytes) failed\n",
490                                cipher_block_size);
491                goto exit;
492            }
493
494            if (mbedtls_md_hmac_update(&md_ctx, buffer, ilen) != 0) {
495                mbedtls_fprintf(stderr, "mbedtls_md_hmac_update() returned error\n");
496                goto exit;
497            }
498            if (mbedtls_cipher_update(&cipher_ctx, buffer, ilen, output,
499                                      &olen) != 0) {
500                mbedtls_fprintf(stderr, "mbedtls_cipher_update() returned error\n");
501                goto exit;
502            }
503
504            if (fwrite(output, 1, olen, fout) != olen) {
505                mbedtls_fprintf(stderr, "fwrite(%ld bytes) failed\n", (long) olen);
506                goto exit;
507            }
508        }
509
510        /*
511         * Verify the message authentication code.
512         */
513        if (mbedtls_md_hmac_finish(&md_ctx, digest) != 0) {
514            mbedtls_fprintf(stderr, "mbedtls_md_hmac_finish() returned error\n");
515            goto exit;
516        }
517
518        if (fread(buffer, 1, md_size, fin) != md_size) {
519            mbedtls_fprintf(stderr, "fread(%d bytes) failed\n", md_size);
520            goto exit;
521        }
522
523        /* Use constant-time buffer comparison */
524        diff = 0;
525        for (i = 0; i < md_size; i++) {
526            diff |= digest[i] ^ buffer[i];
527        }
528
529        if (diff != 0) {
530            mbedtls_fprintf(stderr, "HMAC check failed: wrong key, "
531                                    "or file corrupted.\n");
532            goto exit;
533        }
534
535        /*
536         * Write the final block of data
537         */
538        if (mbedtls_cipher_finish(&cipher_ctx, output, &olen) != 0) {
539            mbedtls_fprintf(stderr, "mbedtls_cipher_finish() returned error\n");
540            goto exit;
541        }
542
543        if (fwrite(output, 1, olen, fout) != olen) {
544            mbedtls_fprintf(stderr, "fwrite(%ld bytes) failed\n", (long) olen);
545            goto exit;
546        }
547    }
548
549    exit_code = MBEDTLS_EXIT_SUCCESS;
550
551exit:
552    if (fin) {
553        fclose(fin);
554    }
555    if (fout) {
556        fclose(fout);
557    }
558
559    /* Zeroize all command line arguments to also cover
560       the case when the user has missed or reordered some,
561       in which case the key might not be in argv[6]. */
562    for (i = 0; i < argc; i++) {
563        mbedtls_platform_zeroize(argv[i], strlen(argv[i]));
564    }
565
566    mbedtls_platform_zeroize(IV,     sizeof(IV));
567    mbedtls_platform_zeroize(key,    sizeof(key));
568    mbedtls_platform_zeroize(buffer, sizeof(buffer));
569    mbedtls_platform_zeroize(output, sizeof(output));
570    mbedtls_platform_zeroize(digest, sizeof(digest));
571
572    mbedtls_cipher_free(&cipher_ctx);
573    mbedtls_md_free(&md_ctx);
574
575    mbedtls_exit(exit_code);
576}
577#endif /* MBEDTLS_CIPHER_C && MBEDTLS_MD_C && MBEDTLS_FS_IO */
578