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