Files
Library/tests/standalone/Archive/Archive.cpp

341 lines
11 KiB
C++

#include <Void/Archive/Archive.hpp>
#include <Void/System/TempDir.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <algorithm>
#include <array>
#include <atomic>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <memory>
#include <span>
#include <string>
#include <string_view>
#include <system_error>
#include <thread>
#include <vector>
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
#include <archive.h>
#include <archive_entry.h>
#endif
namespace
{
enum class FixtureEntryType { Regular, Directory, Symlink };
struct ArchiveEntry {
std::string_view path;
std::string_view contents;
FixtureEntryType type{FixtureEntryType::Regular};
std::string_view link;
};
void write_octal(std::span<char> dst, std::uint64_t val)
{
dst.back() = '\0';
std::size_t pos = dst.size() - 1;
while (pos > 0) {
--pos;
dst[pos] = static_cast<char>('0' + (val & 7ULL));
val >>= 3ULL;
}
}
void write_raw_tar(const std::filesystem::path& path,
std::span<const ArchiveEntry> entries)
{
std::ofstream out{path, std::ios::binary | std::ios::trunc};
Void::Testing::require(out.is_open());
for (const auto& spec : entries) {
std::array<char, 512> hdr{};
std::memcpy(hdr.data(), spec.path.data(),
std::min<std::size_t>(spec.path.size(), 100));
const std::uint32_t perm =
spec.type == FixtureEntryType::Directory ? 0755U : 0644U;
write_octal(std::span{hdr}.subspan(100, 8), perm);
write_octal(std::span{hdr}.subspan(108, 8), 0);
write_octal(std::span{hdr}.subspan(116, 8), 0);
const std::uint64_t sz =
spec.type == FixtureEntryType::Regular ? spec.contents.size()
: 0ULL;
write_octal(std::span{hdr}.subspan(124, 12), sz);
write_octal(std::span{hdr}.subspan(136, 12), 0);
std::fill(hdr.begin() + 148, hdr.begin() + 156, ' ');
hdr[156] = spec.type == FixtureEntryType::Directory
? '5'
: (spec.type == FixtureEntryType::Symlink ? '2' : '0');
if (!spec.link.empty()) {
std::memcpy(hdr.data() + 157, spec.link.data(),
std::min<std::size_t>(spec.link.size(), 100));
}
std::memcpy(hdr.data() + 257, "ustar\0", 6);
hdr[263] = '0';
hdr[264] = '0';
std::uint32_t sum = 0;
for (const char ch : hdr) {
sum += static_cast<unsigned char>(ch);
}
write_octal(std::span{hdr}.subspan(148, 7), sum);
hdr[155] = ' ';
out.write(hdr.data(), hdr.size());
if (spec.type == FixtureEntryType::Regular && !spec.contents.empty()) {
out.write(spec.contents.data(),
static_cast<std::streamsize>(spec.contents.size()));
const std::size_t rem = spec.contents.size() % 512U;
if (rem != 0) {
std::array<char, 512> pad{};
out.write(pad.data(),
static_cast<std::streamsize>(512U - rem));
}
}
}
std::array<char, 1024> eof{};
out.write(eof.data(), eof.size());
out.close();
Void::Testing::require(out.good());
}
void write_archive(const std::filesystem::path& path,
std::span<const ArchiveEntry> entries)
{
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
using Writer = std::unique_ptr<archive, decltype(&archive_write_free)>;
using Entry =
std::unique_ptr<archive_entry, decltype(&archive_entry_free)>;
Writer writer{archive_write_new(), &archive_write_free};
Void::Testing::require(static_cast<bool>(writer));
Void::Testing::require(archive_write_add_filter_zstd(writer.get()) ==
ARCHIVE_OK);
Void::Testing::require(archive_write_set_format_pax_restricted(
writer.get()) == ARCHIVE_OK);
#ifdef _WIN32
Void::Testing::require(archive_write_open_filename_w(
writer.get(), path.c_str()) == ARCHIVE_OK);
#else
Void::Testing::require(archive_write_open_filename(
writer.get(), path.c_str()) == ARCHIVE_OK);
#endif
for (const auto& specification : entries) {
Entry entry{archive_entry_new(), &archive_entry_free};
const std::string entryPath{specification.path};
archive_entry_set_pathname(entry.get(), entryPath.c_str());
const unsigned int ae_type =
specification.type == FixtureEntryType::Directory
? AE_IFDIR
: (specification.type == FixtureEntryType::Symlink
? AE_IFLNK
: AE_IFREG);
archive_entry_set_filetype(entry.get(), ae_type);
archive_entry_set_perm(
entry.get(),
specification.type == FixtureEntryType::Directory ? 0755 : 0644);
if (specification.type == FixtureEntryType::Regular) {
archive_entry_set_size(
entry.get(),
static_cast<la_int64_t>(specification.contents.size()));
}
if (!specification.link.empty()) {
const std::string link{specification.link};
archive_entry_set_symlink(entry.get(), link.c_str());
}
Void::Testing::require(
archive_write_header(writer.get(), entry.get()) == ARCHIVE_OK);
std::size_t offset = 0;
while (offset < specification.contents.size()) {
const auto count = archive_write_data(
writer.get(), specification.contents.data() + offset,
specification.contents.size() - offset);
Void::Testing::require(count > 0);
offset += static_cast<std::size_t>(count);
}
Void::Testing::require(archive_write_finish_entry(writer.get()) ==
ARCHIVE_OK);
}
Void::Testing::require(archive_write_close(writer.get()) == ARCHIVE_OK);
#else
write_raw_tar(path, entries);
#endif
}
void write_archive(const std::filesystem::path& path,
std::string_view entryPath, std::string_view contents,
FixtureEntryType type = FixtureEntryType::Regular,
std::string_view link = {})
{
const std::array entries{ArchiveEntry{entryPath, contents, type, link}};
write_archive(path, entries);
}
[[nodiscard]] bool
extraction_file_visible(const std::filesystem::path& destination)
{
std::error_code error;
if (std::filesystem::exists(destination / "anchor", error)) {
return true;
}
error.clear();
for (std::filesystem::directory_iterator iterator{destination, error};
!error && iterator != std::filesystem::directory_iterator{};
iterator.increment(error)) {
if (iterator->path().filename().string().starts_with(
".void-archive-")) {
return true;
}
}
return false;
}
} // namespace
Void::Testing::Test archive_extracts_bounded_tar_zstd()
{
Void::FileSystem::TempDir temporary{"void_archive_"};
const auto source = temporary / "package.tar.zst";
const auto destination = temporary / "output";
write_archive(source, "bin/tool", "payload");
auto extracted = Void::Archive::extract(source, destination);
Void::Testing::require(extracted.has_value());
Void::Testing::expect_eq(extracted->entries, std::size_t{1});
Void::Testing::expect_eq(extracted->bytes, std::uint64_t{7});
std::ifstream input{destination / "bin/tool"};
std::string contents;
input >> contents;
Void::Testing::expect_eq(contents, std::string{"payload"});
}
Void::Testing::Test archive_accepts_explicit_directory_entries()
{
Void::FileSystem::TempDir temporary{"void_archive_"};
const auto source = temporary / "directory.tar.zst";
const auto destination = temporary / "output";
const std::array entries{
ArchiveEntry{"bin/", {}, FixtureEntryType::Directory},
ArchiveEntry{"bin/tool", "payload"}};
write_archive(source, entries);
auto extracted = Void::Archive::extract(source, destination);
Void::Testing::require(extracted.has_value());
Void::Testing::expect_eq(extracted->entries, std::size_t{2});
Void::Testing::expect_eq(extracted->bytes, std::uint64_t{7});
Void::Testing::expect(std::filesystem::is_directory(destination / "bin"));
std::ifstream input{destination / "bin/tool"};
std::string contents;
input >> contents;
Void::Testing::expect_eq(contents, std::string{"payload"});
}
Void::Testing::Test archive_rejects_traversal_and_links()
{
Void::FileSystem::TempDir temporary{"void_archive_"};
const auto traversal = temporary / "traversal.tar.zst";
write_archive(traversal, "../escape", "bad");
Void::Testing::expect(
!Void::Archive::extract(traversal, temporary / "out1").has_value());
Void::Testing::expect(
!std::filesystem::exists(temporary.path() / "escape"));
const auto symlink = temporary / "symlink.tar.zst";
write_archive(symlink, "link", {}, FixtureEntryType::Symlink,
"/tmp/escape");
Void::Testing::expect(
!Void::Archive::extract(symlink, temporary / "out2").has_value());
const auto trailingFile = temporary / "trailing-file.tar.zst";
write_archive(trailingFile, "file/", "bad");
Void::Testing::expect(
!Void::Archive::extract(trailingFile, temporary / "out3").has_value());
}
Void::Testing::Test archive_rejects_symlink_parent()
{
#ifndef _WIN32
Void::FileSystem::TempDir temporary{"void_archive_"};
const auto source = temporary / "parent-link.tar.zst";
const auto destination = temporary / "output";
const auto outside = temporary / "outside";
std::filesystem::create_directories(destination);
std::filesystem::create_directories(outside);
std::filesystem::create_directory_symlink(outside, destination / "parent");
write_archive(source, "parent/escape", "bad");
Void::Testing::expect(
!Void::Archive::extract(source, destination).has_value());
Void::Testing::expect(!std::filesystem::exists(outside / "escape"));
#else
Void::Testing::expect(true);
#endif
}
Void::Testing::Test archive_pins_destination_during_path_swap()
{
#ifndef _WIN32
Void::FileSystem::TempDir temporary{"void_archive_"};
const auto source = temporary / "swap.tar.zst";
const auto destination = temporary / "output";
const auto displaced = temporary / "displaced";
const auto outside = temporary / "outside";
std::filesystem::create_directories(destination);
std::filesystem::create_directories(outside);
const std::string largePayload(32U * 1024U * 1024U, 'x');
const std::array entries{ArchiveEntry{"anchor", largePayload},
ArchiveEntry{"second", "safe"}};
write_archive(source, entries);
std::atomic_bool extractionFinished{false};
std::atomic_bool swapped{false};
std::jthread attacker{[&] {
while (!extractionFinished.load(std::memory_order_acquire)) {
if (!extraction_file_visible(destination)) {
std::this_thread::yield();
continue;
}
std::error_code error;
std::filesystem::rename(destination, displaced, error);
if (error) {
return;
}
std::filesystem::create_directory_symlink(outside, destination,
error);
if (error) {
std::error_code restoreError;
std::filesystem::rename(displaced, destination, restoreError);
return;
}
swapped.store(true, std::memory_order_release);
return;
}
}};
auto extracted = Void::Archive::extract(source, destination);
extractionFinished.store(true, std::memory_order_release);
attacker.join();
Void::Testing::require(swapped.load(std::memory_order_acquire));
Void::Testing::require(extracted.has_value());
Void::Testing::expect(!std::filesystem::exists(outside / "second"));
Void::Testing::expect(std::filesystem::exists(displaced / "second"));
#else
Void::Testing::expect(true);
#endif
}
Void::Testing::Test archive_enforces_actual_size_limit()
{
Void::FileSystem::TempDir temporary{"void_archive_"};
const auto source = temporary / "large.tar.zst";
write_archive(source, "file", "12345678");
Void::Archive::ExtractionOptions options;
options.maxFileBytes = 4;
Void::Testing::expect(
!Void::Archive::extract(source, temporary / "out", options)
.has_value());
Void::Testing::expect(
!std::filesystem::exists(temporary.path() / "out/file"));
}