1 /*
2  *  AES-256 file encryption program
3  *
4  *  Copyright The Mbed TLS Contributors
5  *  SPDX-License-Identifier: Apache-2.0
6  *
7  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
8  *  not use this file except in compliance with the License.
9  *  You may obtain a copy of the License at
10  *
11  *  http://www.apache.org/licenses/LICENSE-2.0
12  *
13  *  Unless required by applicable law or agreed to in writing, software
14  *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15  *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  *  See the License for the specific language governing permissions and
17  *  limitations under the License.
18  */
19 
20 /* Enable definition of fileno() even when compiling with -std=c99. Must be
21  * set before config.h, which pulls in glibc's features.h indirectly.
22  * Harmless on other platforms. */
23 #define _POSIX_C_SOURCE 200112L
24 
25 #if !defined(MBEDTLS_CONFIG_FILE)
26 #include "mbedtls/config.h"
27 #else
28 #include MBEDTLS_CONFIG_FILE
29 #endif
30 
31 #if defined(MBEDTLS_PLATFORM_C)
32 #include "mbedtls/platform.h"
33 #else
34 #include <stdio.h>
35 #include <stdlib.h>
36 #define mbedtls_fprintf         fprintf
37 #define mbedtls_printf          printf
38 #define mbedtls_exit            exit
39 #define MBEDTLS_EXIT_SUCCESS    EXIT_SUCCESS
40 #define MBEDTLS_EXIT_FAILURE    EXIT_FAILURE
41 #endif /* MBEDTLS_PLATFORM_C */
42 
43 #include "mbedtls/aes.h"
44 #include "mbedtls/md.h"
45 #include "mbedtls/platform_util.h"
46 
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <string.h>
50 
51 #if defined(_WIN32)
52 #include <windows.h>
53 #if !defined(_WIN32_WCE)
54 #include <io.h>
55 #endif
56 #else
57 #include <sys/types.h>
58 #include <unistd.h>
59 #endif
60 
61 #define MODE_ENCRYPT    0
62 #define MODE_DECRYPT    1
63 
64 #define USAGE   \
65     "\n  aescrypt2 <mode> <input filename> <output filename> <key>\n" \
66     "\n   <mode>: 0 = encrypt, 1 = decrypt\n" \
67     "\n  example: aescrypt2 0 file file.aes hex:E76B2413958B00E193\n" \
68     "\n"
69 
70 #if !defined(MBEDTLS_AES_C) || !defined(MBEDTLS_SHA256_C) || \
71     !defined(MBEDTLS_FS_IO) || !defined(MBEDTLS_MD_C)
main(void)72 int main( void )
73 {
74     mbedtls_printf("MBEDTLS_AES_C and/or MBEDTLS_SHA256_C "
75                     "and/or MBEDTLS_FS_IO and/or MBEDTLS_MD_C "
76                     "not defined.\n");
77     mbedtls_exit( 0 );
78 }
79 #else
80 
81 
main(int argc,char * argv[])82 int main( int argc, char *argv[] )
83 {
84     int ret = 0;
85     int exit_code = MBEDTLS_EXIT_FAILURE;
86 
87     unsigned int i, n;
88     int mode, lastn;
89     size_t keylen;
90     FILE *fkey, *fin = NULL, *fout = NULL;
91 
92     char *p;
93 
94     unsigned char IV[16];
95     unsigned char tmp[16];
96     unsigned char key[512];
97     unsigned char digest[64];
98     unsigned char buffer[1024];
99     unsigned char diff;
100 
101     mbedtls_aes_context aes_ctx;
102     mbedtls_md_context_t sha_ctx;
103 
104 #if defined(_WIN32_WCE)
105     long filesize, offset;
106 #elif defined(_WIN32)
107        LARGE_INTEGER li_size;
108     __int64 filesize, offset;
109 #else
110       off_t filesize, offset;
111 #endif
112 
113     mbedtls_aes_init( &aes_ctx );
114     mbedtls_md_init( &sha_ctx );
115 
116     ret = mbedtls_md_setup( &sha_ctx, mbedtls_md_info_from_type( MBEDTLS_MD_SHA256 ), 1 );
117     if( ret != 0 )
118     {
119         mbedtls_printf( "  ! mbedtls_md_setup() returned -0x%04x\n", (unsigned int) -ret );
120         goto exit;
121     }
122 
123     /*
124      * Parse the command-line arguments.
125      */
126     if( argc != 5 )
127     {
128         mbedtls_printf( USAGE );
129 
130 #if defined(_WIN32)
131         mbedtls_printf( "\n  Press Enter to exit this program.\n" );
132         fflush( stdout ); getchar();
133 #endif
134 
135         goto exit;
136     }
137 
138     mode = atoi( argv[1] );
139     memset( IV,     0, sizeof( IV ) );
140     memset( key,    0, sizeof( key ) );
141     memset( digest, 0, sizeof( digest ) );
142     memset( buffer, 0, sizeof( buffer ) );
143 
144     if( mode != MODE_ENCRYPT && mode != MODE_DECRYPT )
145     {
146         mbedtls_fprintf( stderr, "invalide operation mode\n" );
147         goto exit;
148     }
149 
150     if( strcmp( argv[2], argv[3] ) == 0 )
151     {
152         mbedtls_fprintf( stderr, "input and output filenames must differ\n" );
153         goto exit;
154     }
155 
156     if( ( fin = fopen( argv[2], "rb" ) ) == NULL )
157     {
158         mbedtls_fprintf( stderr, "fopen(%s,rb) failed\n", argv[2] );
159         goto exit;
160     }
161 
162     if( ( fout = fopen( argv[3], "wb+" ) ) == NULL )
163     {
164         mbedtls_fprintf( stderr, "fopen(%s,wb+) failed\n", argv[3] );
165         goto exit;
166     }
167 
168     /*
169      * Read the secret key from file or command line
170      */
171     if( ( fkey = fopen( argv[4], "rb" ) ) != NULL )
172     {
173         keylen = fread( key, 1, sizeof( key ), fkey );
174         fclose( fkey );
175     }
176     else
177     {
178         if( memcmp( argv[4], "hex:", 4 ) == 0 )
179         {
180             p = &argv[4][4];
181             keylen = 0;
182 
183             while( sscanf( p, "%02X", &n ) > 0 &&
184                    keylen < (int) sizeof( key ) )
185             {
186                 key[keylen++] = (unsigned char) n;
187                 p += 2;
188             }
189         }
190         else
191         {
192             keylen = strlen( argv[4] );
193 
194             if( keylen > (int) sizeof( key ) )
195                 keylen = (int) sizeof( key );
196 
197             memcpy( key, argv[4], keylen );
198         }
199     }
200 
201 #if defined(_WIN32_WCE)
202     filesize = fseek( fin, 0L, SEEK_END );
203 #else
204 #if defined(_WIN32)
205     /*
206      * Support large files (> 2Gb) on Win32
207      */
208     li_size.QuadPart = 0;
209     li_size.LowPart  =
210         SetFilePointer( (HANDLE) _get_osfhandle( _fileno( fin ) ),
211                         li_size.LowPart, &li_size.HighPart, FILE_END );
212 
213     if( li_size.LowPart == 0xFFFFFFFF && GetLastError() != NO_ERROR )
214     {
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     {
223         perror( "lseek" );
224         goto exit;
225     }
226 #endif
227 #endif
228 
229     if( fseek( fin, 0, SEEK_SET ) < 0 )
230     {
231         mbedtls_fprintf( stderr, "fseek(0,SEEK_SET) failed\n" );
232         goto exit;
233     }
234 
235     if( mode == MODE_ENCRYPT )
236     {
237         /*
238          * Generate the initialization vector as:
239          * IV = SHA-256( filesize || filename )[0..15]
240          */
241         for( i = 0; i < 8; i++ )
242             buffer[i] = (unsigned char)( filesize >> ( i << 3 ) );
243 
244         p = argv[2];
245 
246         mbedtls_md_starts( &sha_ctx );
247         mbedtls_md_update( &sha_ctx, buffer, 8 );
248         mbedtls_md_update( &sha_ctx, (unsigned char *) p, strlen( p ) );
249         mbedtls_md_finish( &sha_ctx, digest );
250 
251         memcpy( IV, digest, 16 );
252 
253         /*
254          * The last four bits in the IV are actually used
255          * to store the file size modulo the AES block size.
256          */
257         lastn = (int)( filesize & 0x0F );
258 
259         IV[15] = (unsigned char)
260             ( ( IV[15] & 0xF0 ) | lastn );
261 
262         /*
263          * Append the IV at the beginning of the output.
264          */
265         if( fwrite( IV, 1, 16, fout ) != 16 )
266         {
267             mbedtls_fprintf( stderr, "fwrite(%d bytes) failed\n", 16 );
268             goto exit;
269         }
270 
271         /*
272          * Hash the IV and the secret key together 8192 times
273          * using the result to setup the AES context and HMAC.
274          */
275         memset( digest, 0,  32 );
276         memcpy( digest, IV, 16 );
277 
278         for( i = 0; i < 8192; i++ )
279         {
280             mbedtls_md_starts( &sha_ctx );
281             mbedtls_md_update( &sha_ctx, digest, 32 );
282             mbedtls_md_update( &sha_ctx, key, keylen );
283             mbedtls_md_finish( &sha_ctx, digest );
284         }
285 
286         mbedtls_aes_setkey_enc( &aes_ctx, digest, 256 );
287         mbedtls_md_hmac_starts( &sha_ctx, digest, 32 );
288 
289         /*
290          * Encrypt and write the ciphertext.
291          */
292         for( offset = 0; offset < filesize; offset += 16 )
293         {
294             n = ( filesize - offset > 16 ) ? 16 : (int)
295                 ( filesize - offset );
296 
297             if( fread( buffer, 1, n, fin ) != (size_t) n )
298             {
299                 mbedtls_fprintf( stderr, "fread(%u bytes) failed\n", n );
300                 goto exit;
301             }
302 
303             for( i = 0; i < 16; i++ )
304                 buffer[i] = (unsigned char)( buffer[i] ^ IV[i] );
305 
306             mbedtls_aes_crypt_ecb( &aes_ctx, MBEDTLS_AES_ENCRYPT, buffer, buffer );
307             mbedtls_md_hmac_update( &sha_ctx, buffer, 16 );
308 
309             if( fwrite( buffer, 1, 16, fout ) != 16 )
310             {
311                 mbedtls_fprintf( stderr, "fwrite(%d bytes) failed\n", 16 );
312                 goto exit;
313             }
314 
315             memcpy( IV, buffer, 16 );
316         }
317 
318         /*
319          * Finally write the HMAC.
320          */
321         mbedtls_md_hmac_finish( &sha_ctx, digest );
322 
323         if( fwrite( digest, 1, 32, fout ) != 32 )
324         {
325             mbedtls_fprintf( stderr, "fwrite(%d bytes) failed\n", 16 );
326             goto exit;
327         }
328     }
329 
330     if( mode == MODE_DECRYPT )
331     {
332         /*
333          *  The encrypted file must be structured as follows:
334          *
335          *        00 .. 15              Initialization Vector
336          *        16 .. 31              AES Encrypted Block #1
337          *           ..
338          *      N*16 .. (N+1)*16 - 1    AES Encrypted Block #N
339          *  (N+1)*16 .. (N+1)*16 + 32   HMAC-SHA-256(ciphertext)
340          */
341         if( filesize < 48 )
342         {
343             mbedtls_fprintf( stderr, "File too short to be encrypted.\n" );
344             goto exit;
345         }
346 
347         if( ( filesize & 0x0F ) != 0 )
348         {
349             mbedtls_fprintf( stderr, "File size not a multiple of 16.\n" );
350             goto exit;
351         }
352 
353         /*
354          * Subtract the IV + HMAC length.
355          */
356         filesize -= ( 16 + 32 );
357 
358         /*
359          * Read the IV and original filesize modulo 16.
360          */
361         if( fread( buffer, 1, 16, fin ) != 16 )
362         {
363             mbedtls_fprintf( stderr, "fread(%d bytes) failed\n", 16 );
364             goto exit;
365         }
366 
367         memcpy( IV, buffer, 16 );
368         lastn = IV[15] & 0x0F;
369 
370         /*
371          * Hash the IV and the secret key together 8192 times
372          * using the result to setup the AES context and HMAC.
373          */
374         memset( digest, 0,  32 );
375         memcpy( digest, IV, 16 );
376 
377         for( i = 0; i < 8192; i++ )
378         {
379             mbedtls_md_starts( &sha_ctx );
380             mbedtls_md_update( &sha_ctx, digest, 32 );
381             mbedtls_md_update( &sha_ctx, key, keylen );
382             mbedtls_md_finish( &sha_ctx, digest );
383         }
384 
385         mbedtls_aes_setkey_dec( &aes_ctx, digest, 256 );
386         mbedtls_md_hmac_starts( &sha_ctx, digest, 32 );
387 
388         /*
389          * Decrypt and write the plaintext.
390          */
391         for( offset = 0; offset < filesize; offset += 16 )
392         {
393             if( fread( buffer, 1, 16, fin ) != 16 )
394             {
395                 mbedtls_fprintf( stderr, "fread(%d bytes) failed\n", 16 );
396                 goto exit;
397             }
398 
399             memcpy( tmp, buffer, 16 );
400 
401             mbedtls_md_hmac_update( &sha_ctx, buffer, 16 );
402             mbedtls_aes_crypt_ecb( &aes_ctx, MBEDTLS_AES_DECRYPT, buffer, buffer );
403 
404             for( i = 0; i < 16; i++ )
405                 buffer[i] = (unsigned char)( buffer[i] ^ IV[i] );
406 
407             memcpy( IV, tmp, 16 );
408 
409             n = ( lastn > 0 && offset == filesize - 16 )
410                 ? lastn : 16;
411 
412             if( fwrite( buffer, 1, n, fout ) != (size_t) n )
413             {
414                 mbedtls_fprintf( stderr, "fwrite(%u bytes) failed\n", n );
415                 goto exit;
416             }
417         }
418 
419         /*
420          * Verify the message authentication code.
421          */
422         mbedtls_md_hmac_finish( &sha_ctx, digest );
423 
424         if( fread( buffer, 1, 32, fin ) != 32 )
425         {
426             mbedtls_fprintf( stderr, "fread(%d bytes) failed\n", 32 );
427             goto exit;
428         }
429 
430         /* Use constant-time buffer comparison */
431         diff = 0;
432         for( i = 0; i < 32; i++ )
433             diff |= digest[i] ^ buffer[i];
434 
435         if( diff != 0 )
436         {
437             mbedtls_fprintf( stderr, "HMAC check failed: wrong key, "
438                              "or file corrupted.\n" );
439             goto exit;
440         }
441     }
442 
443     exit_code = MBEDTLS_EXIT_SUCCESS;
444 
445 exit:
446     if( fin )
447         fclose( fin );
448     if( fout )
449         fclose( fout );
450 
451     /* Zeroize all command line arguments to also cover
452        the case when the user has missed or reordered some,
453        in which case the key might not be in argv[4]. */
454     for( i = 0; i < (unsigned int) argc; i++ )
455         mbedtls_platform_zeroize( argv[i], strlen( argv[i] ) );
456 
457     mbedtls_platform_zeroize( IV,     sizeof( IV ) );
458     mbedtls_platform_zeroize( key,    sizeof( key ) );
459     mbedtls_platform_zeroize( tmp,    sizeof( tmp ) );
460     mbedtls_platform_zeroize( buffer, sizeof( buffer ) );
461     mbedtls_platform_zeroize( digest, sizeof( digest ) );
462 
463     mbedtls_aes_free( &aes_ctx );
464     mbedtls_md_free( &sha_ctx );
465 
466     mbedtls_exit( exit_code );
467 }
468 #endif /* MBEDTLS_AES_C && MBEDTLS_SHA256_C && MBEDTLS_FS_IO */
469