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