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