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