1 /******************************************************************************/
2 /* SlunkCrypt, by LoRd_MuldeR <MuldeR2@GMX.de> */
3 /* This work has been released under the CC0 1.0 Universal license! */
4 /******************************************************************************/
6 #define _CRT_SECURE_NO_WARNINGS 1
8 #include <slunkcrypt.h>
18 #define BUFFER_SIZE 4096U
20 #define OP_MODE_NONE 0
21 #define OP_MODE_HELP 1
22 #define OP_MODE_VERS 2
23 #define OP_MODE_ENCR 3
24 #define OP_MODE_DECR 4
25 #define OP_MODE_TEST 5
27 static const CHR *const ENVV_PASSWD_NAME = T("SLUNK_PASSPHRASE");
29 // ==========================================================================
30 // Auxiliary functions
31 // ==========================================================================
33 static int parse_mode(const CHR* const command)
35 if ((!STRICMP(command, T("-h"))) || (!STRICMP(command, T("/?"))) || (!STRICMP(command, T("--help"))))
39 else if ((!STRICMP(command, T("-v"))) || (!STRICMP(command, T("--version"))))
43 else if ((!STRICMP(command, T("-e"))) || (!STRICMP(command, T("--encrypt"))))
47 else if ((!STRICMP(command, T("-d"))) || (!STRICMP(command, T("--decrypt"))))
51 else if ((!STRICMP(command, T("-t"))) || (!STRICMP(command, T("--self-test"))))
57 FPRINTF(stderr, T("Error: The specified command \"%") T(PRISTR) T("\" is unknown!\n\n"), command);
62 static void print_manpage(const CHR *const program)
64 FPUTS(T("====================================================================\n"), stderr);
65 FPUTS(T("This software has been released under the CC0 1.0 Universal license:\n"), stderr);
66 FPUTS(T("https://creativecommons.org/publicdomain/zero/1.0/legalcode\n"), stderr);
67 FPUTS(T("====================================================================\n\n"), stderr);
68 FPUTS(T("Synopsis:\n"), stderr);
69 FPRINTF(stderr, T(" %") T(PRISTR) T(" --encrypt [[@][:]<passphrase>] <input.txt> <output.enc>\n"), program);
70 FPRINTF(stderr, T(" %") T(PRISTR) T(" --decrypt [[@][:]<passphrase>] <input.enc> <output.txt>\n\n"), program);
71 FPUTS(T("Options:\n"), stderr);
72 FPUTS(T("- If <passphrase> is prefixed with a '@' character, then it specifies the file\n"), stderr);
73 FPUTS(T(" to read the passphrase from; only the first line in that file is used!\n"), stderr);
74 FPUTS(T("- If <passphrase> is prefixed with a ':' character, then the leading character\n"), stderr);
75 FPUTS(T(" is skipped and the remainder of the argument is used as passphrase.\n"), stderr);
76 FPUTS(T("- If argument <passphrase> is omitted, then the passphrase is read from the\n"), stderr);
77 FPRINTF(stderr, T(" environment variable \"%") T(PRISTR) T("\" instead.\n"), ENVV_PASSWD_NAME);
78 FPUTS(T("- Specify \"@-\" in order to read the passphrase from the standard input stream!\n\n"), stderr);
81 static char* read_passphrase(const CHR* const file_name)
83 const size_t max_len = SLUNKCRYPT_PWDLEN_MAX + 3U;
84 char *buffer = (char*) malloc(max_len * sizeof(char));
90 const int use_stdin = (STRICMP(file_name, T("-")) == 0);
91 FILE *const file = use_stdin ? stdin : FOPEN(file_name, T("rb"));
100 if (!fgets(buffer, (int)max_len, file))
106 size_t length = strlen(buffer);
107 while ((length > 0U) && ((buffer[length - 1U] == '\r') || (buffer[length - 1U] == '\n')))
109 buffer[--length] = '\0';
116 if ((!use_stdin) && file)
124 static int weak_passphrase(const char *str)
126 int flags[4U] = { 0, 0, 0, 0 };
129 const CHR c = *str++;
132 flags[isupper(c) ? 0U : 1U] = 1;
136 flags[isdigit(c) ? 2U : 3U] = 1;
139 const int strong = flags[0U] && flags[1U] && flags[2U] && flags[3U];
143 static int open_files(FILE **const file_in, FILE **const file_out, const CHR* const input_path, const CHR* const output_path)
145 *file_in = FOPEN(input_path, T("rb"));
148 FPUTS(T("Error: Failed to open input file for reading!\n\n"), stderr);
152 *file_out = FOPEN(output_path, T("wb"));
155 FPUTS(T("Error: Failed to open output file for writing!\n\n"), stderr);
163 static void sigint_handler(const int sig)
167 g_slunkcrypt_abort_flag = 1;
168 signal(SIGINT, sigint_handler);
172 // ==========================================================================
174 // ==========================================================================
176 static int encrypt(const char* const passphrase, const CHR* const input_path, const CHR* const output_path)
178 slunkcrypt_t ctx = SLUNKCRYPT_NULL;
179 FILE * file_in = NULL, * file_out = NULL;
182 if (open_files(&file_in, &file_out, input_path, output_path) != 0)
187 const uint64_t file_size = get_file_size(file_in);
188 if (file_size == UINT64_MAX)
190 FPUTS(T("I/O error: Failed to determine size of input file!\n\n"), stderr);
193 else if (file_size < 1U)
195 FPUTS(T("Error: Input file is empty or an unsupported type!\n\n"), stderr);
199 FPUTS(T("Encrypting file contents, please be patient... "), stderr);
203 if (slunkcrypt_generate_seed(&seed) != SLUNKCRYPT_SUCCESS)
205 FPUTS(T("\n\nSlunkCrypt error: Failed to generate seed!\n\n"), stderr);
209 if (fwrite(&seed, sizeof(uint64_t), 1U, file_out) < 1U)
211 FPUTS(T("\n\nI/O error: Failed to write seed value!\n\n"), stderr);
215 ctx = slunkcrypt_alloc(seed, (const uint8_t*)passphrase, strlen(passphrase));
218 FPUTS(g_slunkcrypt_abort_flag ? T("\n\nProcess interrupted!\n\n") : T("\n\nSlunkCrypt error: Failed to initialize encryption!\n\n"), stderr);
222 clock_t clk_now, clk_update = clock();
223 uint64_t crc_actual = CRC_INITIALIZER, bytes_read = 0U;
224 uint8_t buffer[BUFFER_SIZE];
226 FPRINTF(stderr, T("%5.1f%% "), 0.0);
229 while (bytes_read < file_size)
231 const uint64_t bytes_remaining = file_size - bytes_read;
232 const size_t request_len = (bytes_remaining < BUFFER_SIZE) ? ((size_t)bytes_remaining) : BUFFER_SIZE;
233 const size_t count = fread(buffer, sizeof(uint8_t), request_len, file_in);
236 crc_actual = crc64_update(crc_actual, buffer, count);
238 const int status = slunkcrypt_encrypt_inplace(ctx, buffer, count);
239 if (status != SLUNKCRYPT_SUCCESS)
241 FPUTS((status == SLUNKCRYPT_ABORTED) ? T("\n\nProcess interrupted!\n\n") : T("\n\nSlunkCrypt error: Failed to encrypt data!\n\n"), stderr);
244 if (fwrite(buffer, sizeof(uint8_t), count, file_out) < count)
246 FPUTS(T("\n\nI/O error: Failed to write encrypted data!\n\n"), stderr);
250 if (count < request_len)
254 if ((clk_now = clock()) - clk_update > CLOCKS_PER_SEC)
256 FPRINTF(stderr, T("\b\b\b\b\b\b\b%5.1f%% "), (bytes_read / ((double)file_size)) * 100.0);
258 clk_update = clk_now;
264 FPUTS(T("\n\nI/O error: Failed to read input data!\n\n"), stderr);
268 if (bytes_read < file_size)
270 FPUTS(T("\n\nI/O error: Input file could not be fully read!\n\n"), stderr);
274 crc_actual = crc64_finish(crc_actual);
275 FPRINTF(stderr, T("\b\b\b\b\b\b\b%5.1f%%\n\n"), 100.0);
278 if (fwrite(&crc_actual, sizeof(uint64_t), 1U, file_out) < 1U)
280 FPUTS(T("I/O error: Failed to write CRC checksum!\n\n"), stderr);
286 FPUTS(T("All is done.\n\n"), stderr);
293 slunkcrypt_free(ctx);
309 // ==========================================================================
311 // ==========================================================================
313 static int decrypt(const char* const passphrase, const CHR* const input_path, const CHR* const output_path)
315 slunkcrypt_t ctx = SLUNKCRYPT_NULL;
316 FILE *file_in = NULL, *file_out = NULL;
319 if (open_files(&file_in, &file_out, input_path, output_path) != 0)
324 const uint64_t file_size = get_file_size(file_in);
325 if (file_size == UINT64_MAX)
327 FPUTS(T("I/O error: Failed to determine size of input file!\n\n"), stderr);
330 else if (file_size < 16U)
332 FPUTS(T("Error: Input file is too small! Truncated?\n\n"), stderr);
336 FPUTS(T("Decrypting file contents, please be patient... "), stderr);
340 if (fread(&seed, sizeof(uint64_t), 1U, file_in) < 1U)
342 FPUTS(T("\n\nI/O error: Failed to read seed value!\n\n"), stderr);
346 ctx = slunkcrypt_alloc(seed, (const uint8_t*)passphrase, strlen(passphrase));
349 FPUTS(g_slunkcrypt_abort_flag ? T("\n\nProcess interrupted!\n\n") : T("\n\nSlunkCrypt error: Failed to initialize decryption!\n\n"), stderr);
353 clock_t clk_now, clk_update = clock();
354 uint64_t crc_actual = CRC_INITIALIZER, bytes_read = sizeof(uint64_t);
355 uint8_t buffer[BUFFER_SIZE];
356 const uint64_t read_limit = file_size - sizeof(uint64_t);
358 FPRINTF(stderr, T("%5.1f%% "), 0.0);
361 while (bytes_read < read_limit)
363 const uint64_t bytes_remaining = read_limit - bytes_read;
364 const size_t request_len = (bytes_remaining < BUFFER_SIZE) ? ((size_t)bytes_remaining) : BUFFER_SIZE;
365 const size_t count = fread(buffer, sizeof(uint8_t), request_len, file_in);
369 const int status = slunkcrypt_decrypt_inplace(ctx, buffer, count);
370 if (status != SLUNKCRYPT_SUCCESS)
372 FPUTS((status == SLUNKCRYPT_ABORTED) ? T("\n\nProcess interrupted!\n\n") : T("\n\nSlunkCrypt error: Failed to decrypt data!\n\n"), stderr);
375 crc_actual = crc64_update(crc_actual, buffer, count);
376 if (fwrite(buffer, sizeof(uint8_t), count, file_out) < count)
378 FPUTS(T("failed!\n\nI/O error: Failed to write decrypted data!\n\n"), stderr);
382 if (count < request_len)
386 if ((clk_now = clock()) - clk_update > CLOCKS_PER_SEC)
388 FPRINTF(stderr, T("\b\b\b\b\b\b\b%5.1f%% "), (bytes_read / ((double)read_limit)) * 100.0);
390 clk_update = clk_now;
396 FPUTS(T("\n\nI/O error: Failed to read input data!\n\n"), stderr);
400 if (bytes_read < read_limit)
402 FPUTS(T("\n\nI/O error: Input file could not be fully read!\n\n"), stderr);
406 crc_actual = crc64_finish(crc_actual);
407 FPRINTF(stderr, T("\b\b\b\b\b\b\b%5.1f%%\n\n"), 100.0);
410 uint64_t crc_expected;
411 if (fread(&crc_expected, sizeof(uint64_t), 1U, file_in) < 1U)
413 FPUTS(T("I/O error: Failed to read CRC checksum!\n\n"), stderr);
417 if (crc_actual != crc_expected)
419 FPRINTF(stderr, T("CRC error: Checksum mismatch detected! [expected: 0x%016") T(PRIX64) T(", actual: 0x%016") T(PRIX64) T("]\n\n"), crc_actual, crc_expected);
420 FPUTS(T("Wrong passphrase or corrupted file?\n\n"), stderr);
426 FPUTS(T("CRC checksum is correct.\n\n"), stderr);
433 slunkcrypt_free(ctx);
449 // ==========================================================================
451 // ==========================================================================
453 static int run_test_case(const char *const message)
455 static const char* const passphrase = "OrpheanBeh0lderScry!Doubt";
457 const size_t length = strlen(message) + 1U;
458 int status, result = 1;
459 slunkcrypt_t ctx = SLUNKCRYPT_NULL;
462 if (slunkcrypt_generate_seed(&seed) != SLUNKCRYPT_SUCCESS)
464 FPUTS(T("\n\nWhoops: Failed to generate seed!\n\n"), stderr);
468 char* const text_temp = strdup(message);
471 FPUTS(T("\n\nWhoops: Failed to allocate text buffer!\n\n"), stderr);
475 ctx = slunkcrypt_alloc(seed, (const uint8_t*)passphrase, strlen(passphrase));
478 FPUTS(g_slunkcrypt_abort_flag ? T("\n\nProcess interrupted!\n\n") : T("\n\nWhoops: Failed to initialize encoder!\n\n"), stderr);
482 status = slunkcrypt_encrypt_inplace(ctx, (uint8_t*)text_temp, length);
483 if (status != SLUNKCRYPT_SUCCESS)
485 FPUTS((status == SLUNKCRYPT_ABORTED) ? T("\n\nProcess interrupted!\n\n") : T("\n\nWhoops: Failed to encrypt the message!\n\n"), stderr);
489 if (strncmp(message, text_temp, length) == 0)
491 FPUTS(T("\n\nWhoops: Encrypted message equals the original message!\n\n"), stderr);
495 status = slunkcrypt_reset(ctx, seed, (const uint8_t*)passphrase, strlen(passphrase));
496 if (status != SLUNKCRYPT_SUCCESS)
498 FPUTS((status == SLUNKCRYPT_ABORTED) ? T("\n\nProcess interrupted!\n\n") : T("\n\nWhoops: Failed to initialize decoder!\n\n"), stderr);
502 status = slunkcrypt_decrypt_inplace(ctx, (uint8_t*)text_temp, length);
503 if (status != SLUNKCRYPT_SUCCESS)
505 FPUTS((status == SLUNKCRYPT_ABORTED) ? T("\n\nProcess interrupted!\n\n") : T("\n\nWhoops: Failed to decrypt the message!\n\n"), stderr);
509 if (strncmp(message, text_temp, length) != 0)
511 FPUTS(T("\n\nWhoops: Decrypted message does *not* match the original message!\n\n"), stderr);
521 slunkcrypt_free(ctx);
526 slunkcrypt_bzero(text_temp, strlen(text_temp));
533 static int run_self_test(void)
535 static const size_t total = 32U;
536 const char* const test_data[] = { TEST_DATA_0, TEST_DATA_1, TEST_DATA_2, TEST_DATA_3, NULL };
538 size_t completed = 0U;
539 FPRINTF(stderr, T("Self-test is running, please be patient... %2u/%2u "), (unsigned int)completed, (unsigned int)total);
542 for (size_t i = 0U; i < 8U; ++i)
544 for (size_t j = 0U; test_data[j]; ++j)
546 FPRINTF(stderr, T("\b\b\b\b\b\b%2u/%2u "), (unsigned int)++completed, (unsigned int)total);
548 if (run_test_case(test_data[j]))
555 FPRINTF(stderr, T("\b\b\b\b\b\b%2u/%2u\n\nCompleted successfully.\n\n"), (unsigned int)total, (unsigned int)total);
561 // ==========================================================================
563 // ==========================================================================
565 int MAIN(const int argc, CHR *const argv[])
568 signal(SIGINT, sigint_handler);
571 FPRINTF(stderr, T("SlunkCrypt Utility (%") T(PRIstr) T("-%") T(PRIstr) T("), by LoRd_MuldeR <MuldeR2@GMX.de>\n"), OS_TYPE, CPU_ARCH);
572 FPRINTF(stderr, T("Using libSlunkCrypt v%u.%u.%u [%") T(PRIstr) T("]\n\n"), SLUNKCRYPT_VERSION_MAJOR, SLUNKCRYPT_VERSION_MINOR, SLUNKCRYPT_VERSION_PATCH, SLUNKCRYPT_BUILD);
574 /* ----------------------------------------------------- */
575 /* Parse arguments */
576 /* ----------------------------------------------------- */
578 const int mode = (argc > 1) ? parse_mode(argv[1U]) : OP_MODE_NONE;
582 FPRINTF(stderr, T("Error: Nothing to do. Please type '%") T(PRISTR) T(" --help' for details!\n\n"), get_file_name(argv[0U]));
585 print_manpage(get_file_name(argv[0U]));
591 return run_self_test();
598 FPRINTF(stderr, T("Error: Required argument is missing. Please type '%") T(PRISTR) T(" --help' for details!\n\n"), get_file_name(argv[0U]));
602 const CHR* const passphrase = (argc > 4) ? argv[2U] : GETENV(ENVV_PASSWD_NAME);
603 const CHR* const input_file = argv[(argc > 4) ? 3U : 2U], * const output_file = argv[(argc > 4) ? 4U : 3U];
605 if ((!passphrase) || (!passphrase[0U]) || (((passphrase[0U] == T('@')) || (passphrase[0U] == T(':'))) && (!passphrase[1U])))
607 FPUTS(T("Error: The specified passphrase must not be empty!\n\n"), stderr);
611 if ((!input_file[0U]) || (!output_file[0U]))
613 FPUTS(T("Error: The input file and/or output file must not be empty!\n\n"), stderr);
617 /* ----------------------------------------------------- */
618 /* Initialize passphrase */
619 /* ----------------------------------------------------- */
621 char *const passphrase_buffer = (passphrase[0U] == T('@')) ? read_passphrase(passphrase + 1U) : CHR_to_utf8((passphrase[0U] == T(':')) ? (passphrase + 1U) : passphrase);
622 if (!passphrase_buffer)
624 FPUTS(T("Error: Failed to read the passphrase!\n\n"), stderr);
628 slunkcrypt_bzero((CHR*)passphrase, STRLEN(passphrase) * sizeof(CHR));
630 const size_t passphrase_len = strlen(passphrase_buffer);
631 if (passphrase_len < SLUNKCRYPT_PWDLEN_MIN)
633 FPRINTF(stderr, T("Error: Passphrase must be at least %") T(PRIu64) T(" characters in length!\n\n"), (uint64_t)SLUNKCRYPT_PWDLEN_MIN);
636 else if (passphrase_len > SLUNKCRYPT_PWDLEN_MAX)
638 FPRINTF(stderr, T("Error: Passphrase must be at most %") T(PRIu64) T(" characters in length!\n\n"), (uint64_t)SLUNKCRYPT_PWDLEN_MAX);
642 if (passphrase_len < 12U)
644 FPUTS(T("Warning: Using a *short* passphrase; a length of 12 characters or more is recommended!\n\n"), stderr);
646 else if (weak_passphrase(passphrase_buffer))
648 FPUTS(T("Warning: Using a *weak* passphrase; a mix of upper-case letters, lower-case letters, digits and 'special' characters is recommended!\n\n"), stderr);
651 /* ----------------------------------------------------- */
652 /* Encrypt or decrypt */
653 /* ----------------------------------------------------- */
655 const clock_t clk_start = clock();
660 result = encrypt(passphrase_buffer, input_file, output_file);
663 result = decrypt(passphrase_buffer, input_file, output_file);
666 abort(); /*not supposed to happen!*/
669 if (!g_slunkcrypt_abort_flag)
671 FPUTS(T("--------\n\n"), stderr);
673 const clock_t clk_end = clock();
674 FPRINTF(stderr, T("Operation completed after %.1f seconds.\n\n"), (clk_end - clk_start) / ((double)CLOCKS_PER_SEC));
677 /* ----------------------------------------------------- */
679 /* ----------------------------------------------------- */
683 if (passphrase_buffer)
685 slunkcrypt_bzero(passphrase_buffer, strlen(passphrase_buffer));
686 free(passphrase_buffer);