diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 884bfb1..d4e1f86 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -115,10 +115,10 @@ jobs: cd extract_test ../build/bin/bfc extract ../test.bfc - # Verify extracted files - [ -f hello.txt ] && echo "hello.txt extracted" - [ -f bye.txt ] && echo "bye.txt extracted" - [ -f subdir/nested.txt ] && echo "nested.txt extracted" + # Verify extracted files (directory paths are preserved) + [ -f test_data/hello.txt ] && echo "hello.txt extracted" + [ -f test_data/bye.txt ] && echo "bye.txt extracted" + [ -f test_data/subdir/nested.txt ] && echo "nested.txt extracted" cd .. rm -rf extract_test @@ -153,12 +153,13 @@ jobs: ./build/bin/bfc info test_symlinks.bfc | grep "Symlinks:" && echo "Symlinks counted in container info" || echo "Symlink counting failed" # Test symlink-specific info - ./build/bin/bfc info test_symlinks.bfc simple_link.txt | grep "Type: Symlink" && echo "Symlink type displayed correctly" || echo "Symlink type display failed" + ./build/bin/bfc info test_symlinks.bfc test_symlinks/simple_link.txt | grep "Type: Symlink" && echo "Symlink type displayed correctly" || echo "Symlink type display failed" # Test symlink extraction mkdir -p extract_symlinks cd extract_symlinks ../build/bin/bfc extract ../test_symlinks.bfc + cd test_symlinks # Verify symlinks were extracted correctly [ -L simple_link.txt ] && echo "Simple symlink extracted as symlink" || echo "Simple symlink not extracted as symlink" @@ -175,11 +176,11 @@ jobs: [ "$TARGET" = "/tmp/absolute_target" ] && echo "Absolute symlink target correct" || echo "Absolute symlink target incorrect: $TARGET" fi - cd .. + cd ../.. rm -rf extract_symlinks # Test symlinks with compression and encryption - ./build/bin/bfc create -c zstd -e testpass symlinks_comp_enc.bfc test_symlinks/simple_link.txt test_symlinks/absolute_link.txt + ./build/bin/bfc create -c zstd -p testpass symlinks_comp_enc.bfc test_symlinks/simple_link.txt test_symlinks/absolute_link.txt echo "Symlinks work with compression and encryption" mkdir -p extract_comp_enc @@ -194,7 +195,7 @@ jobs: # Test encryption functionality echo "Testing encryption features..." - ./build/bin/bfc create -e testpassword123 test_encrypted.bfc test_data/ + ./build/bin/bfc create -p testpassword123 test_encrypted.bfc test_data/ ./build/bin/bfc info test_encrypted.bfc ./build/bin/bfc info test_encrypted.bfc test_data/hello.txt | grep -i encrypt @@ -204,9 +205,9 @@ jobs: ../build/bin/bfc extract -p testpassword123 ../test_encrypted.bfc # Verify extracted files from encrypted container - [ -f hello.txt ] && echo "hello.txt extracted from encrypted container" - [ -f bye.txt ] && echo "bye.txt extracted from encrypted container" - [ -f subdir/nested.txt ] && echo "nested.txt extracted from encrypted container" + [ -f test_data/hello.txt ] && echo "hello.txt extracted from encrypted container" + [ -f test_data/bye.txt ] && echo "bye.txt extracted from encrypted container" + [ -f test_data/subdir/nested.txt ] && echo "nested.txt extracted from encrypted container" cd .. rm -rf extract_encrypted @@ -220,19 +221,19 @@ jobs: # Test key file encryption echo -n "0123456789abcdef0123456789abcdef" > test.key - ./build/bin/bfc create -k test.key test_keyfile.bfc test_data/ + ./build/bin/bfc create -K test.key test_keyfile.bfc test_data/ ./build/bin/bfc info test_keyfile.bfc | grep -i encrypt mkdir -p extract_keyfile cd extract_keyfile ../build/bin/bfc extract -K ../test.key ../test_keyfile.bfc - [ -f hello.txt ] && echo "hello.txt extracted with key file" + [ -f test_data/hello.txt ] && echo "hello.txt extracted with key file" cd .. rm -rf extract_keyfile # Test encryption with compression echo "This is a larger test file with enough content to be compressed by zstd compression algorithm." > test_data/large.txt - ./build/bin/bfc create -e testpass -c zstd test_enc_comp.bfc test_data/ + ./build/bin/bfc create -p testpass -c zstd test_enc_comp.bfc test_data/ ./build/bin/bfc info test_enc_comp.bfc test_data/large.txt | grep -i encrypt ./build/bin/bfc info test_enc_comp.bfc test_data/large.txt | grep -i zstd @@ -264,15 +265,15 @@ jobs: mkdir extract_test && cd extract_test "$OLDPWD/$BFC" extract ../test.bfc - [ -f hello.txt ] && echo "hello.txt extracted" - [ -f bye.txt ] && echo "bye.txt extracted" - [ -f subdir/nested.txt ] && echo "nested.txt extracted" + [ -f test_data/hello.txt ] && echo "hello.txt extracted" + [ -f test_data/bye.txt ] && echo "bye.txt extracted" + [ -f test_data/subdir/nested.txt ] && echo "nested.txt extracted" cd .. - "$BFC" create -e testpassword123 test_encrypted.bfc test_data/ + "$BFC" create -p testpassword123 test_encrypted.bfc test_data/ mkdir extract_enc && cd extract_enc "$OLDPWD/$BFC" extract -p testpassword123 ../test_encrypted.bfc - [ -f hello.txt ] && echo "hello.txt extracted from encrypted container" + [ -f test_data/hello.txt ] && echo "hello.txt extracted from encrypted container" cd .. mkdir extract_fail && cd extract_fail @@ -353,14 +354,22 @@ jobs: lcov --capture --directory . --output-file coverage.info \ --rc branch_coverage=1 \ --ignore-errors deprecated,unsupported,unused + # Thresholds apply to the library. The CLI only shows up in coverage + # since tests/cli runs the bfc binary; it is reported separately + # below and does not count towards the thresholds. lcov --remove coverage.info \ - '*/tests/*' \ + '*/tests/*' '*/src/cli/*' \ --output-file coverage_filtered.info \ --rc branch_coverage=1 \ --ignore-errors deprecated,unsupported,unused lcov --list coverage_filtered.info \ --rc branch_coverage=1 \ --ignore-errors deprecated,unsupported,unused + echo "CLI coverage (informational, not checked):" + lcov --extract coverage.info '*/src/cli/*' \ + --output-file coverage_cli.info \ + --rc branch_coverage=1 \ + --ignore-errors deprecated,unsupported,unused,empty || true - name: Check coverage thresholds run: | diff --git a/README.md b/README.md index 3301714..541f792 100644 --- a/README.md +++ b/README.md @@ -162,8 +162,10 @@ The `create` command builds new BFC containers from files and directories. - `-c, --compression TYPE` - Compression: `none`, `zstd`, `auto` (default: none) - `-l, --compression-level N` - Compression level for ZSTD (1-22, default: 3) - `-t, --compression-threshold SIZE` - Minimum file size to compress (default: 64 bytes) -- `-e, --encrypt PASSWORD` - Encrypt files with password (requires libsodium) -- `-k, --keyfile FILE` - Encrypt with 32-byte key from file (requires libsodium) +- `-p, --password PASS` - Encrypt files with password (requires libsodium) +- `--password-file FILE` - Read the password from FILE, `-` for stdin (keeps it out of `ps` and shell history) +- `-K, --keyfile FILE` - Encrypt with 32-byte key from file (requires libsodium) +- `-e, --encrypt` and `-k` are deprecated spellings of `-p` and `-K` **Examples:** ```bash @@ -184,11 +186,12 @@ bfc create -c zstd archive.bfc /data/ bfc create -c zstd -l 9 archive.bfc /data/ # Maximum compression # Create with encryption -bfc create -e mypassword secure.bfc /sensitive/data/ -bfc create -k secret.key secure.bfc /sensitive/data/ +bfc create -p mypassword secure.bfc /sensitive/data/ +bfc create --password-file pass.txt secure.bfc /sensitive/data/ +bfc create -K secret.key secure.bfc /sensitive/data/ # Combined compression and encryption -bfc create -c zstd -e secret -l 6 archive.bfc /data/ +bfc create -c zstd -p secret -l 6 archive.bfc /data/ ``` ### Compression support @@ -231,18 +234,22 @@ BFC supports optional file encryption using industry-standard ChaCha20-Poly1305 ```bash # Password-based encryption -bfc create -e mypassword secure.bfc /sensitive/data/ +bfc create -p mypassword secure.bfc /sensitive/data/ # Key file encryption (32 bytes) echo -n "0123456789abcdef0123456789abcdef" > secret.key -bfc create -k secret.key secure.bfc /sensitive/data/ +bfc create -K secret.key secure.bfc /sensitive/data/ # Combine encryption with compression -bfc create -e mypassword -c zstd archive.bfc /data/ +bfc create -p mypassword -c zstd archive.bfc /data/ # Extract encrypted container with password bfc extract -p mypassword secure.bfc +# Without -p, --password-file or -K, extract asks for the password on the +# terminal (only when stdin is a terminal) +bfc extract secure.bfc + # Extract with key file bfc extract -K secret.key secure.bfc @@ -310,20 +317,24 @@ The `extract` command extracts files and directories from containers. **Options:** - `-C, --directory DIR` - Extract to specific directory (changes to DIR before extracting) - `-f, --force` - Overwrite existing files without prompting -- `-k, --keep-paths` - Preserve full directory structure (default: flatten to basenames) +- `--flatten` - Drop directories and extract every file by its name only. Fails if two entries have the same name, even with `-f` - `-p, --password PASS` - Provide password for encrypted containers +- `--password-file FILE` - Read the password from FILE (`-` for stdin) - `-K, --keyfile FILE` - Use key file for encrypted containers (32 bytes) +- `-k, --keep-paths` - Deprecated, no effect: directory paths are preserved by default + +Directory paths are recreated under the output directory. Entries with absolute paths or `..` components, and entries that would be written through a symlink, are refused. **Examples:** ```bash -# Extract all files to current directory (flattened) +# Extract all files to the current directory, keeping directory paths bfc extract archive.bfc # Extract to specific directory bfc extract -C /tmp/extracted archive.bfc -# Extract preserving directory structure -bfc extract -k archive.bfc +# Extract every file into one directory, without subdirectories +bfc extract --flatten archive.bfc # Extract specific files/directories only bfc extract archive.bfc docs/ README.txt @@ -337,8 +348,8 @@ bfc extract -p mypassword secure.bfc # Extract encrypted container with key file bfc extract -K secret.key secure.bfc -# Combined: extract to directory, preserve paths, force overwrite -bfc extract -kf -C /tmp/output archive.bfc +# Combined: extract to directory, force overwrite +bfc extract -f -C /tmp/output archive.bfc ``` ### Container information @@ -373,7 +384,8 @@ The `verify` command checks container and file integrity. **Options:** - `--deep` - Perform deep verification (read and verify all file contents, slower but thorough) -- `-p, --progress` - Show progress bar during verification (useful for large containers) +- `--progress` - Show progress during verification (useful for large containers) +- `-p, --password PASS`, `--password-file FILE`, `-K, --keyfile FILE` - Credentials for encrypted containers, needed for `--deep` **Examples:** ```bash @@ -384,7 +396,10 @@ bfc verify archive.bfc bfc verify --deep archive.bfc # Deep verification with progress indicator -bfc verify -p --deep archive.bfc +bfc verify --progress --deep archive.bfc + +# Deep verification of an encrypted container +bfc verify --deep -p mypassword secure.bfc ``` ## Library Usage @@ -473,8 +488,9 @@ See the [examples/](examples/) directory for complete examples. -c, --compression TYPE none|zstd|auto (default: none) -l, --compression-level N ZSTD level 1-22 (default: 3) -t, --compression-threshold SIZE Min size to compress (default: 64) --e, --encrypt PASSWORD Encrypt with password --k, --keyfile FILE Encrypt with key file (32 bytes) +-p, --password PASS Encrypt with password + --password-file FILE Read the password from FILE (- for stdin) +-K, --keyfile FILE Encrypt with key file (32 bytes) ``` **`bfc list [options] [path]`** @@ -488,8 +504,9 @@ See the [examples/](examples/) directory for complete examples. ``` -C, --directory DIR Extract to specific directory -f, --force Overwrite existing files --k, --keep-paths Preserve directory structure + --flatten Drop directories, extract files by name only -p, --password PASS Password for encrypted containers + --password-file FILE Read the password from FILE (- for stdin) -K, --keyfile FILE Key file for encrypted containers ``` @@ -501,23 +518,26 @@ See the [examples/](examples/) directory for complete examples. **`bfc verify [options] `** ``` --deep Deep verification (check all content) --p, --progress Show progress indicator + --progress Show progress indicator +-p, --password PASS Password for encrypted containers + --password-file FILE Read the password from FILE (- for stdin) +-K, --keyfile FILE Key file for encrypted containers ``` ### Common Usage Patterns ```bash # Create compressed encrypted archive -bfc create -c zstd -e password archive.bfc /data/ +bfc create -c zstd -p password archive.bfc /data/ # List with full details bfc list -lsc archive.bfc -# Extract preserving structure to specific location -bfc extract -k -C /tmp/restored archive.bfc +# Extract to a specific location +bfc extract -C /tmp/restored archive.bfc # Verify with progress -bfc verify -p --deep archive.bfc +bfc verify --progress --deep archive.bfc # Get detailed info about specific file bfc info -d archive.bfc path/to/file.txt diff --git a/src/cli/CMakeLists.txt b/src/cli/CMakeLists.txt index a7b5bf6..3f8b02a 100644 --- a/src/cli/CMakeLists.txt +++ b/src/cli/CMakeLists.txt @@ -20,6 +20,7 @@ set(BFC_CLI_SOURCES cmd_extract.c cmd_verify.c cli_util.c + cli_credentials.c ) add_executable(bfc_cli ${BFC_CLI_SOURCES}) diff --git a/src/cli/cli.h b/src/cli/cli.h index fb85579..d87b8cb 100644 --- a/src/cli/cli.h +++ b/src/cli/cli.h @@ -59,6 +59,27 @@ int parse_global_options(int* argc, char*** argv, bfc_options_t* opts); const char* bfc_error_string(int error_code); int read_key_from_file(const char* keyfile, uint8_t key[32]); +// Password and key-file options, shared by create, extract and verify +typedef struct { + const char* password; // -p, --password + const char* password_file; // --password-file ("-" for stdin) + const char* keyfile; // -K, --keyfile + char* owned_password; // read from file or prompt; wiped on free +} cli_credentials_t; + +void cli_credentials_init(cli_credentials_t* c); +void cli_credentials_free(cli_credentials_t* c); +// Returns 1 if argv[*i] was a credential option (and consumes its value), +// 0 if it was not, -1 on error. +int cli_parse_credential_option(int argc, char* argv[], int* i, cli_credentials_t* c); +int cli_credentials_given(const cli_credentials_t* c); +int cli_credentials_check(const cli_credentials_t* c); +// prompt_if_needed: ask on the terminal when the container is encrypted and +// no credentials were given (only when stdin is a terminal). +// Both return 1 if a password or key was set, 0 if none was given, -1 on error. +int cli_apply_reader_credentials(bfc_t* reader, cli_credentials_t* c, int prompt_if_needed); +int cli_apply_writer_credentials(bfc_t* writer, cli_credentials_t* c); + // Global options (extern declaration) extern bfc_options_t g_options; diff --git a/src/cli/cli_credentials.c b/src/cli/cli_credentials.c new file mode 100644 index 0000000..1f5bc4d --- /dev/null +++ b/src/cli/cli_credentials.c @@ -0,0 +1,266 @@ +/* + * Copyright 2021 zombocoder (Taras Havryliak) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Password and key-file options shared by create, extract and verify, so the +// commands spell and handle them the same way. + +#include "cli.h" +#include +#include +#include +#include + +#ifdef _WIN32 +#include +#include +#define isatty _isatty +#define fileno _fileno +#else +#include +#include +#endif + +#define CLI_PASSWORD_MAX 1024 + +void cli_credentials_init(cli_credentials_t* c) { + c->password = NULL; + c->password_file = NULL; + c->keyfile = NULL; + c->owned_password = NULL; +} + +void cli_credentials_free(cli_credentials_t* c) { + if (c->owned_password) { + memset(c->owned_password, 0, strlen(c->owned_password)); + free(c->owned_password); + c->owned_password = NULL; + } +} + +int cli_parse_credential_option(int argc, char* argv[], int* i, cli_credentials_t* c) { + const char* arg = argv[*i]; + const char** target = NULL; + + if (strcmp(arg, "-p") == 0 || strcmp(arg, "--password") == 0) { + target = &c->password; + } else if (strcmp(arg, "--password-file") == 0) { + target = &c->password_file; + } else if (strcmp(arg, "-K") == 0 || strcmp(arg, "--keyfile") == 0) { + target = &c->keyfile; + } else { + return 0; + } + + if (*i + 1 >= argc) { + print_error("%s requires an argument", arg); + return -1; + } + *target = argv[++(*i)]; + return 1; +} + +int cli_credentials_given(const cli_credentials_t* c) { + return c->password || c->password_file || c->keyfile; +} + +int cli_credentials_check(const cli_credentials_t* c) { + int n = (c->password != NULL) + (c->password_file != NULL) + (c->keyfile != NULL); + if (n > 1) { + print_error("Use only one of --password, --password-file and --keyfile"); + return -1; + } + return 0; +} + +// Read the first line of a file ("-" for stdin) as the password. +static char* read_password_file(const char* path) { + FILE* f = strcmp(path, "-") == 0 ? stdin : fopen(path, "rb"); + if (!f) { + print_error("Cannot open password file '%s': %s", path, strerror(errno)); + return NULL; + } + + char* buf = malloc(CLI_PASSWORD_MAX); + if (!buf) { + if (f != stdin) { + fclose(f); + } + print_error("Out of memory"); + return NULL; + } + + if (!fgets(buf, CLI_PASSWORD_MAX, f)) { + buf[0] = '\0'; + } + if (f != stdin) { + fclose(f); + } + + buf[strcspn(buf, "\r\n")] = '\0'; + if (buf[0] == '\0') { + print_error("Password file '%s' is empty", path); + free(buf); + return NULL; + } + return buf; +} + +// Prompt on the terminal with echo turned off. Returns NULL if stdin is not a +// terminal, so scripts never block waiting for input. +static char* prompt_password(const char* prompt) { + if (!isatty(fileno(stdin))) { + return NULL; + } + + char* buf = malloc(CLI_PASSWORD_MAX); + if (!buf) { + print_error("Out of memory"); + return NULL; + } + + fprintf(stderr, "%s", prompt); + fflush(stderr); + +#ifdef _WIN32 + size_t n = 0; + int ch; + while ((ch = _getch()) != '\r' && ch != '\n' && ch != EOF) { + if (ch == '\b') { + if (n > 0) { + n--; + } + } else if (n + 1 < CLI_PASSWORD_MAX) { + buf[n++] = (char) ch; + } + } + buf[n] = '\0'; +#else + struct termios old_t, new_t; + int restore = 0; + if (tcgetattr(fileno(stdin), &old_t) == 0) { + new_t = old_t; + new_t.c_lflag &= ~(tcflag_t) ECHO; + restore = tcsetattr(fileno(stdin), TCSAFLUSH, &new_t) == 0; + } + if (!fgets(buf, CLI_PASSWORD_MAX, stdin)) { + buf[0] = '\0'; + } + if (restore) { + tcsetattr(fileno(stdin), TCSAFLUSH, &old_t); + } + buf[strcspn(buf, "\r\n")] = '\0'; +#endif + + fprintf(stderr, "\n"); + return buf; +} + +// Resolve the password from --password or --password-file. Returns 0 with +// *out set (or NULL if none was given), -1 on error. +static int resolve_password(cli_credentials_t* c, const char** out) { + *out = c->password; + if (c->password_file) { + c->owned_password = read_password_file(c->password_file); + if (!c->owned_password) { + return -1; + } + *out = c->owned_password; + } + return 0; +} + +int cli_apply_reader_credentials(bfc_t* reader, cli_credentials_t* c, int prompt_if_needed) { + const char* password; + if (resolve_password(c, &password) != 0) { + return -1; + } + + if (!password && !c->keyfile && prompt_if_needed && bfc_has_encryption(reader)) { + c->owned_password = prompt_password("Password: "); + password = c->owned_password; + if (!password) { + print_error("Container is encrypted; pass --password, --password-file or --keyfile"); + return -1; + } + if (password[0] == '\0') { + print_error("No password entered"); + return -1; + } + } + + if (!password && !c->keyfile) { + return 0; + } + +#ifdef BFC_WITH_SODIUM + int result; + if (password) { + result = bfc_reader_set_encryption_password(reader, password, strlen(password)); + } else { + uint8_t key[32]; + if (read_key_from_file(c->keyfile, key) != 0) { + return -1; + } + result = bfc_reader_set_encryption_key(reader, key); + memset(key, 0, sizeof(key)); + } + if (result != BFC_OK) { + print_error("Failed to set encryption key: %s", bfc_error_string(result)); + return -1; + } + return 1; +#else + (void) reader; + print_error("Encryption support not available. Please build with BFC_WITH_SODIUM=ON"); + return -1; +#endif +} + +int cli_apply_writer_credentials(bfc_t* writer, cli_credentials_t* c) { + const char* password; + if (resolve_password(c, &password) != 0) { + return -1; + } + + if (!password && !c->keyfile) { + return 0; + } + +#ifdef BFC_WITH_SODIUM + int result; + if (password) { + result = bfc_set_encryption_password(writer, password, strlen(password)); + print_verbose("Encryption: ChaCha20-Poly1305 with password-based key derivation"); + } else { + uint8_t key[32]; + if (read_key_from_file(c->keyfile, key) != 0) { + return -1; + } + result = bfc_set_encryption_key(writer, key); + memset(key, 0, sizeof(key)); + print_verbose("Encryption: ChaCha20-Poly1305 with key from file"); + } + if (result != BFC_OK) { + print_error("Failed to set encryption key: %s", bfc_error_string(result)); + return -1; + } + return 1; +#else + (void) writer; + print_error("Encryption support not available. Rebuild with -DBFC_WITH_SODIUM=ON"); + return -1; +#endif +} diff --git a/src/cli/cmd_create.c b/src/cli/cmd_create.c index 06c84f2..55801d2 100644 --- a/src/cli/cmd_create.c +++ b/src/cli/cmd_create.c @@ -37,9 +37,7 @@ typedef struct { int compression_level; size_t compression_threshold; // Encryption options - const char* encryption_password; - const char* encryption_keyfile; - int use_encryption; + cli_credentials_t creds; } create_options_t; static void print_create_help(void) { @@ -51,16 +49,18 @@ static void print_create_help(void) { printf(" -c, --compression TYPE Compression type: none, zstd, auto (default: none)\n"); printf(" -l, --compression-level N Compression level (1-22 for zstd, default: 3)\n"); printf(" -t, --compression-threshold SIZE Min file size to compress (default: 64)\n"); - printf(" -e, --encrypt PASSWORD Encrypt with password\n"); - printf(" -k, --keyfile FILE Encrypt with key from file (32 bytes)\n"); + printf(" -p, --password PASS Encrypt with password\n"); + printf(" --password-file FILE Read the password from FILE (- for stdin)\n"); + printf(" -K, --keyfile FILE Encrypt with key from file (32 bytes)\n"); printf(" -h, --help Show this help message\n\n"); printf("Examples:\n"); printf(" bfc create archive.bfc /path/to/files/\n"); printf(" bfc create -f archive.bfc file1.txt file2.txt dir/\n"); printf(" bfc create -b 8192 archive.bfc /home/user/documents/\n"); printf(" bfc create -c zstd -l 9 archive.bfc /data/\n"); - printf(" bfc create -e mypassword archive.bfc /secure/data/\n"); - printf(" bfc create -c zstd -e secret -l 6 archive.bfc /compressed-encrypted/\n"); + printf(" bfc create -p mypassword archive.bfc /secure/data/\n"); + printf(" bfc create -c zstd -p secret -l 6 archive.bfc /compressed-encrypted/\n"); + printf(" bfc create --password-file pass.txt archive.bfc /secure/data/\n"); } static int parse_create_options(int argc, char* argv[], create_options_t* opts) { @@ -75,11 +75,9 @@ static int parse_create_options(int argc, char* argv[], create_options_t* opts) opts->compression_level = 3; opts->compression_threshold = 64; // Encryption defaults - opts->encryption_password = NULL; - opts->encryption_keyfile = NULL; - opts->use_encryption = 0; + cli_credentials_init(&opts->creds); - int i; + int i, cred; for (i = 1; i < argc; i++) { if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) { print_create_help(); @@ -129,19 +127,25 @@ static int parse_create_options(int argc, char* argv[], create_options_t* opts) return -1; } } else if (strcmp(argv[i], "-e") == 0 || strcmp(argv[i], "--encrypt") == 0) { + // Deprecated spelling of -p/--password if (i + 1 >= argc) { - print_error("--encrypt requires a password argument"); + print_error("%s requires a password argument", argv[i]); return -1; } - opts->encryption_password = argv[++i]; - opts->use_encryption = 1; - } else if (strcmp(argv[i], "-k") == 0 || strcmp(argv[i], "--keyfile") == 0) { + fprintf(stderr, "Warning: %s is deprecated, use -p/--password\n", argv[i]); + opts->creds.password = argv[++i]; + } else if (strcmp(argv[i], "-k") == 0) { + // Deprecated spelling of -K/--keyfile if (i + 1 >= argc) { - print_error("--keyfile requires a file path argument"); + print_error("-k requires a file path argument"); + return -1; + } + fprintf(stderr, "Warning: -k is deprecated, use -K/--keyfile\n"); + opts->creds.keyfile = argv[++i]; + } else if ((cred = cli_parse_credential_option(argc, argv, &i, &opts->creds)) != 0) { + if (cred < 0) { return -1; } - opts->encryption_keyfile = argv[++i]; - opts->use_encryption = 1; } else if (argv[i][0] == '-') { print_error("Unknown option: %s", argv[i]); return -1; @@ -164,8 +168,7 @@ static int parse_create_options(int argc, char* argv[], create_options_t* opts) } // Validate encryption options - if (opts->encryption_password && opts->encryption_keyfile) { - print_error("Cannot specify both --encrypt and --keyfile"); + if (cli_credentials_check(&opts->creds) != 0) { return -1; } @@ -367,7 +370,7 @@ int cmd_create(int argc, char* argv[]) { } // Add encryption feature if encryption is enabled - if (opts.use_encryption) { + if (cli_credentials_given(&opts.creds)) { features |= BFC_FEATURE_AEAD; } @@ -399,43 +402,11 @@ int cmd_create(int argc, char* argv[]) { } // Configure encryption settings - if (opts.use_encryption) { -#ifndef BFC_WITH_SODIUM - print_error("Encryption support not available. Rebuild with -DBFC_WITH_SODIUM=ON"); + int enc_result = cli_apply_writer_credentials(writer, &opts.creds); + cli_credentials_free(&opts.creds); + if (enc_result < 0) { bfc_close(writer); return 1; -#else - if (opts.encryption_password) { - // Use password-based encryption - result = bfc_set_encryption_password(writer, opts.encryption_password, - strlen(opts.encryption_password)); - if (result != BFC_OK) { - print_error("Failed to set encryption password: %s", bfc_error_string(result)); - bfc_close(writer); - return 1; - } - print_verbose("Encryption: ChaCha20-Poly1305 with password-based key derivation"); - } else if (opts.encryption_keyfile) { - // Use key file - uint8_t key[32]; - if (read_key_from_file(opts.encryption_keyfile, key) != 0) { - bfc_close(writer); - return 1; - } - - result = bfc_set_encryption_key(writer, key); - - // Clear key from memory - memset(key, 0, sizeof(key)); - - if (result != BFC_OK) { - print_error("Failed to set encryption key: %s", bfc_error_string(result)); - bfc_close(writer); - return 1; - } - print_verbose("Encryption: ChaCha20-Poly1305 with key from file"); - } -#endif } // Add input paths diff --git a/src/cli/cmd_extract.c b/src/cli/cmd_extract.c index 68bacac..e0b16c0 100644 --- a/src/cli/cmd_extract.c +++ b/src/cli/cmd_extract.c @@ -14,9 +14,9 @@ * limitations under the License. */ +#include "bfc_format.h" #include "cli.h" #ifndef _WIN32 -#include #include #include #endif @@ -30,13 +30,12 @@ typedef struct { int force; - int preserve_paths; + int flatten; const char* output_dir; const char* container_file; const char** extract_paths; int num_paths; - const char* encryption_password; - const char* encryption_keyfile; + cli_credentials_t creds; } extract_options_t; static void print_extract_help(void) { @@ -45,18 +44,22 @@ static void print_extract_help(void) { printf("Options:\n"); printf(" -C, --directory DIR Change to directory DIR before extracting\n"); printf(" -f, --force Overwrite existing files\n"); - printf(" -k, --keep-paths Preserve full directory paths when extracting\n"); + printf(" --flatten Drop directories: extract every file by its name only\n"); printf(" -p, --password PASS Password for encrypted container\n"); + printf(" --password-file FILE Read the password from FILE (- for stdin)\n"); printf(" -K, --keyfile FILE Key file for encrypted container (32 bytes)\n"); printf(" -h, --help Show this help message\n\n"); printf("Arguments:\n"); printf(" container.bfc BFC container to extract from\n"); printf(" paths Optional paths to extract (default: all)\n\n"); + printf("Directory paths from the container are recreated under the output\n"); + printf("directory. Entries with absolute paths or '..' components, and entries\n"); + printf("that would be written through a symlink, are refused.\n\n"); printf("Examples:\n"); printf(" bfc extract archive.bfc # Extract all files\n"); printf(" bfc extract -C /tmp archive.bfc # Extract to /tmp\n"); printf(" bfc extract archive.bfc docs/ # Extract docs/ directory\n"); - printf(" bfc extract -k archive.bfc file.txt # Extract preserving path\n"); + printf(" bfc extract --flatten archive.bfc # All files into one directory\n"); printf(" bfc extract -p secret archive.bfc # Extract encrypted container\n"); printf(" bfc extract -K key.bin archive.bfc # Extract with key file\n"); } @@ -64,15 +67,14 @@ static void print_extract_help(void) { static int parse_extract_options(int argc, char* argv[], extract_options_t* opts) { // Initialize options opts->force = 0; - opts->preserve_paths = 0; + opts->flatten = 0; opts->output_dir = NULL; opts->container_file = NULL; opts->extract_paths = NULL; opts->num_paths = 0; - opts->encryption_password = NULL; - opts->encryption_keyfile = NULL; + cli_credentials_init(&opts->creds); - int i; + int i, cred; for (i = 1; i < argc; i++) { if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) { print_extract_help(); @@ -80,25 +82,23 @@ static int parse_extract_options(int argc, char* argv[], extract_options_t* opts } else if (strcmp(argv[i], "-f") == 0 || strcmp(argv[i], "--force") == 0) { opts->force = 1; } else if (strcmp(argv[i], "-k") == 0 || strcmp(argv[i], "--keep-paths") == 0) { - opts->preserve_paths = 1; + // Paths are preserved by default now; -K is the key-file option. + fprintf(stderr, + "Warning: %s is deprecated and has no effect: paths are preserved by " + "default (use -K for a key file)\n", + argv[i]); + } else if (strcmp(argv[i], "--flatten") == 0) { + opts->flatten = 1; } else if (strcmp(argv[i], "-C") == 0 || strcmp(argv[i], "--directory") == 0) { if (i + 1 >= argc) { print_error("--directory requires an argument"); return -1; } opts->output_dir = argv[++i]; - } else if (strcmp(argv[i], "-p") == 0 || strcmp(argv[i], "--password") == 0) { - if (i + 1 >= argc) { - print_error("--password requires an argument"); - return -1; - } - opts->encryption_password = argv[++i]; - } else if (strcmp(argv[i], "-K") == 0 || strcmp(argv[i], "--keyfile") == 0) { - if (i + 1 >= argc) { - print_error("--keyfile requires an argument"); + } else if ((cred = cli_parse_credential_option(argc, argv, &i, &opts->creds)) != 0) { + if (cred < 0) { return -1; } - opts->encryption_keyfile = argv[++i]; } else if (argv[i][0] == '-') { // Handle combined short options like -fk const char* opt = argv[i] + 1; @@ -108,7 +108,8 @@ static int parse_extract_options(int argc, char* argv[], extract_options_t* opts opts->force = 1; break; case 'k': - opts->preserve_paths = 1; + fprintf(stderr, "Warning: -k is deprecated and has no effect: paths are preserved by " + "default (use -K for a key file)\n"); break; default: print_error("Unknown option: -%c", *opt); @@ -134,50 +135,46 @@ static int parse_extract_options(int argc, char* argv[], extract_options_t* opts return -1; } - return 0; + return cli_credentials_check(&opts->creds); } +// Create every missing parent directory of path. Walks the components in +// place: dirname() returns a static buffer on some systems (macOS), which a +// recursive implementation overwrites. static int create_parent_directories(const char* path, int force) { - char* path_copy = strdup(path); - if (!path_copy) { + (void) force; + char* buf = strdup(path); + if (!buf) { return -1; } - char* dir = dirname(path_copy); - if (strcmp(dir, ".") == 0 || strcmp(dir, "/") == 0) { - free(path_copy); - return 0; - } - - // Recursively create parent directories first - if (create_parent_directories(dir, force) != 0) { - free(path_copy); - return -1; - } - - print_verbose("Creating directory: %s", dir); + for (char* p = buf + 1; (p = strchr(p, '/')) != NULL; p++) { + *p = '\0'; + print_verbose("Creating directory: %s", buf); #ifdef _WIN32 - if (mkdir(dir) != 0) { + int rc = mkdir(buf); #else - if (mkdir(dir, 0755) != 0) { + int rc = mkdir(buf, 0755); #endif - if (errno == EEXIST) { - // Directory already exists - verify it is actually a directory - struct stat st; - if (stat(dir, &st) != 0 || !S_ISDIR(st.st_mode)) { - print_error("'%s' exists but is not a directory", dir); - free(path_copy); + if (rc != 0) { + if (errno == EEXIST) { + // Already exists - verify it is actually a directory + struct stat st; + if (stat(buf, &st) != 0 || !S_ISDIR(st.st_mode)) { + print_error("'%s' exists but is not a directory", buf); + free(buf); + return -1; + } + } else { + print_error("Cannot create directory '%s': %s", buf, strerror(errno)); + free(buf); return -1; } - // Already a directory, that is fine - } else { - print_error("Cannot create directory '%s': %s", dir, strerror(errno)); - free(path_copy); - return -1; } + *p = '/'; } - free(path_copy); + free(buf); return 0; } @@ -417,6 +414,110 @@ static int extract_symlink(bfc_t* reader, const bfc_entry_t* entry, const char* return 0; } +// Refuse entry paths that could land outside the output directory. The writer +// normalizes paths, but the reader takes them from the index as stored, so a +// hand-made container can hold anything. +static int entry_path_is_safe(const char* path) { + if (bfc_path_validate(path) != BFC_OK) { + return 0; // absolute, empty, or contains ".." components + } +#ifdef _WIN32 + // On Windows "\\" is also a separator and "C:" a drive prefix + if (strchr(path, '\\') || strchr(path, ':')) { + return 0; + } +#endif + return 1; +} + +// Return 1 if any parent component of path (relative to the current directory) +// is a symlink. Writing below one would follow it, possibly out of the output +// directory, since O_NOFOLLOW only covers the last component. +static int has_symlink_parent(const char* path) { +#ifdef _WIN32 + (void) path; + return 0; // symlinks are never created on Windows +#else + char buf[1024]; + size_t len = strlen(path); + if (len >= sizeof(buf)) { + return 1; + } + memcpy(buf, path, len + 1); + + for (char* p = buf; (p = strchr(p, '/')) != NULL; p++) { + struct stat st; + *p = '\0'; + int is_link = lstat(buf, &st) == 0 && S_ISLNK(st.st_mode); + *p = '/'; + if (is_link) { + return 1; + } + } + return 0; +#endif +} + +// Set of output names already used in --flatten mode, to catch two entries +// that would be written to the same file. +typedef struct { + char** slots; + size_t cap; + size_t used; +} name_set_t; + +static uint64_t name_hash(const char* s) { + uint64_t h = 1469598103934665603ULL; // FNV-1a + for (; *s; s++) { + h = (h ^ (unsigned char) *s) * 1099511628211ULL; + } + return h; +} + +// Returns 1 if added, 0 if already present, -1 on allocation failure. +static int name_set_add(name_set_t* set, const char* name) { + if (set->used * 2 >= set->cap) { + size_t ncap = set->cap ? set->cap * 2 : 64; + char** nslots = calloc(ncap, sizeof(char*)); + if (!nslots) { + return -1; + } + for (size_t i = 0; i < set->cap; i++) { + if (set->slots[i]) { + size_t j = name_hash(set->slots[i]) & (ncap - 1); + while (nslots[j]) { + j = (j + 1) & (ncap - 1); + } + nslots[j] = set->slots[i]; + } + } + free(set->slots); + set->slots = nslots; + set->cap = ncap; + } + + size_t j = name_hash(name) & (set->cap - 1); + while (set->slots[j]) { + if (strcmp(set->slots[j], name) == 0) { + return 0; + } + j = (j + 1) & (set->cap - 1); + } + set->slots[j] = strdup(name); + if (!set->slots[j]) { + return -1; + } + set->used++; + return 1; +} + +static void name_set_free(name_set_t* set) { + for (size_t i = 0; i < set->cap; i++) { + free(set->slots[i]); + } + free(set->slots); +} + // Extract callback structure typedef struct { extract_options_t* opts; @@ -424,6 +525,7 @@ typedef struct { const char* output_dir; int count; int errors; + name_set_t flat_names; } extract_context_t; static int extract_entry_callback(const bfc_entry_t* entry, void* user) { @@ -432,27 +534,54 @@ static int extract_entry_callback(const bfc_entry_t* entry, void* user) { ctx->count++; + if (!entry_path_is_safe(entry->path)) { + print_error("Refusing to extract '%s': unsafe path", entry->path); + ctx->errors++; + return 0; + } + // Determine output path char output_path[1024]; - const char* extract_name; + const char* extract_name = entry->path; - if (opts->preserve_paths) { - extract_name = entry->path; - } else { - // Use basename only - extract_name = strrchr(entry->path, '/'); - extract_name = extract_name ? extract_name + 1 : entry->path; - - // Skip if basename is empty (root directory) - if (strlen(extract_name) == 0) { + if (opts->flatten) { + // Directories have nothing to hold once paths are dropped + if (S_ISDIR(entry->mode)) { + return 0; + } + const char* slash = strrchr(entry->path, '/'); + extract_name = slash ? slash + 1 : entry->path; + + int added = name_set_add(&ctx->flat_names, extract_name); + if (added <= 0) { + if (added == 0) { + print_error("Refusing to extract '%s': another entry was already extracted as '%s' " + "(drop --flatten to keep directories)", + entry->path, extract_name); + } else { + print_error("Out of memory"); + } + ctx->errors++; return 0; } } + int n; if (ctx->output_dir) { - snprintf(output_path, sizeof(output_path), "%s/%s", ctx->output_dir, extract_name); + n = snprintf(output_path, sizeof(output_path), "%s/%s", ctx->output_dir, extract_name); } else { - snprintf(output_path, sizeof(output_path), "%s", extract_name); + n = snprintf(output_path, sizeof(output_path), "%s", extract_name); + } + if (n < 0 || (size_t) n >= sizeof(output_path)) { + print_error("Refusing to extract '%s': path too long", entry->path); + ctx->errors++; + return 0; + } + + if (has_symlink_parent(output_path)) { + print_error("Refusing to extract '%s': a parent directory is a symlink", entry->path); + ctx->errors++; + return 0; } // Extract based on entry type @@ -492,6 +621,15 @@ int cmd_extract(int argc, char* argv[]) { return 1; } + // Configure encryption before changing directory, so relative paths to + // --password-file and --keyfile resolve against the caller's directory + int enc_result = cli_apply_reader_credentials(reader, &opts.creds, 1); + cli_credentials_free(&opts.creds); + if (enc_result < 0) { + bfc_close_read(reader); + return 1; + } + // Change to output directory if specified (after opening container) if (opts.output_dir) { print_verbose("Changing to directory: %s", opts.output_dir); @@ -502,43 +640,8 @@ int cmd_extract(int argc, char* argv[]) { } } - // Configure encryption if needed -#ifdef BFC_WITH_SODIUM - if (opts.encryption_password) { - result = bfc_reader_set_encryption_password(reader, opts.encryption_password, - strlen(opts.encryption_password)); - if (result != BFC_OK) { - print_error("Failed to set encryption password: %s", bfc_error_string(result)); - bfc_close_read(reader); - return 1; - } - } else if (opts.encryption_keyfile) { - uint8_t key[32]; - if (read_key_from_file(opts.encryption_keyfile, key) != 0) { - bfc_close_read(reader); - return 1; - } - - result = bfc_reader_set_encryption_key(reader, key); - if (result != BFC_OK) { - print_error("Failed to set encryption key: %s", bfc_error_string(result)); - bfc_close_read(reader); - return 1; - } - - // Clear key from memory - memset(key, 0, sizeof(key)); - } -#else - if (opts.encryption_password || opts.encryption_keyfile) { - print_error("Encryption support not available. Please build with BFC_WITH_SODIUM=ON"); - bfc_close_read(reader); - return 1; - } -#endif - // Extract entries - extract_context_t ctx = {&opts, reader, NULL, 0, 0}; + extract_context_t ctx = {&opts, reader, NULL, 0, 0, {NULL, 0, 0}}; if (opts.num_paths == 0) { // Extract all entries @@ -555,6 +658,8 @@ int cmd_extract(int argc, char* argv[]) { } } + name_set_free(&ctx.flat_names); + if (result != BFC_OK) { print_error("Failed to list container contents: %s", bfc_error_string(result)); bfc_close_read(reader); diff --git a/src/cli/cmd_verify.c b/src/cli/cmd_verify.c index eefc47f..ee8212a 100644 --- a/src/cli/cmd_verify.c +++ b/src/cli/cmd_verify.c @@ -25,8 +25,7 @@ typedef struct { const char* container_file; int deep_verify; int show_progress; - const char* encryption_password; - const char* encryption_keyfile; + cli_credentials_t creds; } verify_options_t; static void print_verify_help(void) { @@ -34,8 +33,9 @@ static void print_verify_help(void) { printf("Verify integrity of a BFC container.\n\n"); printf("Options:\n"); printf(" --deep Perform deep verification (read and check all file contents)\n"); - printf(" -p, --progress Show progress during verification\n"); - printf(" --password PASS Password for encrypted container (needed for --deep)\n"); + printf(" --progress Show progress during verification\n"); + printf(" -p, --password PASS Password for encrypted container (needed for --deep)\n"); + printf(" --password-file FILE Read the password from FILE (- for stdin)\n"); printf(" -K, --keyfile FILE Key file for encrypted container (32 bytes)\n"); printf(" -h, --help Show this help message\n\n"); printf("Arguments:\n"); @@ -43,8 +43,8 @@ static void print_verify_help(void) { printf("Examples:\n"); printf(" bfc verify archive.bfc # Quick structural verification\n"); printf(" bfc verify --deep archive.bfc # Full content verification\n"); - printf(" bfc verify -p --deep archive.bfc # Deep verification with progress\n"); - printf(" bfc verify --deep --password secret archive.bfc # Deep verify encrypted container\n"); + printf(" bfc verify --progress --deep archive.bfc # Deep verification with progress\n"); + printf(" bfc verify --deep -p secret archive.bfc # Deep verify encrypted container\n"); } static int parse_verify_options(int argc, char* argv[], verify_options_t* opts) { @@ -52,44 +52,24 @@ static int parse_verify_options(int argc, char* argv[], verify_options_t* opts) opts->container_file = NULL; opts->deep_verify = 0; opts->show_progress = 0; - opts->encryption_password = NULL; - opts->encryption_keyfile = NULL; + cli_credentials_init(&opts->creds); - int i; + int i, cred; for (i = 1; i < argc; i++) { if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) { print_verify_help(); return 1; } else if (strcmp(argv[i], "--deep") == 0) { opts->deep_verify = 1; - } else if (strcmp(argv[i], "-p") == 0 || strcmp(argv[i], "--progress") == 0) { + } else if (strcmp(argv[i], "--progress") == 0) { opts->show_progress = 1; - } else if (strcmp(argv[i], "--password") == 0) { - if (i + 1 >= argc) { - print_error("--password requires an argument"); + } else if ((cred = cli_parse_credential_option(argc, argv, &i, &opts->creds)) != 0) { + if (cred < 0) { return -1; } - opts->encryption_password = argv[++i]; - } else if (strcmp(argv[i], "-K") == 0 || strcmp(argv[i], "--keyfile") == 0) { - if (i + 1 >= argc) { - print_error("--keyfile requires an argument"); - return -1; - } - opts->encryption_keyfile = argv[++i]; } else if (argv[i][0] == '-') { - // Handle combined short options like -p - const char* opt = argv[i] + 1; - while (*opt) { - switch (*opt) { - case 'p': - opts->show_progress = 1; - break; - default: - print_error("Unknown option: -%c", *opt); - return -1; - } - opt++; - } + print_error("Unknown option: %s", argv[i]); + return -1; } else { // Non-option argument is the container file if (!opts->container_file) { @@ -106,7 +86,7 @@ static int parse_verify_options(int argc, char* argv[], verify_options_t* opts) return -1; } - return 0; + return cli_credentials_check(&opts->creds); } // Progress callback for deep verification @@ -146,41 +126,14 @@ int cmd_verify(int argc, char* argv[]) { return 1; } - // Configure encryption if needed -#ifdef BFC_WITH_SODIUM - if (opts.encryption_password) { - result = bfc_reader_set_encryption_password(reader, opts.encryption_password, - strlen(opts.encryption_password)); - if (result != BFC_OK) { - print_error("Failed to set encryption password: %s", bfc_error_string(result)); - bfc_close_read(reader); - return 1; - } - } else if (opts.encryption_keyfile) { - uint8_t key[32]; - if (read_key_from_file(opts.encryption_keyfile, key) != 0) { - bfc_close_read(reader); - return 1; - } - - result = bfc_reader_set_encryption_key(reader, key); - - // Clear key from memory - memset(key, 0, sizeof(key)); - - if (result != BFC_OK) { - print_error("Failed to set encryption key: %s", bfc_error_string(result)); - bfc_close_read(reader); - return 1; - } - } -#else - if (opts.encryption_password || opts.encryption_keyfile) { - print_error("Encryption support not available. Please build with BFC_WITH_SODIUM=ON"); + // Configure encryption if needed. Only deep verification reads content, so + // only then is it worth prompting for a password. + int enc_result = cli_apply_reader_credentials(reader, &opts.creds, opts.deep_verify); + cli_credentials_free(&opts.creds); + if (enc_result < 0) { bfc_close_read(reader); return 1; } -#endif if (!g_options.quiet) { printf("Verifying container: %s\n", opts.container_file); @@ -240,7 +193,7 @@ int cmd_verify(int argc, char* argv[]) { print_error("The file is not a valid BFC container or is corrupted"); break; case BFC_E_CRC: - if (opts.encryption_password || opts.encryption_keyfile) { + if (enc_result > 0) { print_error("Checksum mismatch - wrong password/key or data corruption"); } else { print_error("CRC32C checksum mismatch detected - data corruption"); diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 3e157d5..d051e29 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -17,6 +17,11 @@ include(CTest) # Add unit tests add_subdirectory(unit) +# Add command-line tests (POSIX shell) +if(NOT WIN32) + add_subdirectory(cli) +endif() + # Add fuzz tests if available find_program(AFL_FUZZ afl-fuzz) if(AFL_FUZZ AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/fuzz) diff --git a/tests/cli/CMakeLists.txt b/tests/cli/CMakeLists.txt new file mode 100644 index 0000000..9cd1fbd --- /dev/null +++ b/tests/cli/CMakeLists.txt @@ -0,0 +1,32 @@ +# Copyright 2021 zombocoder (Taras Havryliak) +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# End-to-end tests of the bfc command-line tool. They need a POSIX shell and +# symlinks, so they are not built on Windows. + +add_executable(make_symlink_parent make_symlink_parent.c) +target_link_libraries(make_symlink_parent bfc) + +# The static library's dependencies may live off the default linker path +if(BFC_WITH_ZSTD) + target_link_directories(make_symlink_parent PRIVATE ${ZSTD_LIBRARY_DIRS}) +endif() +if(BFC_WITH_SODIUM) + target_link_directories(make_symlink_parent PRIVATE ${SODIUM_LIBRARY_DIRS}) +endif() + +add_test(NAME cli + COMMAND sh ${CMAKE_CURRENT_SOURCE_DIR}/test_cli.sh + $ $ +) diff --git a/tests/cli/make_symlink_parent.c b/tests/cli/make_symlink_parent.c new file mode 100644 index 0000000..86004b2 --- /dev/null +++ b/tests/cli/make_symlink_parent.c @@ -0,0 +1,54 @@ +/* + * Copyright 2021 zombocoder (Taras Havryliak) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Test helper: writes a container holding a symlink "lnk" -> and a +// file "lnk/file.txt" below it. `bfc create` never produces this layout, so +// the CLI tests use it to check that extract refuses to write through the +// symlink. +// +// usage: make_symlink_parent + +#include +#include + +int main(int argc, char** argv) { + if (argc != 3) { + fprintf(stderr, "usage: %s \n", argv[0]); + return 2; + } + + bfc_t* w = NULL; + if (bfc_create(argv[1], 4096, 0, &w) != BFC_OK) { + return 1; + } + + FILE* content = tmpfile(); + if (!content) { + bfc_close(w); + return 1; + } + fputs("written through a symlink\n", content); + rewind(content); + + uint32_t crc; + int ok = bfc_add_symlink(w, "lnk", argv[2], 0755, 0) == BFC_OK && + bfc_add_file(w, "lnk/file.txt", content, 0644, 0, &crc) == BFC_OK && + bfc_finish(w) == BFC_OK; + + fclose(content); + bfc_close(w); + return ok ? 0 : 1; +} diff --git a/tests/cli/test_cli.sh b/tests/cli/test_cli.sh new file mode 100644 index 0000000..baba63c --- /dev/null +++ b/tests/cli/test_cli.sh @@ -0,0 +1,174 @@ +#!/bin/sh +# +# Copyright 2021 zombocoder (Taras Havryliak) +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# End-to-end tests for the bfc CLI: directory paths on extract (#18) and the +# password / key-file options shared by create, extract and verify (#19). +# +# usage: test_cli.sh + +BFC=$1 +MAKE_SYMLINK_PARENT=$2 + +if [ ! -x "$BFC" ] || [ ! -x "$MAKE_SYMLINK_PARENT" ]; then + echo "usage: $0 " >&2 + exit 2 +fi + +T=$(mktemp -d "${TMPDIR:-/tmp}/bfc-cli-test.XXXXXX") || exit 2 +trap 'rm -rf "$T"' EXIT +cd "$T" || exit 2 + +failures=0 +tests=0 + +ok() { + tests=$((tests + 1)) + echo "ok - $1" +} + +not_ok() { + tests=$((tests + 1)) + failures=$((failures + 1)) + echo "not ok - $1" +} + +check() { + # check + desc=$1 + shift + if "$@" >/dev/null 2>&1; then ok "$desc"; else not_ok "$desc"; fi +} + +check_fails() { + desc=$1 + shift + if "$@" >/dev/null 2>&1; then not_ok "$desc"; else ok "$desc"; fi +} + +# Run a command and keep its stderr in $T/err for later inspection +run() { + "$@" >"$T/out" 2>"$T/err" +} + +# --- test data -------------------------------------------------------------- + +mkdir -p src/a src/b src/a/deep +echo "from a" >src/a/same.txt +echo "from b" >src/b/same.txt +echo "deep" >src/a/deep/file.txt +echo "top" >src/top.txt +"$BFC" create t.bfc src >/dev/null || { echo "Bail out! cannot create t.bfc"; exit 1; } + +# --- #18: directory paths --------------------------------------------------- + +mkdir o1 +check "extract preserves directory paths by default" \ + "$BFC" extract -C o1 t.bfc +check " src/a/same.txt has the content from src/a" grep -qx "from a" o1/src/a/same.txt +check " src/b/same.txt has the content from src/b" grep -qx "from b" o1/src/b/same.txt +check " nested src/a/deep/file.txt is extracted" test -f o1/src/a/deep/file.txt +check_fails " nothing is flattened into the output root" test -e o1/same.txt + +mkdir o2 +run "$BFC" extract -k -C o2 t.bfc +check "-k still works" test -f o2/src/a/same.txt +check " -k prints a deprecation warning" grep -q "deprecated" "$T/err" + +mkdir o3 +check_fails "--flatten fails when two entries share a name" \ + "$BFC" extract --flatten -C o3 t.bfc +mkdir o4 +check_fails "--flatten -f still refuses to overwrite one entry with another" \ + "$BFC" extract --flatten -f -C o4 t.bfc +check " the first same.txt is kept intact" grep -qx "from a" o4/same.txt + +mkdir -p u/x u/y +echo 1 >u/x/one.txt +echo 2 >u/y/two.txt +"$BFC" create u.bfc u >/dev/null +mkdir o5 +check "--flatten extracts files without collisions" \ + "$BFC" extract --flatten -C o5 u.bfc +check " files land in the output root" test -f o5/one.txt -a -f o5/two.txt +check_fails " no empty directories are created" test -d o5/u -o -d o5/x + +mkdir o6 +check "extracting a single subtree keeps its path" \ + "$BFC" extract -C o6 t.bfc src/b +check " src/b/same.txt is extracted" test -f o6/src/b/same.txt +check_fails " src/a is not extracted" test -e o6/src/a/same.txt + +# --- path safety ----------------------------------------------------------- + +mkdir outside o7 +"$MAKE_SYMLINK_PARENT" sym.bfc "$T/outside" || { echo "Bail out! make_symlink_parent"; exit 1; } +run "$BFC" extract -C o7 sym.bfc +check_fails "extract fails on an entry below a symlink" test $? -eq 0 +check " the refusal names the symlink" grep -q "symlink" "$T/err" +check_fails " nothing is written through the symlink" test -e outside/file.txt + +# --- #19: password and key-file options -------------------------------------- + +if "$BFC" create -p x probe.bfc src/top.txt 2>&1 | grep -q "Encryption support not available"; then + echo "# bfc built without libsodium: skipping encryption tests" +else + printf 'secret\n' >pass.txt + printf '0123456789abcdef0123456789abcdef' >key.bin + + check "create -p encrypts with a password" "$BFC" create -p secret p.bfc src + check "create --password encrypts with a password" "$BFC" create --password secret p2.bfc src + check "create --password-file reads the password from a file" \ + "$BFC" create --password-file pass.txt pf.bfc src + check "create -K encrypts with a key file" "$BFC" create -K key.bin k.bfc src + + run "$BFC" create -e secret e.bfc src + check "create -e still works" test -f e.bfc + check " -e prints a deprecation warning" grep -q "deprecated" "$T/err" + run "$BFC" create -k key.bin kold.bfc src + check "create -k (key file) still works" test -f kold.bfc + check " -k prints a deprecation warning" grep -q "deprecated" "$T/err" + + check_fails "create rejects a password and a key file together" \ + "$BFC" create -p secret -K key.bin both.bfc src + + mkdir x1 x2 x3 x4 x5 + check "extract -p decrypts" "$BFC" extract -p secret -C x1 p.bfc + check " content is correct" grep -qx "from a" x1/src/a/same.txt + check "extract --password-file decrypts" "$BFC" extract --password-file pass.txt -C x2 pf.bfc + check "extract -K decrypts" "$BFC" extract -K key.bin -C x3 k.bfc + check "extract reads --password-file from stdin" \ + sh -c "printf 'secret\n' | '$BFC' extract --password-file - -C x4 p.bfc" + check_fails "extract with a wrong password fails" "$BFC" extract -p wrong -C x5 p.bfc + check_fails "extract without credentials fails without waiting for input" \ + sh -c "'$BFC' extract -C x5 p.bfc ' fails loudly" test $? -eq 0 +fi + +echo "1..$tests" +if [ "$failures" -ne 0 ]; then + echo "# $failures of $tests checks failed" + exit 1 +fi +echo "# all $tests checks passed"