feat(crypto,archive): implement VL-007 built-in hashes and VL-006 archive creation/gzip/tar fallback
This commit is contained in:
1 parent
b50131f52e
commit
22c8538754
19 files changed
+3326
-133
No files matched your search
@@ -29,9 +29,14 @@ namespace Void::Archive
|
||||
std::uint64_t bytes{0};
|
||||
};
|
||||
|
||||
/// Extract a tar/tar.zst archive incrementally into `destination` without
|
||||
/// invoking an external process. Preserved 1.x incremental API; callers
|
||||
/// requiring all-or-nothing directory visibility should use
|
||||
/// Returns true if Void::Archive was built with LibArchive support (required
|
||||
/// for .tar.zst and .tar.gz compression/decompression; uncompressed USTAR/PAX
|
||||
/// .tar reading and writing work with zero external dependencies).
|
||||
[[nodiscard]] bool has_libarchive_backend() noexcept;
|
||||
|
||||
/// Extract a tar/tar.gz/tar.zst archive incrementally into `destination`
|
||||
/// without invoking an external process. Preserved 1.x incremental API;
|
||||
/// callers requiring all-or-nothing directory visibility should use
|
||||
/// `extract_staged` + `StagedTree::publish`.
|
||||
[[nodiscard]] Void::Result::Result<ExtractionResult>
|
||||
extract(const std::filesystem::path& archivePath,
|
||||
@@ -177,9 +182,9 @@ namespace Void::Archive
|
||||
std::chrono::seconds min_age =
|
||||
std::chrono::seconds{300});
|
||||
|
||||
/// Create a bounded, optionally reproducible tar or tar.zst archive from
|
||||
/// regular file and directory entries. Sorts normalized paths, rejects
|
||||
/// duplicates/conflicts, and opens source files with O_NOFOLLOW.
|
||||
/// Create a bounded, optionally reproducible tar, tar.gz, or tar.zst
|
||||
/// archive from regular file and directory entries. Sorts normalized
|
||||
/// paths, rejects duplicates/conflicts, and opens source files with O_NOFOLLOW.
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
create_archive(ByteSink& sink, std::span<const CreateEntry> entries,
|
||||
const CreationOptions& options = {});
|
||||
@@ -189,6 +194,16 @@ namespace Void::Archive
|
||||
std::span<const CreateEntry> entries,
|
||||
const CreationOptions& options = {});
|
||||
|
||||
/// Canonical snake_case alias for `create_archive`.
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
create(ByteSink& sink, std::span<const CreateEntry> entries,
|
||||
const CreationOptions& options = {});
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
create(const std::filesystem::path& output_path,
|
||||
std::span<const CreateEntry> entries,
|
||||
const CreationOptions& options = {});
|
||||
|
||||
/// Hardened untrusted-input profile: extracts the archive in an isolated
|
||||
/// System child process with bounded execution time and RSS checks, then
|
||||
/// independently verifies the staged tree and inventory in the parent
|
||||
|
||||
@@ -175,13 +175,17 @@ namespace Void::Archive
|
||||
ProgressCallback on_progress{};
|
||||
};
|
||||
|
||||
enum class ArchiveCompression : std::uint8_t { None = 0, Zstd };
|
||||
enum class ArchiveCompression : std::uint8_t { None = 0, Zstd, Gzip };
|
||||
|
||||
struct CreationOptions {
|
||||
ArchiveCompression compression{ArchiveCompression::Zstd};
|
||||
bool reproducible{true};
|
||||
ReadLimits limits{};
|
||||
std::stop_token stop{};
|
||||
std::int64_t canonical_mtime{0};
|
||||
std::uint32_t canonical_uid{0};
|
||||
std::uint32_t canonical_gid{0};
|
||||
bool prefer_builtin_tar{false};
|
||||
};
|
||||
|
||||
struct CreateEntry {
|
||||
@@ -190,6 +194,7 @@ namespace Void::Archive
|
||||
bool executable{false};
|
||||
std::vector<std::byte> content{};
|
||||
std::optional<std::filesystem::path> source_file{};
|
||||
std::optional<std::uint32_t> mode{};
|
||||
};
|
||||
|
||||
struct IsolationOptions {
|
||||
|
||||
@@ -13,9 +13,14 @@
|
||||
|
||||
namespace Void::Crypto
|
||||
{
|
||||
enum class HashAlgorithm { Sha1, Sha256, Sha512 };
|
||||
enum class HashAlgorithm { Sha1, Sha256, Sha512, Blake2b256, Blake2b512 };
|
||||
using Digest = std::vector<std::byte>;
|
||||
|
||||
/// Returns true if Void::Crypto was built with OpenSSL support (required
|
||||
/// for Ed25519; hashing/HMAC/HKDF work on the built-in pure-C++ backend
|
||||
/// with zero external dependencies).
|
||||
[[nodiscard]] bool has_openssl_backend() noexcept;
|
||||
|
||||
class Hasher
|
||||
{
|
||||
public:
|
||||
@@ -60,6 +65,11 @@ namespace Void::Crypto
|
||||
[[nodiscard]] Void::Result::Result<Digest>
|
||||
hashFile(HashAlgorithm algorithm, const std::filesystem::path& path,
|
||||
const ProviderOptions& provider);
|
||||
[[nodiscard]] Void::Result::Result<Digest>
|
||||
hash_file(HashAlgorithm algorithm, const std::filesystem::path& path);
|
||||
[[nodiscard]] Void::Result::Result<Digest>
|
||||
hash_file(HashAlgorithm algorithm, const std::filesystem::path& path,
|
||||
const ProviderOptions& provider);
|
||||
|
||||
[[nodiscard]] Void::Result::Result<Digest>
|
||||
sha1(std::span<const std::byte> data);
|
||||
@@ -70,12 +80,29 @@ namespace Void::Crypto
|
||||
[[nodiscard]] Void::Result::Result<Digest>
|
||||
sha512(std::span<const std::byte> data);
|
||||
[[nodiscard]] Void::Result::Result<Digest> sha512(std::string_view data);
|
||||
[[nodiscard]] Void::Result::Result<Digest>
|
||||
blake2b256(std::span<const std::byte> data);
|
||||
[[nodiscard]] Void::Result::Result<Digest> blake2b256(std::string_view data);
|
||||
[[nodiscard]] Void::Result::Result<Digest>
|
||||
blake2b512(std::span<const std::byte> data);
|
||||
[[nodiscard]] Void::Result::Result<Digest> blake2b512(std::string_view data);
|
||||
|
||||
[[nodiscard]] Void::Result::Result<Digest>
|
||||
sha1File(const std::filesystem::path& path);
|
||||
[[nodiscard]] Void::Result::Result<Digest>
|
||||
sha256File(const std::filesystem::path& path);
|
||||
[[nodiscard]] Void::Result::Result<Digest>
|
||||
sha512File(const std::filesystem::path& path);
|
||||
[[nodiscard]] Void::Result::Result<Digest>
|
||||
sha1_file(const std::filesystem::path& path);
|
||||
[[nodiscard]] Void::Result::Result<Digest>
|
||||
sha256_file(const std::filesystem::path& path);
|
||||
[[nodiscard]] Void::Result::Result<Digest>
|
||||
sha512_file(const std::filesystem::path& path);
|
||||
[[nodiscard]] Void::Result::Result<Digest>
|
||||
blake2b256_file(const std::filesystem::path& path);
|
||||
[[nodiscard]] Void::Result::Result<Digest>
|
||||
blake2b512_file(const std::filesystem::path& path);
|
||||
|
||||
/// Move-only owning Ed25519 private key handle. Has no implicit copy,
|
||||
/// string conversion, or secret formatting.
|
||||
|
||||
@@ -111,10 +111,11 @@ namespace Void::Crypto
|
||||
MovedFrom
|
||||
};
|
||||
|
||||
/// Per-operation OpenSSL 3 provider selection. Never mutates process-wide
|
||||
/// Per-operation backend/provider selection. Never mutates process-wide
|
||||
/// provider state.
|
||||
struct ProviderOptions {
|
||||
std::string property_query{};
|
||||
bool prefer_builtin{false};
|
||||
};
|
||||
|
||||
struct Ed25519PublicKey {
|
||||
|
||||
+148
-30
@@ -1,10 +1,13 @@
|
||||
#include <Void/Archive/Archive.hpp>
|
||||
|
||||
#include "BuiltinTar.hpp"
|
||||
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <cerrno>
|
||||
#include <cstring>
|
||||
#include <format>
|
||||
#include <limits>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <set>
|
||||
@@ -13,8 +16,10 @@
|
||||
#include <system_error>
|
||||
#include <utility>
|
||||
|
||||
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
|
||||
#include <archive.h>
|
||||
#include <archive_entry.h>
|
||||
#endif
|
||||
|
||||
#ifndef _WIN32
|
||||
#include <fcntl.h>
|
||||
@@ -28,6 +33,7 @@ namespace Void::Archive
|
||||
{
|
||||
namespace
|
||||
{
|
||||
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
|
||||
using ArchiveHandle =
|
||||
std::unique_ptr<archive, decltype(&archive_read_free)>;
|
||||
|
||||
@@ -39,6 +45,7 @@ namespace Void::Archive
|
||||
"Archive::extract: {}: {}", operation,
|
||||
message == nullptr ? "unknown archive error" : message)};
|
||||
}
|
||||
#endif
|
||||
|
||||
[[nodiscard]] std::optional<std::filesystem::path>
|
||||
safe_relative_path(std::string_view rawPath, bool directory)
|
||||
@@ -225,12 +232,14 @@ namespace Void::Archive
|
||||
return {};
|
||||
}
|
||||
|
||||
template <typename ReadFn>
|
||||
[[nodiscard]] Void::Result::Result<std::uint64_t>
|
||||
extract_regular(archive *reader, int rootDescriptor,
|
||||
const std::filesystem::path &relative,
|
||||
const std::filesystem::path &displayRoot,
|
||||
const ExtractionOptions &options,
|
||||
std::uint64_t alreadyExtracted, bool executable)
|
||||
extract_regular_stream(int rootDescriptor,
|
||||
const std::filesystem::path &relative,
|
||||
const std::filesystem::path &displayRoot,
|
||||
const ExtractionOptions &options,
|
||||
std::uint64_t alreadyExtracted,
|
||||
bool executable, ReadFn &&read_fn)
|
||||
{
|
||||
auto openedParent = open_parent_directory(
|
||||
rootDescriptor, relative.parent_path(), displayRoot);
|
||||
@@ -286,15 +295,14 @@ namespace Void::Archive
|
||||
std::array<std::byte, 64 * 1024> buffer{};
|
||||
std::uint64_t fileBytes = 0;
|
||||
for (;;) {
|
||||
const auto count =
|
||||
archive_read_data(reader, buffer.data(), buffer.size());
|
||||
if (count == 0) {
|
||||
auto chunk = read_fn(std::span{buffer});
|
||||
if (!chunk.has_value()) {
|
||||
return fail(chunk.error().message());
|
||||
}
|
||||
if (*chunk == 0) {
|
||||
break;
|
||||
}
|
||||
if (count < 0) {
|
||||
return fail(archive_error(reader, "read entry").message());
|
||||
}
|
||||
const auto amount = static_cast<std::uint64_t>(count);
|
||||
const auto amount = static_cast<std::uint64_t>(*chunk);
|
||||
if (amount > options.maxFileBytes - fileBytes ||
|
||||
amount >
|
||||
options.maxTotalBytes - alreadyExtracted - fileBytes) {
|
||||
@@ -303,11 +311,11 @@ namespace Void::Archive
|
||||
}
|
||||
|
||||
std::size_t written = 0;
|
||||
while (written < static_cast<std::size_t>(count)) {
|
||||
while (written < *chunk) {
|
||||
const auto result = ::write(
|
||||
descriptor.get(),
|
||||
reinterpret_cast<const char *>(buffer.data()) + written,
|
||||
static_cast<std::size_t>(count) - written);
|
||||
*chunk - written);
|
||||
if (result < 0 && errno == EINTR) {
|
||||
continue;
|
||||
}
|
||||
@@ -448,10 +456,12 @@ namespace Void::Archive
|
||||
return {};
|
||||
}
|
||||
|
||||
template <typename ReadFn>
|
||||
[[nodiscard]] Void::Result::Result<std::uint64_t>
|
||||
extract_regular(archive *reader, const std::filesystem::path &path,
|
||||
const ExtractionOptions &options,
|
||||
std::uint64_t alreadyExtracted)
|
||||
extract_regular_stream(const std::filesystem::path &path,
|
||||
const ExtractionOptions &options,
|
||||
std::uint64_t alreadyExtracted,
|
||||
ReadFn &&read_fn)
|
||||
{
|
||||
std::error_code error;
|
||||
const auto status = std::filesystem::symlink_status(path, error);
|
||||
@@ -486,15 +496,14 @@ namespace Void::Archive
|
||||
std::array<std::byte, 64 * 1024> buffer{};
|
||||
std::uint64_t fileBytes = 0;
|
||||
for (;;) {
|
||||
const auto count =
|
||||
archive_read_data(reader, buffer.data(), buffer.size());
|
||||
if (count == 0) {
|
||||
auto chunk = read_fn(std::span{buffer});
|
||||
if (!chunk.has_value()) {
|
||||
return fail(chunk.error().message());
|
||||
}
|
||||
if (*chunk == 0) {
|
||||
break;
|
||||
}
|
||||
if (count < 0) {
|
||||
return fail(archive_error(reader, "read entry").message());
|
||||
}
|
||||
const auto amount = static_cast<std::uint64_t>(count);
|
||||
const auto amount = static_cast<std::uint64_t>(*chunk);
|
||||
if (amount > options.maxFileBytes - fileBytes ||
|
||||
amount >
|
||||
options.maxTotalBytes - alreadyExtracted - fileBytes) {
|
||||
@@ -502,7 +511,7 @@ namespace Void::Archive
|
||||
"Archive::extract: extracted size exceeds policy");
|
||||
}
|
||||
output.write(reinterpret_cast<const char *>(buffer.data()),
|
||||
count);
|
||||
static_cast<std::streamsize>(*chunk));
|
||||
if (!output) {
|
||||
return fail("Archive::extract: write failed");
|
||||
}
|
||||
@@ -544,11 +553,13 @@ namespace Void::Archive
|
||||
}
|
||||
#endif
|
||||
|
||||
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
|
||||
ArchiveHandle reader{archive_read_new(), &archive_read_free};
|
||||
if (!reader) {
|
||||
return Void::Result::fail(
|
||||
"Archive::extract: cannot allocate archive reader");
|
||||
}
|
||||
archive_read_support_filter_gzip(reader.get());
|
||||
archive_read_support_filter_zstd(reader.get());
|
||||
archive_read_support_filter_none(reader.get());
|
||||
archive_read_support_format_tar(reader.get());
|
||||
@@ -633,14 +644,23 @@ namespace Void::Archive
|
||||
return Void::Result::fail(
|
||||
"Archive::extract: declared entry size exceeds policy");
|
||||
}
|
||||
auto read_libarchive_chunk =
|
||||
[&](std::span<std::byte> dst) -> Void::Result::Result<std::size_t> {
|
||||
const auto count =
|
||||
archive_read_data(reader.get(), dst.data(), dst.size());
|
||||
if (count < 0) {
|
||||
return std::unexpected{archive_error(reader.get(), "read entry")};
|
||||
}
|
||||
return static_cast<std::size_t>(count);
|
||||
};
|
||||
#ifndef _WIN32
|
||||
const bool executable = (archive_entry_perm(entry) & 0111) != 0;
|
||||
auto extracted =
|
||||
extract_regular(reader.get(), root->get(), *relative,
|
||||
destination, options, result.bytes, executable);
|
||||
auto extracted = extract_regular_stream(
|
||||
root->get(), *relative, destination, options, result.bytes,
|
||||
executable, read_libarchive_chunk);
|
||||
#else
|
||||
auto extracted =
|
||||
extract_regular(reader.get(), output, options, result.bytes);
|
||||
auto extracted = extract_regular_stream(
|
||||
output, options, result.bytes, read_libarchive_chunk);
|
||||
#endif
|
||||
if (!extracted) {
|
||||
return std::unexpected{extracted.error()};
|
||||
@@ -648,5 +668,103 @@ namespace Void::Archive
|
||||
result.bytes += *extracted;
|
||||
}
|
||||
return result;
|
||||
#else
|
||||
auto source = FileByteSource::open(archivePath);
|
||||
if (!source.has_value()) {
|
||||
return std::unexpected{std::move(source.error())};
|
||||
}
|
||||
ReadLimits limits;
|
||||
limits.max_entries = options.maxEntries;
|
||||
limits.max_file_bytes = options.maxFileBytes;
|
||||
limits.max_total_bytes = options.maxTotalBytes;
|
||||
limits.max_compressed_bytes = std::numeric_limits<std::uint64_t>::max();
|
||||
Detail::BuiltinTarStream stream{
|
||||
*source, limits, {}, std::nullopt,
|
||||
Void::Time::SystemMonotonicClock::instance()};
|
||||
if (auto opened = stream.open(); !opened.has_value()) {
|
||||
return std::unexpected{std::move(opened.error())};
|
||||
}
|
||||
|
||||
ExtractionResult result;
|
||||
std::set<std::filesystem::path> seen;
|
||||
for (;;) {
|
||||
auto next = stream.next_entry();
|
||||
if (!next.has_value()) {
|
||||
return std::unexpected{std::move(next.error())};
|
||||
}
|
||||
if (!next->has_value()) {
|
||||
break;
|
||||
}
|
||||
if (++result.entries > options.maxEntries) {
|
||||
return Void::Result::fail(
|
||||
"Archive::extract: entry count exceeds policy");
|
||||
}
|
||||
|
||||
const auto &entry = **next;
|
||||
if (entry.type == EntryType::Hardlink ||
|
||||
entry.type == EntryType::Symlink || !entry.linkname.empty()) {
|
||||
return Void::Result::fail(
|
||||
"Archive::extract: links are not allowed");
|
||||
}
|
||||
if (entry.type != EntryType::Directory &&
|
||||
entry.type != EntryType::RegularFile) {
|
||||
return Void::Result::fail(
|
||||
"Archive::extract: special files are not allowed");
|
||||
}
|
||||
const bool is_dir = (entry.type == EntryType::Directory);
|
||||
auto relative = safe_relative_path(entry.path, is_dir);
|
||||
if (!relative || !seen.insert(*relative).second) {
|
||||
return Void::Result::fail(std::format(
|
||||
"Archive::extract: unsafe or duplicate path '{}'",
|
||||
entry.path));
|
||||
}
|
||||
|
||||
#ifdef _WIN32
|
||||
if (auto parents = safe_parents(root, relative->parent_path());
|
||||
!parents) {
|
||||
return std::unexpected{parents.error()};
|
||||
}
|
||||
const auto output = root / *relative;
|
||||
#endif
|
||||
if (is_dir) {
|
||||
#ifndef _WIN32
|
||||
auto created =
|
||||
create_directory_entry(root->get(), *relative, destination,
|
||||
options.overwriteExisting);
|
||||
#else
|
||||
auto created =
|
||||
create_directory_entry(output, options.overwriteExisting);
|
||||
#endif
|
||||
if (!created) {
|
||||
return std::unexpected{created.error()};
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (entry.declared_size > options.maxFileBytes ||
|
||||
entry.declared_size > options.maxTotalBytes - result.bytes) {
|
||||
return Void::Result::fail(
|
||||
"Archive::extract: declared entry size exceeds policy");
|
||||
}
|
||||
auto read_builtin_chunk =
|
||||
[&](std::span<std::byte> dst) -> Void::Result::Result<std::size_t> {
|
||||
return stream.read_entry_data(dst);
|
||||
};
|
||||
#ifndef _WIN32
|
||||
const bool executable = (entry.mode & 0111U) != 0U;
|
||||
auto extracted = extract_regular_stream(
|
||||
root->get(), *relative, destination, options, result.bytes,
|
||||
executable, read_builtin_chunk);
|
||||
#else
|
||||
auto extracted = extract_regular_stream(
|
||||
output, options, result.bytes, read_builtin_chunk);
|
||||
#endif
|
||||
if (!extracted) {
|
||||
return std::unexpected{extracted.error()};
|
||||
}
|
||||
result.bytes += *extracted;
|
||||
}
|
||||
return result;
|
||||
#endif
|
||||
}
|
||||
} // namespace Void::Archive
|
||||
@@ -0,0 +1,867 @@
|
||||
#include "BuiltinTar.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cerrno>
|
||||
#include <charconv>
|
||||
#include <chrono>
|
||||
#include <cstring>
|
||||
#include <format>
|
||||
#include <string_view>
|
||||
|
||||
#ifndef _WIN32
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
namespace Void::Archive::Detail
|
||||
{
|
||||
namespace
|
||||
{
|
||||
constexpr std::size_t kTarBlockSize = 512;
|
||||
|
||||
[[nodiscard]] bool is_zero_block(const std::array<std::byte, kTarBlockSize>& block) noexcept
|
||||
{
|
||||
for (const std::byte b : block) {
|
||||
if (b != std::byte{0}) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
inline void write_octal(std::span<std::byte> field, std::uint64_t value) noexcept
|
||||
{
|
||||
if (field.size() < 2) {
|
||||
return;
|
||||
}
|
||||
field.back() = std::byte{0};
|
||||
std::size_t pos = field.size() - 1;
|
||||
while (pos > 0) {
|
||||
--pos;
|
||||
field[pos] = static_cast<std::byte>('0' + (value & 7ULL));
|
||||
value >>= 3ULL;
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::uint64_t>
|
||||
parse_octal(std::span<const std::byte> field, const char* name)
|
||||
{
|
||||
const auto* p = reinterpret_cast<const unsigned char*>(field.data());
|
||||
std::size_t n = field.size();
|
||||
if (n > 0 && (p[0] & 0x80U) != 0U) {
|
||||
// POSIX / GNU big-endian base-256 unsigned extension.
|
||||
if ((p[0] & 0x40U) != 0U) {
|
||||
return std::unexpected{make_archive_error(
|
||||
ArchiveErrorCode::corrupt_archive,
|
||||
std::format("Archive: negative base-256 field '{}'",
|
||||
name))};
|
||||
}
|
||||
std::uint64_t v = static_cast<std::uint64_t>(p[0] & 0x3FU);
|
||||
for (std::size_t i = 1; i < n; ++i) {
|
||||
if (v > (std::numeric_limits<std::uint64_t>::max() >> 8U)) {
|
||||
return std::unexpected{make_archive_error(
|
||||
ArchiveErrorCode::corrupt_archive,
|
||||
std::format("Archive: overflowing field '{}'",
|
||||
name))};
|
||||
}
|
||||
v = (v << 8U) | static_cast<std::uint64_t>(p[i]);
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
std::size_t i = 0;
|
||||
while (i < n && (p[i] == ' ' || p[i] == '\0')) {
|
||||
++i;
|
||||
}
|
||||
if (i == n) {
|
||||
return std::uint64_t{0};
|
||||
}
|
||||
std::uint64_t out = 0;
|
||||
bool saw_digit = false;
|
||||
for (; i < n; ++i) {
|
||||
if (p[i] == '\0' || p[i] == ' ') {
|
||||
break;
|
||||
}
|
||||
if (p[i] < '0' || p[i] > '7') {
|
||||
return std::unexpected{make_archive_error(
|
||||
ArchiveErrorCode::corrupt_archive,
|
||||
std::format("Archive: invalid octal character in '{}'",
|
||||
name))};
|
||||
}
|
||||
if (out > (std::numeric_limits<std::uint64_t>::max() >> 3U)) {
|
||||
return std::unexpected{make_archive_error(
|
||||
ArchiveErrorCode::corrupt_archive,
|
||||
std::format("Archive: octal overflow in '{}'", name))};
|
||||
}
|
||||
out = (out << 3U) | static_cast<std::uint64_t>(p[i] - '0');
|
||||
saw_digit = true;
|
||||
}
|
||||
if (!saw_digit) {
|
||||
return std::uint64_t{0};
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string_view
|
||||
c_field(std::span<const std::byte> field) noexcept
|
||||
{
|
||||
const char* s = reinterpret_cast<const char*>(field.data());
|
||||
std::size_t len = 0;
|
||||
while (len < field.size() && s[len] != '\0') {
|
||||
++len;
|
||||
}
|
||||
return {s, len};
|
||||
}
|
||||
|
||||
[[nodiscard]] std::uint32_t
|
||||
compute_checksum_unsigned(const std::array<std::byte, kTarBlockSize>& block) noexcept
|
||||
{
|
||||
std::uint32_t sum = 0;
|
||||
for (std::size_t i = 0; i < kTarBlockSize; ++i) {
|
||||
if (i >= 148 && i < 156) {
|
||||
sum += static_cast<std::uint32_t>(' ');
|
||||
} else {
|
||||
sum += static_cast<std::uint32_t>(
|
||||
std::to_integer<std::uint8_t>(block[i]));
|
||||
}
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::int32_t
|
||||
compute_checksum_signed(const std::array<std::byte, kTarBlockSize>& block) noexcept
|
||||
{
|
||||
std::int32_t sum = 0;
|
||||
for (std::size_t i = 0; i < kTarBlockSize; ++i) {
|
||||
if (i >= 148 && i < 156) {
|
||||
sum += static_cast<std::int32_t>(' ');
|
||||
} else {
|
||||
sum += static_cast<std::int32_t>(
|
||||
static_cast<signed char>(
|
||||
std::to_integer<unsigned char>(block[i])));
|
||||
}
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
void build_ustar_header(std::array<std::byte, kTarBlockSize>& hdr,
|
||||
std::string_view wire_name, char typeflag,
|
||||
std::uint32_t mode, std::uint32_t uid,
|
||||
std::uint32_t gid, std::uint64_t size,
|
||||
std::uint64_t mtime) noexcept
|
||||
{
|
||||
hdr.fill(std::byte{0});
|
||||
|
||||
// Split into prefix (<=155) + name (<=100) only when needed and valid;
|
||||
// callers handling paths >255 emit PAX 'x' before this header.
|
||||
std::string_view prefix{};
|
||||
std::string_view name = wire_name;
|
||||
if (wire_name.size() > 100) {
|
||||
const std::size_t min_split =
|
||||
wire_name.size() > 100 ? wire_name.size() - 101 : 0;
|
||||
const std::size_t max_split = std::min<std::size_t>(155, wire_name.size() - 1);
|
||||
std::size_t chosen = std::string_view::npos;
|
||||
for (std::size_t pos = max_split; pos >= min_split; --pos) {
|
||||
if (pos < wire_name.size() && wire_name[pos] == '/') {
|
||||
const std::string_view cand_prefix = wire_name.substr(0, pos);
|
||||
const std::string_view cand_name = wire_name.substr(pos + 1);
|
||||
if (!cand_prefix.empty() && cand_prefix.size() <= 155 &&
|
||||
!cand_name.empty() && cand_name.size() <= 100) {
|
||||
chosen = pos;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (pos == 0) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (chosen != std::string_view::npos) {
|
||||
prefix = wire_name.substr(0, chosen);
|
||||
name = wire_name.substr(chosen + 1);
|
||||
} else {
|
||||
name = wire_name.substr(0, 100);
|
||||
}
|
||||
}
|
||||
|
||||
std::memcpy(hdr.data() + 0, name.data(), std::min<std::size_t>(name.size(), 100));
|
||||
write_octal(std::span{hdr}.subspan(100, 8), mode & 07777U);
|
||||
write_octal(std::span{hdr}.subspan(108, 8), uid);
|
||||
write_octal(std::span{hdr}.subspan(116, 8), gid);
|
||||
// Clamp size field to 11 octal digits when PAX overrides size.
|
||||
const std::uint64_t ustar_size =
|
||||
size <= 077777777777ULL ? size : 0ULL;
|
||||
write_octal(std::span{hdr}.subspan(124, 12), ustar_size);
|
||||
write_octal(std::span{hdr}.subspan(136, 12), mtime);
|
||||
std::fill(hdr.begin() + 148, hdr.begin() + 156, std::byte{' '});
|
||||
hdr[156] = static_cast<std::byte>(typeflag);
|
||||
std::memcpy(hdr.data() + 257, "ustar\0", 6);
|
||||
hdr[263] = std::byte{'0'};
|
||||
hdr[264] = std::byte{'0'};
|
||||
write_octal(std::span{hdr}.subspan(329, 8), 0);
|
||||
write_octal(std::span{hdr}.subspan(337, 8), 0);
|
||||
if (!prefix.empty()) {
|
||||
std::memcpy(hdr.data() + 345, prefix.data(),
|
||||
std::min<std::size_t>(prefix.size(), 155));
|
||||
}
|
||||
|
||||
const std::uint32_t sum = compute_checksum_unsigned(hdr);
|
||||
write_octal(std::span{hdr}.subspan(148, 7), sum);
|
||||
hdr[155] = std::byte{' '};
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string
|
||||
make_pax_record(std::string_view key, std::string_view value)
|
||||
{
|
||||
const std::size_t rest_len = 1U + key.size() + 1U + value.size() + 1U;
|
||||
std::size_t total = rest_len + 1U;
|
||||
for (;;) {
|
||||
const std::string digits = std::to_string(total);
|
||||
const std::size_t next = digits.size() + rest_len;
|
||||
if (next == total) {
|
||||
break;
|
||||
}
|
||||
total = next;
|
||||
}
|
||||
return std::format("{} {}={}\n", total, key, value);
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
write_padding(ByteSink& sink, std::uint64_t written)
|
||||
{
|
||||
const std::size_t rem = static_cast<std::size_t>(written % kTarBlockSize);
|
||||
if (rem == 0) {
|
||||
return {};
|
||||
}
|
||||
std::array<std::byte, kTarBlockSize> zeros{};
|
||||
return sink.write(std::span{zeros}.subspan(0, kTarBlockSize - rem));
|
||||
}
|
||||
|
||||
[[nodiscard]] bool
|
||||
can_fit_ustar_path(std::string_view wire_path) noexcept
|
||||
{
|
||||
if (wire_path.size() <= 100) {
|
||||
return true;
|
||||
}
|
||||
if (wire_path.size() > 256) {
|
||||
return false;
|
||||
}
|
||||
const std::size_t min_split = wire_path.size() - 101;
|
||||
const std::size_t max_split = std::min<std::size_t>(155, wire_path.size() - 1);
|
||||
for (std::size_t pos = max_split; pos >= min_split; --pos) {
|
||||
if (pos < wire_path.size() && wire_path[pos] == '/') {
|
||||
const std::size_t p_len = pos;
|
||||
const std::size_t n_len = wire_path.size() - (pos + 1);
|
||||
if (p_len >= 1 && p_len <= 155 && n_len >= 1 && n_len <= 100) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (pos == 0) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
parse_pax_records(std::string_view payload, std::string& path_out,
|
||||
std::string& link_out,
|
||||
std::optional<std::uint64_t>& size_out,
|
||||
std::size_t max_path_bytes)
|
||||
{
|
||||
std::size_t pos = 0;
|
||||
while (pos < payload.size()) {
|
||||
const std::size_t sp = payload.find(' ', pos);
|
||||
if (sp == std::string_view::npos) {
|
||||
return std::unexpected{make_archive_error(
|
||||
ArchiveErrorCode::corrupt_archive,
|
||||
"Archive: malformed PAX record length")};
|
||||
}
|
||||
std::size_t rec_len = 0;
|
||||
const auto lr = std::from_chars(payload.data() + pos,
|
||||
payload.data() + sp, rec_len);
|
||||
if (lr.ec != std::errc{} || lr.ptr != payload.data() + sp ||
|
||||
rec_len == 0 || pos + rec_len > payload.size() ||
|
||||
sp >= pos + rec_len) {
|
||||
return std::unexpected{make_archive_error(
|
||||
ArchiveErrorCode::corrupt_archive,
|
||||
"Archive: invalid PAX extended header record length")};
|
||||
}
|
||||
const std::string_view rec =
|
||||
payload.substr(sp + 1, pos + rec_len - (sp + 1));
|
||||
if (rec.empty() || rec.back() != '\n') {
|
||||
return std::unexpected{make_archive_error(
|
||||
ArchiveErrorCode::corrupt_archive,
|
||||
"Archive: PAX record missing trailing newline")};
|
||||
}
|
||||
const std::string_view kv = rec.substr(0, rec.size() - 1);
|
||||
const std::size_t eq = kv.find('=');
|
||||
if (eq == std::string_view::npos) {
|
||||
return std::unexpected{make_archive_error(
|
||||
ArchiveErrorCode::corrupt_archive,
|
||||
"Archive: PAX record missing '='")};
|
||||
}
|
||||
const std::string_view key = kv.substr(0, eq);
|
||||
const std::string_view val = kv.substr(eq + 1);
|
||||
if (key == "path") {
|
||||
if (val.size() > max_path_bytes + 1U) {
|
||||
return std::unexpected{make_archive_error(
|
||||
ArchiveErrorCode::limit_exceeded,
|
||||
"Archive: PAX path exceeds configured limit")};
|
||||
}
|
||||
path_out.assign(val);
|
||||
} else if (key == "linkpath") {
|
||||
if (val.size() > max_path_bytes + 1U) {
|
||||
return std::unexpected{make_archive_error(
|
||||
ArchiveErrorCode::limit_exceeded,
|
||||
"Archive: PAX linkpath exceeds configured limit")};
|
||||
}
|
||||
link_out.assign(val);
|
||||
} else if (key == "size") {
|
||||
std::uint64_t parsed_size = 0;
|
||||
const auto sr = std::from_chars(
|
||||
val.data(), val.data() + val.size(), parsed_size);
|
||||
if (sr.ec != std::errc{} ||
|
||||
sr.ptr != val.data() + val.size()) {
|
||||
return std::unexpected{make_archive_error(
|
||||
ArchiveErrorCode::corrupt_archive,
|
||||
"Archive: invalid PAX size field")};
|
||||
}
|
||||
size_out = parsed_size;
|
||||
}
|
||||
pos += rec_len;
|
||||
}
|
||||
return {};
|
||||
}
|
||||
} // namespace
|
||||
|
||||
Void::Result::Result<void>
|
||||
write_builtin_tar(ByteSink& sink,
|
||||
std::span<const BuiltinCreateItem> items,
|
||||
const CreationOptions& options)
|
||||
{
|
||||
const std::uint64_t mtime =
|
||||
options.reproducible
|
||||
? static_cast<std::uint64_t>(std::max<std::int64_t>(
|
||||
0, options.canonical_mtime))
|
||||
: static_cast<std::uint64_t>(std::max<std::int64_t>(
|
||||
0,
|
||||
std::chrono::duration_cast<std::chrono::seconds>(
|
||||
std::chrono::system_clock::now().time_since_epoch())
|
||||
.count()));
|
||||
const std::uint32_t uid =
|
||||
options.reproducible ? options.canonical_uid : 0U;
|
||||
const std::uint32_t gid =
|
||||
options.reproducible ? options.canonical_gid : 0U;
|
||||
|
||||
std::array<std::byte, kTarBlockSize> hdr{};
|
||||
std::vector<std::byte> io_buf(options.limits.transfer_buffer_bytes);
|
||||
|
||||
for (const auto& item : items) {
|
||||
if (options.stop.stop_requested()) {
|
||||
return std::unexpected{make_archive_error(
|
||||
ArchiveErrorCode::cancelled,
|
||||
"Archive::create_archive: cancelled")};
|
||||
}
|
||||
|
||||
const std::string wire_path =
|
||||
item.is_directory ? (item.path + "/") : item.path;
|
||||
const bool need_pax_path = !can_fit_ustar_path(wire_path);
|
||||
const bool need_pax_size = item.size > 077777777777ULL;
|
||||
if (need_pax_path || need_pax_size) {
|
||||
std::string pax;
|
||||
if (need_pax_path) {
|
||||
pax += make_pax_record("path", wire_path);
|
||||
}
|
||||
if (need_pax_size) {
|
||||
pax += make_pax_record("size", std::to_string(item.size));
|
||||
}
|
||||
std::string pax_name = "PaxHeaders.0/";
|
||||
const std::size_t suffix_take = std::min<std::size_t>(
|
||||
100U - pax_name.size(), item.path.size());
|
||||
pax_name.append(item.path.substr(0, suffix_take));
|
||||
|
||||
build_ustar_header(hdr, pax_name, 'x', 0644U, 0U, 0U,
|
||||
pax.size(), 0ULL);
|
||||
if (auto w = sink.write(hdr); !w.has_value()) {
|
||||
return w;
|
||||
}
|
||||
const auto pax_bytes =
|
||||
std::as_bytes(std::span{pax.data(), pax.size()});
|
||||
if (auto w = sink.write(pax_bytes); !w.has_value()) {
|
||||
return w;
|
||||
}
|
||||
if (auto p = write_padding(sink, pax.size()); !p.has_value()) {
|
||||
return p;
|
||||
}
|
||||
}
|
||||
|
||||
build_ustar_header(hdr, wire_path, item.is_directory ? '5' : '0',
|
||||
item.mode, uid, gid, item.size, mtime);
|
||||
if (auto w = sink.write(hdr); !w.has_value()) {
|
||||
return w;
|
||||
}
|
||||
|
||||
if (!item.is_directory) {
|
||||
if (item.source_fd >= 0) {
|
||||
#ifndef _WIN32
|
||||
std::uint64_t remaining = item.size;
|
||||
while (remaining > 0) {
|
||||
const std::size_t want = static_cast<std::size_t>(
|
||||
std::min<std::uint64_t>(remaining, io_buf.size()));
|
||||
const ssize_t r =
|
||||
::read(item.source_fd, io_buf.data(), want);
|
||||
if (r < 0 && errno == EINTR) {
|
||||
continue;
|
||||
}
|
||||
if (r <= 0) {
|
||||
return std::unexpected{make_archive_error(
|
||||
ArchiveErrorCode::io_error,
|
||||
"Archive::create_archive: source file shrunk "
|
||||
"or read failed")};
|
||||
}
|
||||
if (auto w = sink.write(std::span<const std::byte>{
|
||||
io_buf.data(), static_cast<std::size_t>(r)});
|
||||
!w.has_value()) {
|
||||
return w;
|
||||
}
|
||||
remaining -= static_cast<std::uint64_t>(r);
|
||||
}
|
||||
#endif
|
||||
} else if (!item.inline_content.empty()) {
|
||||
if (auto w = sink.write(item.inline_content);
|
||||
!w.has_value()) {
|
||||
return w;
|
||||
}
|
||||
}
|
||||
if (auto p = write_padding(sink, item.size); !p.has_value()) {
|
||||
return p;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Standard two 512-byte zero EOF blocks.
|
||||
std::array<std::byte, kTarBlockSize * 2> eof_blocks{};
|
||||
return sink.write(eof_blocks);
|
||||
}
|
||||
|
||||
BuiltinTarStream::BuiltinTarStream(
|
||||
ByteSource& source, const ReadLimits& limits, std::stop_token stop,
|
||||
std::optional<Void::Time::MonotonicClock::time_point> deadline,
|
||||
const Void::Time::MonotonicClock& clock)
|
||||
: m_source(&source), m_limits(limits), m_stop(std::move(stop)),
|
||||
m_deadline(deadline), m_clock(&clock)
|
||||
{
|
||||
}
|
||||
|
||||
Void::Result::Result<void> BuiltinTarStream::check_stop_deadline() const
|
||||
{
|
||||
if (m_stop.stop_requested()) {
|
||||
return std::unexpected{make_archive_error(
|
||||
ArchiveErrorCode::cancelled,
|
||||
"Archive::Reader: operation cancelled")};
|
||||
}
|
||||
if (m_deadline.has_value() && m_clock->now() >= *m_deadline) {
|
||||
return std::unexpected{make_archive_error(
|
||||
ArchiveErrorCode::timeout,
|
||||
"Archive::Reader: deadline expired")};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
Void::Result::Result<std::size_t>
|
||||
BuiltinTarStream::read_exact_or_eof(std::span<std::byte> dst)
|
||||
{
|
||||
std::size_t filled = 0;
|
||||
if (m_prefetch_off < m_prefetch.size()) {
|
||||
const std::size_t take =
|
||||
std::min(dst.size(), m_prefetch.size() - m_prefetch_off);
|
||||
std::memcpy(dst.data(), m_prefetch.data() + m_prefetch_off, take);
|
||||
m_prefetch_off += take;
|
||||
filled += take;
|
||||
if (m_prefetch_off == m_prefetch.size()) {
|
||||
m_prefetch.clear();
|
||||
m_prefetch_off = 0;
|
||||
}
|
||||
}
|
||||
|
||||
while (filled < dst.size()) {
|
||||
if (auto chk = check_stop_deadline(); !chk.has_value()) {
|
||||
return std::unexpected{std::move(chk.error())};
|
||||
}
|
||||
const std::size_t want = dst.size() - filled;
|
||||
auto r = m_source->read(dst.subspan(filled, want));
|
||||
if (!r.has_value()) {
|
||||
return std::unexpected{std::move(r.error())};
|
||||
}
|
||||
if (*r == 0) {
|
||||
break;
|
||||
}
|
||||
const auto n = static_cast<std::uint64_t>(*r);
|
||||
if (n > m_limits.max_compressed_bytes - m_total_compressed) {
|
||||
return std::unexpected{make_archive_error(
|
||||
ArchiveErrorCode::limit_exceeded,
|
||||
"Archive::Reader: compressed input exceeds limit")};
|
||||
}
|
||||
m_total_compressed += n;
|
||||
filled += *r;
|
||||
}
|
||||
return filled;
|
||||
}
|
||||
|
||||
Void::Result::Result<void>
|
||||
BuiltinTarStream::read_exact_required(std::span<std::byte> dst,
|
||||
const char* context)
|
||||
{
|
||||
auto n = read_exact_or_eof(dst);
|
||||
if (!n.has_value()) {
|
||||
return std::unexpected{std::move(n.error())};
|
||||
}
|
||||
if (*n != dst.size()) {
|
||||
return std::unexpected{make_archive_error(
|
||||
ArchiveErrorCode::corrupt_archive,
|
||||
std::format("Archive::Reader: unexpected EOF while reading {}",
|
||||
context))};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
Void::Result::Result<void>
|
||||
BuiltinTarStream::discard_bytes(std::uint64_t count,
|
||||
const char* context)
|
||||
{
|
||||
std::array<std::byte, 4096> scratch{};
|
||||
std::uint64_t rem = count;
|
||||
while (rem > 0) {
|
||||
const std::size_t want = static_cast<std::size_t>(
|
||||
std::min<std::uint64_t>(rem, scratch.size()));
|
||||
if (auto r = read_exact_required(std::span{scratch}.subspan(0, want),
|
||||
context);
|
||||
!r.has_value()) {
|
||||
return r;
|
||||
}
|
||||
rem -= want;
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
Void::Result::Result<void> BuiltinTarStream::open()
|
||||
{
|
||||
if (auto chk = check_stop_deadline(); !chk.has_value()) {
|
||||
return chk;
|
||||
}
|
||||
m_prefetch.resize(std::min<std::size_t>(512U,
|
||||
m_limits.transfer_buffer_bytes));
|
||||
auto r = m_source->read(m_prefetch);
|
||||
if (!r.has_value()) {
|
||||
return std::unexpected{std::move(r.error())};
|
||||
}
|
||||
m_prefetch.resize(*r);
|
||||
m_prefetch_off = 0;
|
||||
const auto n = static_cast<std::uint64_t>(*r);
|
||||
if (n > m_limits.max_compressed_bytes) {
|
||||
return std::unexpected{make_archive_error(
|
||||
ArchiveErrorCode::limit_exceeded,
|
||||
"Archive::Reader: input exceeds compressed limit")};
|
||||
}
|
||||
m_total_compressed = n;
|
||||
if (*r == 0) {
|
||||
m_reached_eof = true;
|
||||
return {};
|
||||
}
|
||||
// Reject compressed streams cleanly when LibArchive is unavailable.
|
||||
if (m_prefetch.size() >= 2 &&
|
||||
m_prefetch[0] == std::byte{0x1F} &&
|
||||
m_prefetch[1] == std::byte{0x8B}) {
|
||||
return std::unexpected{make_archive_error(
|
||||
ArchiveErrorCode::unsupported_format,
|
||||
"Archive::Reader: gzip archives require LibArchive backend")};
|
||||
}
|
||||
if (m_prefetch.size() >= 4 &&
|
||||
m_prefetch[0] == std::byte{0x28} &&
|
||||
m_prefetch[1] == std::byte{0xB5} &&
|
||||
m_prefetch[2] == std::byte{0x2F} &&
|
||||
m_prefetch[3] == std::byte{0xFD}) {
|
||||
return std::unexpected{make_archive_error(
|
||||
ArchiveErrorCode::unsupported_format,
|
||||
"Archive::Reader: zstd archives require LibArchive backend")};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
Void::Result::Result<std::optional<BuiltinTarEntry>>
|
||||
BuiltinTarStream::next_entry()
|
||||
{
|
||||
if (m_reached_eof) {
|
||||
return std::optional<BuiltinTarEntry>{std::nullopt};
|
||||
}
|
||||
if (m_has_active_entry) {
|
||||
return std::unexpected{make_archive_error(
|
||||
ArchiveErrorCode::conflict,
|
||||
"Archive::Reader: active entry must be drained or skipped")};
|
||||
}
|
||||
|
||||
std::string next_pax_path;
|
||||
std::string next_pax_link;
|
||||
std::optional<std::uint64_t> next_pax_size;
|
||||
std::string global_pax_path;
|
||||
std::string global_pax_link;
|
||||
std::optional<std::uint64_t> global_pax_size;
|
||||
std::string gnu_long_name;
|
||||
std::string gnu_long_link;
|
||||
|
||||
std::array<std::byte, kTarBlockSize> hdr{};
|
||||
for (;;) {
|
||||
auto nread = read_exact_or_eof(hdr);
|
||||
if (!nread.has_value()) {
|
||||
return std::unexpected{std::move(nread.error())};
|
||||
}
|
||||
if (*nread == 0) {
|
||||
m_reached_eof = true;
|
||||
return std::optional<BuiltinTarEntry>{std::nullopt};
|
||||
}
|
||||
if (*nread != kTarBlockSize) {
|
||||
return std::unexpected{make_archive_error(
|
||||
ArchiveErrorCode::corrupt_archive,
|
||||
"Archive::Reader: truncated tar header block")};
|
||||
}
|
||||
if (is_zero_block(hdr)) {
|
||||
m_reached_eof = true;
|
||||
return std::optional<BuiltinTarEntry>{std::nullopt};
|
||||
}
|
||||
|
||||
auto recorded_sum = parse_octal(std::span{hdr}.subspan(148, 8),
|
||||
"chksum");
|
||||
if (!recorded_sum.has_value()) {
|
||||
return std::unexpected{std::move(recorded_sum.error())};
|
||||
}
|
||||
const std::uint32_t usum = compute_checksum_unsigned(hdr);
|
||||
const std::int32_t ssum = compute_checksum_signed(hdr);
|
||||
if (*recorded_sum != usum &&
|
||||
static_cast<std::int64_t>(*recorded_sum) !=
|
||||
static_cast<std::int64_t>(ssum)) {
|
||||
return std::unexpected{make_archive_error(
|
||||
ArchiveErrorCode::corrupt_archive,
|
||||
"Archive::Reader: tar header checksum mismatch")};
|
||||
}
|
||||
|
||||
auto parsed_mode =
|
||||
parse_octal(std::span{hdr}.subspan(100, 8), "mode");
|
||||
if (!parsed_mode.has_value()) {
|
||||
return std::unexpected{std::move(parsed_mode.error())};
|
||||
}
|
||||
auto parsed_size =
|
||||
parse_octal(std::span{hdr}.subspan(124, 12), "size");
|
||||
if (!parsed_size.has_value()) {
|
||||
return std::unexpected{std::move(parsed_size.error())};
|
||||
}
|
||||
|
||||
const char typeflag = static_cast<char>(std::to_integer<unsigned char>(hdr[156]));
|
||||
if (typeflag == 'x' || typeflag == 'g' || typeflag == 'L' ||
|
||||
typeflag == 'K') {
|
||||
if (*parsed_size > m_limits.max_metadata_bytes ||
|
||||
*parsed_size >
|
||||
m_limits.max_metadata_bytes - m_metadata_budget_used) {
|
||||
return std::unexpected{make_archive_error(
|
||||
ArchiveErrorCode::limit_exceeded,
|
||||
"Archive::Reader: tar extended header exceeds metadata "
|
||||
"limit")};
|
||||
}
|
||||
m_metadata_budget_used += static_cast<std::size_t>(*parsed_size);
|
||||
std::string payload(static_cast<std::size_t>(*parsed_size), '\0');
|
||||
if (!payload.empty()) {
|
||||
if (auto rr = read_exact_required(
|
||||
std::as_writable_bytes(std::span{payload}),
|
||||
"extended tar header");
|
||||
!rr.has_value()) {
|
||||
return std::unexpected{std::move(rr.error())};
|
||||
}
|
||||
}
|
||||
const std::size_t pad =
|
||||
static_cast<std::size_t>((kTarBlockSize - (*parsed_size % kTarBlockSize)) % kTarBlockSize);
|
||||
if (pad > 0) {
|
||||
if (auto dr = discard_bytes(pad, "extended header padding");
|
||||
!dr.has_value()) {
|
||||
return std::unexpected{std::move(dr.error())};
|
||||
}
|
||||
}
|
||||
if (typeflag == 'x') {
|
||||
if (auto pr = parse_pax_records(
|
||||
payload, next_pax_path, next_pax_link,
|
||||
next_pax_size, m_limits.max_path_bytes);
|
||||
!pr.has_value()) {
|
||||
return std::unexpected{std::move(pr.error())};
|
||||
}
|
||||
} else if (typeflag == 'g') {
|
||||
if (auto pr = parse_pax_records(
|
||||
payload, global_pax_path, global_pax_link,
|
||||
global_pax_size, m_limits.max_path_bytes);
|
||||
!pr.has_value()) {
|
||||
return std::unexpected{std::move(pr.error())};
|
||||
}
|
||||
} else {
|
||||
while (!payload.empty() && payload.back() == '\0') {
|
||||
payload.pop_back();
|
||||
}
|
||||
if (payload.size() > m_limits.max_path_bytes + 1U) {
|
||||
return std::unexpected{make_archive_error(
|
||||
ArchiveErrorCode::limit_exceeded,
|
||||
"Archive::Reader: GNU long name exceeds limit")};
|
||||
}
|
||||
if (typeflag == 'L') {
|
||||
gnu_long_name = std::move(payload);
|
||||
} else {
|
||||
gnu_long_link = std::move(payload);
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const std::string_view magic_view =
|
||||
c_field(std::span{hdr}.subspan(257, 6));
|
||||
std::string path;
|
||||
if (!next_pax_path.empty()) {
|
||||
path = std::move(next_pax_path);
|
||||
} else if (!gnu_long_name.empty()) {
|
||||
path = std::move(gnu_long_name);
|
||||
} else if (!global_pax_path.empty()) {
|
||||
path = global_pax_path;
|
||||
} else {
|
||||
const std::string_view name =
|
||||
c_field(std::span{hdr}.subspan(0, 100));
|
||||
const std::string_view prefix =
|
||||
magic_view.starts_with("ustar")
|
||||
? c_field(std::span{hdr}.subspan(345, 155))
|
||||
: std::string_view{};
|
||||
if (!prefix.empty()) {
|
||||
path = std::string{prefix} + "/" + std::string{name};
|
||||
} else {
|
||||
path.assign(name);
|
||||
}
|
||||
}
|
||||
|
||||
std::string link;
|
||||
if (!next_pax_link.empty()) {
|
||||
link = std::move(next_pax_link);
|
||||
} else if (!gnu_long_link.empty()) {
|
||||
link = std::move(gnu_long_link);
|
||||
} else if (!global_pax_link.empty()) {
|
||||
link = global_pax_link;
|
||||
} else {
|
||||
link.assign(c_field(std::span{hdr}.subspan(157, 100)));
|
||||
}
|
||||
|
||||
const std::uint64_t entry_size =
|
||||
next_pax_size.has_value()
|
||||
? *next_pax_size
|
||||
: (global_pax_size.has_value() ? *global_pax_size
|
||||
: *parsed_size);
|
||||
|
||||
EntryType etype = EntryType::Other;
|
||||
if (typeflag == '1') {
|
||||
etype = EntryType::Hardlink;
|
||||
} else if (typeflag == '2') {
|
||||
etype = EntryType::Symlink;
|
||||
} else if (typeflag == '5') {
|
||||
etype = EntryType::Directory;
|
||||
} else if (typeflag == '0' || typeflag == '\0') {
|
||||
if (typeflag == '\0' && !magic_view.starts_with("ustar") &&
|
||||
entry_size == 0 && path.ends_with('/')) {
|
||||
etype = EntryType::Directory;
|
||||
} else {
|
||||
etype = EntryType::RegularFile;
|
||||
}
|
||||
}
|
||||
|
||||
BuiltinTarEntry out{};
|
||||
out.path = std::move(path);
|
||||
out.linkname = std::move(link);
|
||||
out.type = etype;
|
||||
out.mode = static_cast<std::uint32_t>(*parsed_mode & 07777ULL);
|
||||
out.declared_size =
|
||||
(etype == EntryType::RegularFile) ? entry_size : 0ULL;
|
||||
|
||||
m_entry_size = (etype == EntryType::RegularFile) ? entry_size : 0ULL;
|
||||
m_entry_remaining = m_entry_size;
|
||||
m_has_active_entry = (etype == EntryType::RegularFile);
|
||||
|
||||
// Non-regular entries with declared non-zero payload must advance
|
||||
// over padding if any (standard tar has 0 size for dirs/links).
|
||||
if (!m_has_active_entry && entry_size > 0) {
|
||||
const std::uint64_t pad =
|
||||
(kTarBlockSize - (entry_size % kTarBlockSize)) % kTarBlockSize;
|
||||
if (auto dr = discard_bytes(entry_size + pad,
|
||||
"non-regular entry payload");
|
||||
!dr.has_value()) {
|
||||
return std::unexpected{std::move(dr.error())};
|
||||
}
|
||||
}
|
||||
|
||||
return std::optional<BuiltinTarEntry>{std::move(out)};
|
||||
}
|
||||
}
|
||||
|
||||
Void::Result::Result<void> BuiltinTarStream::finish_active_entry_padding()
|
||||
{
|
||||
m_has_active_entry = false;
|
||||
const std::uint64_t pad =
|
||||
(kTarBlockSize - (m_entry_size % kTarBlockSize)) % kTarBlockSize;
|
||||
m_entry_size = 0;
|
||||
m_entry_remaining = 0;
|
||||
if (pad > 0) {
|
||||
return discard_bytes(pad, "tar entry block padding");
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
Void::Result::Result<std::size_t>
|
||||
BuiltinTarStream::read_entry_data(std::span<std::byte> dst)
|
||||
{
|
||||
if (!m_has_active_entry) {
|
||||
return std::size_t{0};
|
||||
}
|
||||
if (m_entry_remaining == 0) {
|
||||
if (auto fin = finish_active_entry_padding(); !fin.has_value()) {
|
||||
return std::unexpected{std::move(fin.error())};
|
||||
}
|
||||
return std::size_t{0};
|
||||
}
|
||||
if (dst.empty()) {
|
||||
return std::size_t{0};
|
||||
}
|
||||
const std::size_t want = static_cast<std::size_t>(
|
||||
std::min<std::uint64_t>(dst.size(), m_entry_remaining));
|
||||
if (auto rr = read_exact_required(dst.subspan(0, want),
|
||||
"tar entry data");
|
||||
!rr.has_value()) {
|
||||
return std::unexpected{std::move(rr.error())};
|
||||
}
|
||||
m_entry_remaining -= want;
|
||||
if (m_entry_remaining == 0) {
|
||||
if (auto fin = finish_active_entry_padding(); !fin.has_value()) {
|
||||
return std::unexpected{std::move(fin.error())};
|
||||
}
|
||||
}
|
||||
return want;
|
||||
}
|
||||
|
||||
Void::Result::Result<std::uint64_t> BuiltinTarStream::skip_entry_data()
|
||||
{
|
||||
if (!m_has_active_entry) {
|
||||
return std::uint64_t{0};
|
||||
}
|
||||
const std::uint64_t skipped = m_entry_remaining;
|
||||
const std::uint64_t rem = m_entry_remaining;
|
||||
m_entry_remaining = 0;
|
||||
if (rem > 0) {
|
||||
if (auto dr = discard_bytes(rem, "tar entry data");
|
||||
!dr.has_value()) {
|
||||
return std::unexpected{std::move(dr.error())};
|
||||
}
|
||||
}
|
||||
if (auto fin = finish_active_entry_padding(); !fin.has_value()) {
|
||||
return std::unexpected{std::move(fin.error())};
|
||||
}
|
||||
return skipped;
|
||||
}
|
||||
|
||||
} // namespace Void::Archive::Detail
|
||||
@@ -0,0 +1,93 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Archive/Types.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Time/Clock.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <stop_token>
|
||||
#include <string>
|
||||
|
||||
namespace Void::Archive::Detail
|
||||
{
|
||||
struct BuiltinCreateItem {
|
||||
std::string path{};
|
||||
bool is_directory{false};
|
||||
std::uint32_t mode{0644};
|
||||
std::uint64_t size{0};
|
||||
std::span<const std::byte> inline_content{};
|
||||
int source_fd{-1};
|
||||
};
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
write_builtin_tar(ByteSink& sink,
|
||||
std::span<const BuiltinCreateItem> items,
|
||||
const CreationOptions& options);
|
||||
|
||||
struct BuiltinTarEntry {
|
||||
std::string path{};
|
||||
std::string linkname{};
|
||||
EntryType type{EntryType::RegularFile};
|
||||
std::uint64_t declared_size{0};
|
||||
std::uint32_t mode{0644};
|
||||
};
|
||||
|
||||
class BuiltinTarStream
|
||||
{
|
||||
public:
|
||||
|
||||
BuiltinTarStream(
|
||||
ByteSource& source, const ReadLimits& limits,
|
||||
std::stop_token stop,
|
||||
std::optional<Void::Time::MonotonicClock::time_point> deadline,
|
||||
const Void::Time::MonotonicClock& clock);
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> open();
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::optional<BuiltinTarEntry>>
|
||||
next_entry();
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::size_t>
|
||||
read_entry_data(std::span<std::byte> dst);
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::uint64_t> skip_entry_data();
|
||||
|
||||
[[nodiscard]] std::uint64_t total_compressed_bytes() const noexcept
|
||||
{
|
||||
return m_total_compressed;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> check_stop_deadline() const;
|
||||
[[nodiscard]] Void::Result::Result<std::size_t>
|
||||
read_exact_or_eof(std::span<std::byte> dst);
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
read_exact_required(std::span<std::byte> dst,
|
||||
const char* context);
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
discard_bytes(std::uint64_t count, const char* context);
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
finish_active_entry_padding();
|
||||
|
||||
ByteSource* m_source{nullptr};
|
||||
ReadLimits m_limits{};
|
||||
std::stop_token m_stop{};
|
||||
std::optional<Void::Time::MonotonicClock::time_point> m_deadline{};
|
||||
const Void::Time::MonotonicClock* m_clock{
|
||||
&Void::Time::SystemMonotonicClock::instance()};
|
||||
|
||||
std::vector<std::byte> m_prefetch{};
|
||||
std::size_t m_prefetch_off{0};
|
||||
std::uint64_t m_total_compressed{0};
|
||||
bool m_reached_eof{false};
|
||||
bool m_has_active_entry{false};
|
||||
std::uint64_t m_entry_size{0};
|
||||
std::uint64_t m_entry_remaining{0};
|
||||
std::size_t m_metadata_budget_used{0};
|
||||
};
|
||||
|
||||
} // namespace Void::Archive::Detail
|
||||
+326
-21
@@ -1,6 +1,8 @@
|
||||
#include <Void/Archive/Archive.hpp>
|
||||
#include <Void/System/Process.hpp>
|
||||
|
||||
#include "BuiltinTar.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
@@ -18,8 +20,10 @@
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
|
||||
#include <archive.h>
|
||||
#include <archive_entry.h>
|
||||
#endif
|
||||
|
||||
#ifndef _WIN32
|
||||
#include <dirent.h>
|
||||
@@ -51,12 +55,14 @@ namespace Void::Archive
|
||||
constexpr std::string_view kInventoryFilename = "inventory.txt";
|
||||
constexpr std::string_view kTreeSubdir = "tree";
|
||||
|
||||
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
|
||||
using ArchiveReadPtr =
|
||||
std::unique_ptr<archive, decltype(&archive_read_free)>;
|
||||
using ArchiveWritePtr =
|
||||
std::unique_ptr<archive, decltype(&archive_write_free)>;
|
||||
using ArchiveEntryPtr =
|
||||
std::unique_ptr<archive_entry, decltype(&archive_entry_free)>;
|
||||
#endif
|
||||
|
||||
class OwnedFd
|
||||
{
|
||||
@@ -129,6 +135,7 @@ namespace Void::Archive
|
||||
std::error_code{err, std::generic_category()});
|
||||
}
|
||||
|
||||
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
|
||||
[[nodiscard]] Void::Result::Error
|
||||
make_libarchive_error(archive* a, std::string_view op,
|
||||
ArchiveErrorCode fallback =
|
||||
@@ -140,6 +147,7 @@ namespace Void::Archive
|
||||
return make_archive_error(fallback,
|
||||
std::format("Archive: {}: {}", op, detail));
|
||||
}
|
||||
#endif
|
||||
|
||||
[[nodiscard]] bool is_safe_single_component(
|
||||
std::string_view name, std::size_t max_bytes = 255) noexcept
|
||||
@@ -894,6 +902,15 @@ namespace Void::Archive
|
||||
}
|
||||
} // namespace
|
||||
|
||||
bool has_libarchive_backend() noexcept
|
||||
{
|
||||
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
|
||||
return true;
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
std::string sanitize_diagnostic_path(std::string_view raw) noexcept
|
||||
{
|
||||
std::string out;
|
||||
@@ -1088,10 +1105,14 @@ namespace Void::Archive
|
||||
std::optional<Void::Time::MonotonicClock::time_point> deadline{};
|
||||
const Void::Time::MonotonicClock* clock{
|
||||
&Void::Time::SystemMonotonicClock::instance()};
|
||||
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
|
||||
ArchiveReadPtr handle{nullptr, &archive_read_free};
|
||||
std::vector<std::byte> read_buf{};
|
||||
PathTracker tracker;
|
||||
std::optional<Void::Result::Error> source_error{};
|
||||
#endif
|
||||
std::unique_ptr<Detail::BuiltinTarStream> builtin_stream{};
|
||||
bool using_builtin{false};
|
||||
PathTracker tracker;
|
||||
bool has_active_file{false};
|
||||
bool reached_eof{false};
|
||||
bool poisoned{false};
|
||||
@@ -1101,7 +1122,10 @@ namespace Void::Archive
|
||||
std::uint64_t total_compressed{0};
|
||||
|
||||
explicit Impl(const ReadLimits& lim)
|
||||
: limits(lim), read_buf(lim.transfer_buffer_bytes),
|
||||
: limits(lim),
|
||||
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
|
||||
read_buf(lim.transfer_buffer_bytes),
|
||||
#endif
|
||||
tracker(lim.max_metadata_bytes)
|
||||
{
|
||||
}
|
||||
@@ -1121,6 +1145,7 @@ namespace Void::Archive
|
||||
return {};
|
||||
}
|
||||
|
||||
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
|
||||
static la_ssize_t libarchive_read_cb(archive* a, void* client_data,
|
||||
const void** buffer)
|
||||
{
|
||||
@@ -1150,6 +1175,7 @@ namespace Void::Archive
|
||||
*buffer = self->read_buf.data();
|
||||
return static_cast<la_ssize_t>(n);
|
||||
}
|
||||
#endif
|
||||
};
|
||||
|
||||
Reader::Reader(std::unique_ptr<Impl> impl) noexcept
|
||||
@@ -1178,6 +1204,7 @@ namespace Void::Archive
|
||||
return std::unexpected{std::move(chk.error())};
|
||||
}
|
||||
|
||||
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
|
||||
impl->handle =
|
||||
ArchiveReadPtr{archive_read_new(), &archive_read_free};
|
||||
if (!impl->handle) {
|
||||
@@ -1185,6 +1212,7 @@ namespace Void::Archive
|
||||
ArchiveErrorCode::io_error,
|
||||
"Archive::Reader: cannot allocate libarchive reader")};
|
||||
}
|
||||
(void)archive_read_support_filter_gzip(impl->handle.get());
|
||||
(void)archive_read_support_filter_zstd(impl->handle.get());
|
||||
(void)archive_read_support_filter_none(impl->handle.get());
|
||||
(void)archive_read_support_format_tar(impl->handle.get());
|
||||
@@ -1199,6 +1227,16 @@ namespace Void::Archive
|
||||
impl->handle.get(), "open archive",
|
||||
ArchiveErrorCode::unsupported_format)};
|
||||
}
|
||||
impl->using_builtin = false;
|
||||
#else
|
||||
impl->builtin_stream = std::make_unique<Detail::BuiltinTarStream>(
|
||||
source, limits, stop, deadline, clock);
|
||||
if (auto opened = impl->builtin_stream->open(); !opened.has_value()) {
|
||||
return std::unexpected{std::move(opened.error())};
|
||||
}
|
||||
impl->total_compressed = impl->builtin_stream->total_compressed_bytes();
|
||||
impl->using_builtin = true;
|
||||
#endif
|
||||
return Reader{std::move(impl)};
|
||||
}
|
||||
|
||||
@@ -1242,6 +1280,91 @@ namespace Void::Archive
|
||||
return std::unexpected{std::move(chk.error())};
|
||||
}
|
||||
|
||||
if (m_impl->using_builtin) {
|
||||
auto next = m_impl->builtin_stream->next_entry();
|
||||
m_impl->total_compressed =
|
||||
m_impl->builtin_stream->total_compressed_bytes();
|
||||
if (!next.has_value()) {
|
||||
m_impl->poisoned = true;
|
||||
return std::unexpected{std::move(next.error())};
|
||||
}
|
||||
if (!next->has_value()) {
|
||||
m_impl->reached_eof = true;
|
||||
return std::optional<EntryInfo>{std::nullopt};
|
||||
}
|
||||
if (m_impl->entries_seen >= m_impl->limits.max_entries) {
|
||||
m_impl->poisoned = true;
|
||||
return std::unexpected{make_archive_error(
|
||||
ArchiveErrorCode::limit_exceeded,
|
||||
"Archive::Reader: entry count exceeds limit")};
|
||||
}
|
||||
++m_impl->entries_seen;
|
||||
|
||||
const auto& raw = **next;
|
||||
if (raw.path.empty()) {
|
||||
m_impl->poisoned = true;
|
||||
return std::unexpected{make_archive_error(
|
||||
ArchiveErrorCode::unsafe_entry,
|
||||
"Archive::Reader: entry has no pathname")};
|
||||
}
|
||||
if (raw.type == EntryType::Hardlink ||
|
||||
raw.type == EntryType::Symlink || !raw.linkname.empty()) {
|
||||
m_impl->poisoned = true;
|
||||
return std::unexpected{make_archive_error(
|
||||
ArchiveErrorCode::unsafe_entry,
|
||||
std::format("Archive::Reader: links are not allowed ('{}')",
|
||||
sanitize_diagnostic_path(raw.path)))};
|
||||
}
|
||||
if (raw.type != EntryType::Directory &&
|
||||
raw.type != EntryType::RegularFile) {
|
||||
m_impl->poisoned = true;
|
||||
return std::unexpected{make_archive_error(
|
||||
ArchiveErrorCode::unsafe_entry,
|
||||
std::format("Archive::Reader: special files are not allowed "
|
||||
"('{}')",
|
||||
sanitize_diagnostic_path(raw.path)))};
|
||||
}
|
||||
|
||||
const bool is_dir = (raw.type == EntryType::Directory);
|
||||
auto vp = validate_archive_path(raw.path, is_dir, m_impl->limits);
|
||||
if (!vp.has_value()) {
|
||||
m_impl->poisoned = true;
|
||||
return std::unexpected{std::move(vp.error())};
|
||||
}
|
||||
if (auto rec = m_impl->tracker.record(*vp, is_dir);
|
||||
!rec.has_value()) {
|
||||
m_impl->poisoned = true;
|
||||
return std::unexpected{std::move(rec.error())};
|
||||
}
|
||||
|
||||
std::uint64_t declared_size = 0;
|
||||
bool executable = false;
|
||||
if (!is_dir) {
|
||||
declared_size = raw.declared_size;
|
||||
if (declared_size > m_impl->limits.max_file_bytes ||
|
||||
declared_size > m_impl->limits.max_total_bytes -
|
||||
m_impl->total_decompressed) {
|
||||
m_impl->poisoned = true;
|
||||
return std::unexpected{make_archive_error(
|
||||
ArchiveErrorCode::limit_exceeded,
|
||||
"Archive::Reader: declared entry size exceeds policy")};
|
||||
}
|
||||
executable = (raw.mode & 0111U) != 0U;
|
||||
m_impl->has_active_file = true;
|
||||
m_impl->entry_bytes_read = 0;
|
||||
}
|
||||
|
||||
return std::optional<EntryInfo>{EntryInfo{
|
||||
.path = std::move(vp->normalized),
|
||||
.type = is_dir ? EntryType::Directory : EntryType::RegularFile,
|
||||
.declared_size = declared_size,
|
||||
.safe_mode = is_dir ? 0755U : (executable ? 0755U : 0644U),
|
||||
.executable = executable,
|
||||
.accepted = true,
|
||||
}};
|
||||
}
|
||||
|
||||
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
|
||||
archive_entry* entry = nullptr;
|
||||
const int status =
|
||||
archive_read_next_header(m_impl->handle.get(), &entry);
|
||||
@@ -1335,6 +1458,12 @@ namespace Void::Archive
|
||||
.executable = executable,
|
||||
.accepted = true,
|
||||
}};
|
||||
#else
|
||||
m_impl->poisoned = true;
|
||||
return std::unexpected{make_archive_error(
|
||||
ArchiveErrorCode::unsupported_format,
|
||||
"Archive::Reader: libarchive backend unavailable")};
|
||||
#endif
|
||||
}
|
||||
|
||||
Void::Result::Result<std::size_t>
|
||||
@@ -1358,21 +1487,46 @@ namespace Void::Archive
|
||||
|
||||
const std::size_t to_read =
|
||||
std::min(dst.size(), m_impl->limits.transfer_buffer_bytes);
|
||||
const la_ssize_t n =
|
||||
archive_read_data(m_impl->handle.get(), dst.data(), to_read);
|
||||
if (n == 0) {
|
||||
m_impl->has_active_file = false;
|
||||
return std::size_t{0};
|
||||
}
|
||||
if (n < 0) {
|
||||
m_impl->poisoned = true;
|
||||
if (m_impl->source_error.has_value()) {
|
||||
return std::unexpected{std::move(*m_impl->source_error)};
|
||||
std::size_t read_bytes = 0;
|
||||
if (m_impl->using_builtin) {
|
||||
auto r =
|
||||
m_impl->builtin_stream->read_entry_data(dst.subspan(0, to_read));
|
||||
m_impl->total_compressed =
|
||||
m_impl->builtin_stream->total_compressed_bytes();
|
||||
if (!r.has_value()) {
|
||||
m_impl->poisoned = true;
|
||||
return std::unexpected{std::move(r.error())};
|
||||
}
|
||||
return std::unexpected{
|
||||
make_libarchive_error(m_impl->handle.get(), "read entry data")};
|
||||
read_bytes = *r;
|
||||
if (read_bytes == 0) {
|
||||
m_impl->has_active_file = false;
|
||||
return std::size_t{0};
|
||||
}
|
||||
} else {
|
||||
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
|
||||
const la_ssize_t n =
|
||||
archive_read_data(m_impl->handle.get(), dst.data(), to_read);
|
||||
if (n == 0) {
|
||||
m_impl->has_active_file = false;
|
||||
return std::size_t{0};
|
||||
}
|
||||
if (n < 0) {
|
||||
m_impl->poisoned = true;
|
||||
if (m_impl->source_error.has_value()) {
|
||||
return std::unexpected{std::move(*m_impl->source_error)};
|
||||
}
|
||||
return std::unexpected{make_libarchive_error(
|
||||
m_impl->handle.get(), "read entry data")};
|
||||
}
|
||||
read_bytes = static_cast<std::size_t>(n);
|
||||
#else
|
||||
m_impl->poisoned = true;
|
||||
return std::unexpected{make_archive_error(
|
||||
ArchiveErrorCode::unsupported_format,
|
||||
"Archive::Reader: libarchive backend unavailable")};
|
||||
#endif
|
||||
}
|
||||
const auto amount = static_cast<std::uint64_t>(n);
|
||||
const auto amount = static_cast<std::uint64_t>(read_bytes);
|
||||
if (amount > m_impl->limits.max_file_bytes - m_impl->entry_bytes_read ||
|
||||
amount > m_impl->limits.max_total_bytes -
|
||||
m_impl->total_decompressed) {
|
||||
@@ -1383,7 +1537,7 @@ namespace Void::Archive
|
||||
}
|
||||
m_impl->entry_bytes_read += amount;
|
||||
m_impl->total_decompressed += amount;
|
||||
return static_cast<std::size_t>(n);
|
||||
return read_bytes;
|
||||
}
|
||||
|
||||
Void::Result::Result<std::uint64_t> Reader::skip_entry()
|
||||
@@ -1462,6 +1616,7 @@ namespace Void::Archive
|
||||
}
|
||||
|
||||
// Opt-in forensic listing: reports rejected entries without writing.
|
||||
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
|
||||
struct ForensicState {
|
||||
ByteSource* source{nullptr};
|
||||
ReadLimits limits{};
|
||||
@@ -1477,6 +1632,7 @@ namespace Void::Archive
|
||||
ArchiveErrorCode::io_error,
|
||||
"Archive::list_entries: cannot allocate reader")};
|
||||
}
|
||||
(void)archive_read_support_filter_gzip(handle.get());
|
||||
(void)archive_read_support_filter_zstd(handle.get());
|
||||
(void)archive_read_support_filter_none(handle.get());
|
||||
(void)archive_read_support_format_tar(handle.get());
|
||||
@@ -1592,6 +1748,88 @@ namespace Void::Archive
|
||||
(void)archive_read_data_skip(handle.get());
|
||||
}
|
||||
return out;
|
||||
#else
|
||||
Detail::BuiltinTarStream stream{
|
||||
source, limits, {}, std::nullopt,
|
||||
Void::Time::SystemMonotonicClock::instance()};
|
||||
if (auto opened = stream.open(); !opened.has_value()) {
|
||||
return std::unexpected{std::move(opened.error())};
|
||||
}
|
||||
|
||||
std::vector<EntryInfo> out;
|
||||
PathTracker tracker{limits.max_metadata_bytes};
|
||||
std::size_t metadata_bytes = 0;
|
||||
for (;;) {
|
||||
auto next = stream.next_entry();
|
||||
if (!next.has_value()) {
|
||||
return std::unexpected{std::move(next.error())};
|
||||
}
|
||||
if (!next->has_value()) {
|
||||
break;
|
||||
}
|
||||
if (out.size() >= limits.max_entries) {
|
||||
return std::unexpected{make_archive_error(
|
||||
ArchiveErrorCode::limit_exceeded,
|
||||
"Archive::list_entries: entry count exceeds limit")};
|
||||
}
|
||||
|
||||
const auto& raw = **next;
|
||||
const std::string sanitized =
|
||||
raw.path.empty() ? "<missing>"
|
||||
: sanitize_diagnostic_path(raw.path);
|
||||
if (sanitized.size() + 64U > limits.max_metadata_bytes ||
|
||||
metadata_bytes >
|
||||
limits.max_metadata_bytes - (sanitized.size() + 64U)) {
|
||||
return std::unexpected{make_archive_error(
|
||||
ArchiveErrorCode::limit_exceeded,
|
||||
"Archive::list_entries: metadata limit exceeded")};
|
||||
}
|
||||
metadata_bytes += sanitized.size() + 64U;
|
||||
|
||||
EntryInfo info;
|
||||
info.path = sanitized;
|
||||
if (raw.type == EntryType::Hardlink) {
|
||||
info.type = EntryType::Hardlink;
|
||||
info.accepted = false;
|
||||
info.rejection_reason = "hardlink disallowed";
|
||||
} else if (raw.type == EntryType::Symlink ||
|
||||
!raw.linkname.empty()) {
|
||||
info.type = EntryType::Symlink;
|
||||
info.accepted = false;
|
||||
info.rejection_reason = "symlink disallowed";
|
||||
} else if (raw.type != EntryType::Directory &&
|
||||
raw.type != EntryType::RegularFile) {
|
||||
info.type = EntryType::Other;
|
||||
info.accepted = false;
|
||||
info.rejection_reason = "special file disallowed";
|
||||
} else {
|
||||
const bool is_dir = (raw.type == EntryType::Directory);
|
||||
info.type =
|
||||
is_dir ? EntryType::Directory : EntryType::RegularFile;
|
||||
info.declared_size = raw.declared_size;
|
||||
info.executable = !is_dir && ((raw.mode & 0111U) != 0U);
|
||||
info.safe_mode =
|
||||
is_dir ? 0755U : (info.executable ? 0755U : 0644U);
|
||||
auto vp = validate_archive_path(raw.path, is_dir, limits);
|
||||
if (!vp.has_value()) {
|
||||
info.accepted = false;
|
||||
info.rejection_reason = vp.error().message();
|
||||
} else if (auto rec = tracker.record(*vp, is_dir);
|
||||
!rec.has_value()) {
|
||||
info.accepted = false;
|
||||
info.rejection_reason = rec.error().message();
|
||||
} else {
|
||||
info.path = std::move(vp->normalized);
|
||||
info.accepted = true;
|
||||
}
|
||||
}
|
||||
out.push_back(std::move(info));
|
||||
if (auto sk = stream.skip_entry_data(); !sk.has_value()) {
|
||||
return std::unexpected{std::move(sk.error())};
|
||||
}
|
||||
}
|
||||
return out;
|
||||
#endif
|
||||
}
|
||||
|
||||
Void::Result::Result<std::vector<EntryInfo>>
|
||||
@@ -2314,6 +2552,30 @@ namespace Void::Archive
|
||||
return a.path < b.path;
|
||||
});
|
||||
|
||||
if (options.compression == ArchiveCompression::None &&
|
||||
(options.prefer_builtin_tar || !has_libarchive_backend())) {
|
||||
std::vector<Detail::BuiltinCreateItem> builtin_items;
|
||||
builtin_items.reserve(normalized.size());
|
||||
for (const auto& item : normalized) {
|
||||
const bool is_dir = (item.src->type == EntryType::Directory);
|
||||
const std::uint32_t perm =
|
||||
item.src->mode.has_value()
|
||||
? (*item.src->mode & 0777U)
|
||||
: (is_dir ? 0755U
|
||||
: (item.src->executable ? 0755U : 0644U));
|
||||
builtin_items.push_back(Detail::BuiltinCreateItem{
|
||||
.path = item.path,
|
||||
.is_directory = is_dir,
|
||||
.mode = perm,
|
||||
.size = item.size,
|
||||
.inline_content = item.src->content,
|
||||
.source_fd = item.file_fd.get(),
|
||||
});
|
||||
}
|
||||
return Detail::write_builtin_tar(sink, builtin_items, options);
|
||||
}
|
||||
|
||||
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
|
||||
struct SinkBridge {
|
||||
ByteSink* sink{nullptr};
|
||||
std::optional<Void::Result::Error> err{};
|
||||
@@ -2331,6 +2593,19 @@ namespace Void::Archive
|
||||
return std::unexpected{
|
||||
make_libarchive_error(writer.get(), "add zstd filter")};
|
||||
}
|
||||
} else if (options.compression == ArchiveCompression::Gzip) {
|
||||
if (archive_write_add_filter_gzip(writer.get()) != ARCHIVE_OK) {
|
||||
return std::unexpected{
|
||||
make_libarchive_error(writer.get(), "add gzip filter")};
|
||||
}
|
||||
if (options.reproducible) {
|
||||
if (archive_write_set_filter_option(
|
||||
writer.get(), "gzip", "timestamp", nullptr) !=
|
||||
ARCHIVE_OK) {
|
||||
return std::unexpected{make_libarchive_error(
|
||||
writer.get(), "disable gzip timestamp header")};
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (archive_write_add_filter_none(writer.get()) != ARCHIVE_OK) {
|
||||
return std::unexpected{
|
||||
@@ -2380,14 +2655,24 @@ namespace Void::Archive
|
||||
const bool is_dir = (item.src->type == EntryType::Directory);
|
||||
const std::string wire_path =
|
||||
is_dir ? (item.path + "/") : item.path;
|
||||
const std::uint32_t perm =
|
||||
item.src->mode.has_value()
|
||||
? (*item.src->mode & 0777U)
|
||||
: (is_dir ? 0755U
|
||||
: (item.src->executable ? 0755U : 0644U));
|
||||
archive_entry_set_pathname(ae.get(), wire_path.c_str());
|
||||
archive_entry_set_filetype(ae.get(), is_dir ? AE_IFDIR : AE_IFREG);
|
||||
archive_entry_set_perm(
|
||||
ae.get(), is_dir ? 0755 : (item.src->executable ? 0755 : 0644));
|
||||
archive_entry_set_perm(ae.get(), static_cast<mode_t>(perm));
|
||||
if (options.reproducible) {
|
||||
archive_entry_set_mtime(ae.get(), 0, 0);
|
||||
archive_entry_set_uid(ae.get(), 0);
|
||||
archive_entry_set_gid(ae.get(), 0);
|
||||
archive_entry_set_mtime(
|
||||
ae.get(),
|
||||
static_cast<std::time_t>(
|
||||
std::max<std::int64_t>(0, options.canonical_mtime)),
|
||||
0);
|
||||
archive_entry_set_uid(
|
||||
ae.get(), static_cast<la_int64_t>(options.canonical_uid));
|
||||
archive_entry_set_gid(
|
||||
ae.get(), static_cast<la_int64_t>(options.canonical_gid));
|
||||
archive_entry_set_uname(ae.get(), "");
|
||||
archive_entry_set_gname(ae.get(), "");
|
||||
}
|
||||
@@ -2473,6 +2758,12 @@ namespace Void::Archive
|
||||
make_libarchive_error(writer.get(), "close archive writer")};
|
||||
}
|
||||
return {};
|
||||
#else
|
||||
return std::unexpected{make_archive_error(
|
||||
ArchiveErrorCode::unsupported_format,
|
||||
"Archive::create_archive: compressed archives require "
|
||||
"LibArchive backend")};
|
||||
#endif
|
||||
}
|
||||
|
||||
Void::Result::Result<void>
|
||||
@@ -2491,6 +2782,20 @@ namespace Void::Archive
|
||||
return sink->sync_and_close();
|
||||
}
|
||||
|
||||
Void::Result::Result<void> create(ByteSink& sink,
|
||||
std::span<const CreateEntry> entries,
|
||||
const CreationOptions& options)
|
||||
{
|
||||
return create_archive(sink, entries, options);
|
||||
}
|
||||
|
||||
Void::Result::Result<void> create(const std::filesystem::path& output_path,
|
||||
std::span<const CreateEntry> entries,
|
||||
const CreationOptions& options)
|
||||
{
|
||||
return create_archive(output_path, entries, options);
|
||||
}
|
||||
|
||||
// ── Isolated Child Decoder Profile ───────────────────────────────────────
|
||||
|
||||
Void::Result::Result<StagedTree>
|
||||
|
||||
@@ -1,4 +1,19 @@
|
||||
set(_void_archive_ext_deps "")
|
||||
set(_void_archive_has_libarchive 0)
|
||||
if(NOT CMAKE_DISABLE_FIND_PACKAGE_LibArchive)
|
||||
if(NOT TARGET LibArchive::LibArchive)
|
||||
find_package(LibArchive QUIET)
|
||||
endif()
|
||||
if(TARGET LibArchive::LibArchive)
|
||||
list(APPEND _void_archive_ext_deps LibArchive::LibArchive)
|
||||
set(_void_archive_has_libarchive 1)
|
||||
endif()
|
||||
endif()
|
||||
|
||||
void_add_module(Archive
|
||||
INTERNAL_DEPS Functional Time System
|
||||
EXTERNAL_DEPS LibArchive::LibArchive
|
||||
EXTERNAL_DEPS ${_void_archive_ext_deps}
|
||||
)
|
||||
target_compile_definitions(Void_Archive PUBLIC
|
||||
VOID_ARCHIVE_HAS_LIBARCHIVE=${_void_archive_has_libarchive}
|
||||
)
|
||||
@@ -0,0 +1,895 @@
|
||||
#include "BuiltinHash.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <bit>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <utility>
|
||||
#include <variant>
|
||||
|
||||
namespace Void::Crypto::Detail
|
||||
{
|
||||
namespace
|
||||
{
|
||||
[[nodiscard]] inline std::uint32_t load_be32(const std::byte* p) noexcept
|
||||
{
|
||||
return (static_cast<std::uint32_t>(std::to_integer<std::uint8_t>(p[0])) << 24U) |
|
||||
(static_cast<std::uint32_t>(std::to_integer<std::uint8_t>(p[1])) << 16U) |
|
||||
(static_cast<std::uint32_t>(std::to_integer<std::uint8_t>(p[2])) << 8U) |
|
||||
static_cast<std::uint32_t>(std::to_integer<std::uint8_t>(p[3]));
|
||||
}
|
||||
|
||||
inline void store_be32(std::byte* p, std::uint32_t v) noexcept
|
||||
{
|
||||
p[0] = static_cast<std::byte>((v >> 24U) & 0xFFU);
|
||||
p[1] = static_cast<std::byte>((v >> 16U) & 0xFFU);
|
||||
p[2] = static_cast<std::byte>((v >> 8U) & 0xFFU);
|
||||
p[3] = static_cast<std::byte>(v & 0xFFU);
|
||||
}
|
||||
|
||||
[[nodiscard]] inline std::uint64_t load_be64(const std::byte* p) noexcept
|
||||
{
|
||||
return (static_cast<std::uint64_t>(load_be32(p)) << 32U) |
|
||||
static_cast<std::uint64_t>(load_be32(p + 4));
|
||||
}
|
||||
|
||||
inline void store_be64(std::byte* p, std::uint64_t v) noexcept
|
||||
{
|
||||
store_be32(p, static_cast<std::uint32_t>((v >> 32U) & 0xFFFFFFFFU));
|
||||
store_be32(p + 4, static_cast<std::uint32_t>(v & 0xFFFFFFFFU));
|
||||
}
|
||||
|
||||
[[nodiscard]] inline std::uint64_t load_le64(const std::byte* p) noexcept
|
||||
{
|
||||
return static_cast<std::uint64_t>(std::to_integer<std::uint8_t>(p[0])) |
|
||||
(static_cast<std::uint64_t>(std::to_integer<std::uint8_t>(p[1])) << 8U) |
|
||||
(static_cast<std::uint64_t>(std::to_integer<std::uint8_t>(p[2])) << 16U) |
|
||||
(static_cast<std::uint64_t>(std::to_integer<std::uint8_t>(p[3])) << 24U) |
|
||||
(static_cast<std::uint64_t>(std::to_integer<std::uint8_t>(p[4])) << 32U) |
|
||||
(static_cast<std::uint64_t>(std::to_integer<std::uint8_t>(p[5])) << 40U) |
|
||||
(static_cast<std::uint64_t>(std::to_integer<std::uint8_t>(p[6])) << 48U) |
|
||||
(static_cast<std::uint64_t>(std::to_integer<std::uint8_t>(p[7])) << 56U);
|
||||
}
|
||||
|
||||
inline void store_le64(std::byte* p, std::uint64_t v) noexcept
|
||||
{
|
||||
for (std::size_t i = 0; i < 8; ++i) {
|
||||
p[i] = static_cast<std::byte>((v >> (8U * i)) & 0xFFU);
|
||||
}
|
||||
}
|
||||
|
||||
// ── FIPS 180-4 SHA-1 ─────────────────────────────────────────────────
|
||||
|
||||
struct Sha1State {
|
||||
std::array<std::uint32_t, 5> h{0x67452301U, 0xefcdab89U,
|
||||
0x98badcfeU, 0x10325476U,
|
||||
0xc3d2e1f0U};
|
||||
std::array<std::byte, 64> buf{};
|
||||
std::size_t buf_len{0};
|
||||
std::uint64_t total_bytes{0};
|
||||
|
||||
void compress(const std::byte* block) noexcept
|
||||
{
|
||||
std::array<std::uint32_t, 80> w{};
|
||||
for (std::size_t i = 0; i < 16; ++i) {
|
||||
w[i] = load_be32(block + i * 4);
|
||||
}
|
||||
for (std::size_t i = 16; i < 80; ++i) {
|
||||
w[i] = std::rotl(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^
|
||||
w[i - 16],
|
||||
1);
|
||||
}
|
||||
std::uint32_t a = h[0];
|
||||
std::uint32_t b = h[1];
|
||||
std::uint32_t c = h[2];
|
||||
std::uint32_t d = h[3];
|
||||
std::uint32_t e = h[4];
|
||||
for (std::size_t i = 0; i < 80; ++i) {
|
||||
std::uint32_t f = 0;
|
||||
std::uint32_t k = 0;
|
||||
if (i < 20) {
|
||||
f = (b & c) | ((~b) & d);
|
||||
k = 0x5a827999U;
|
||||
} else if (i < 40) {
|
||||
f = b ^ c ^ d;
|
||||
k = 0x6ed9eba1U;
|
||||
} else if (i < 60) {
|
||||
f = (b & c) | (b & d) | (c & d);
|
||||
k = 0x8f1bbcdcU;
|
||||
} else {
|
||||
f = b ^ c ^ d;
|
||||
k = 0xca62c1d6U;
|
||||
}
|
||||
const std::uint32_t temp =
|
||||
std::rotl(a, 5) + f + e + k + w[i];
|
||||
e = d;
|
||||
d = c;
|
||||
c = std::rotl(b, 30);
|
||||
b = a;
|
||||
a = temp;
|
||||
}
|
||||
h[0] += a;
|
||||
h[1] += b;
|
||||
h[2] += c;
|
||||
h[3] += d;
|
||||
h[4] += e;
|
||||
builtin_secure_wipe(std::as_writable_bytes(std::span{w}));
|
||||
}
|
||||
|
||||
void update(std::span<const std::byte> data) noexcept
|
||||
{
|
||||
total_bytes += data.size();
|
||||
std::size_t off = 0;
|
||||
if (buf_len > 0) {
|
||||
const std::size_t take =
|
||||
std::min(data.size(), buf.size() - buf_len);
|
||||
std::memcpy(buf.data() + buf_len, data.data(), take);
|
||||
buf_len += take;
|
||||
off += take;
|
||||
if (buf_len == buf.size()) {
|
||||
compress(buf.data());
|
||||
buf_len = 0;
|
||||
}
|
||||
}
|
||||
while (off + buf.size() <= data.size()) {
|
||||
compress(data.data() + off);
|
||||
off += buf.size();
|
||||
}
|
||||
if (off < data.size()) {
|
||||
const std::size_t rem = data.size() - off;
|
||||
std::memcpy(buf.data(), data.data() + off, rem);
|
||||
buf_len = rem;
|
||||
}
|
||||
}
|
||||
|
||||
void finalize_into(std::span<std::byte> out20) noexcept
|
||||
{
|
||||
buf[buf_len++] = std::byte{0x80};
|
||||
if (buf_len > 56) {
|
||||
std::fill(buf.begin() + static_cast<std::ptrdiff_t>(buf_len),
|
||||
buf.end(), std::byte{0});
|
||||
compress(buf.data());
|
||||
buf_len = 0;
|
||||
}
|
||||
std::fill(buf.begin() + static_cast<std::ptrdiff_t>(buf_len),
|
||||
buf.begin() + 56, std::byte{0});
|
||||
store_be64(buf.data() + 56, total_bytes << 3U);
|
||||
compress(buf.data());
|
||||
for (std::size_t i = 0; i < 5; ++i) {
|
||||
store_be32(out20.data() + i * 4, h[i]);
|
||||
}
|
||||
wipe();
|
||||
}
|
||||
|
||||
void wipe() noexcept
|
||||
{
|
||||
builtin_secure_wipe(std::as_writable_bytes(std::span{h}));
|
||||
builtin_secure_wipe(buf);
|
||||
buf_len = 0;
|
||||
total_bytes = 0;
|
||||
}
|
||||
};
|
||||
|
||||
// ── FIPS 180-4 SHA-256 ───────────────────────────────────────────────
|
||||
|
||||
struct Sha256State {
|
||||
static constexpr std::array<std::uint32_t, 64> kRound = {
|
||||
0x428a2f98U, 0x71374491U, 0xb5c0fbcfU, 0xe9b5dba5U,
|
||||
0x3956c25bU, 0x59f111f1U, 0x923f82a4U, 0xab1c5ed5U,
|
||||
0xd807aa98U, 0x12835b01U, 0x243185beU, 0x550c7dc3U,
|
||||
0x72be5d74U, 0x80deb1feU, 0x9bdc06a7U, 0xc19bf174U,
|
||||
0xe49b69c1U, 0xefbe4786U, 0x0fc19dc6U, 0x240ca1ccU,
|
||||
0x2de92c6fU, 0x4a7484aaU, 0x5cb0a9dcU, 0x76f988daU,
|
||||
0x983e5152U, 0xa831c66dU, 0xb00327c8U, 0xbf597fc7U,
|
||||
0xc6e00bf3U, 0xd5a79147U, 0x06ca6351U, 0x14292967U,
|
||||
0x27b70a85U, 0x2e1b2138U, 0x4d2c6dfcU, 0x53380d13U,
|
||||
0x650a7354U, 0x766a0abbU, 0x81c2c92eU, 0x92722c85U,
|
||||
0xa2bfe8a1U, 0xa81a664bU, 0xc24b8b70U, 0xc76c51a3U,
|
||||
0xd192e819U, 0xd6990624U, 0xf40e3585U, 0x106aa070U,
|
||||
0x19a4c116U, 0x1e376c08U, 0x2748774cU, 0x34b0bcb5U,
|
||||
0x391c0cb3U, 0x4ed8aa4aU, 0x5b9cca4fU, 0x682e6ff3U,
|
||||
0x748f82eeU, 0x78a5636fU, 0x84c87814U, 0x8cc70208U,
|
||||
0x90befffaU, 0xa4506cebU, 0xbef9a3f7U, 0xc67178f2U};
|
||||
|
||||
std::array<std::uint32_t, 8> h{0x6a09e667U, 0xbb67ae85U,
|
||||
0x3c6ef372U, 0xa54ff53aU,
|
||||
0x510e527fU, 0x9b05688cU,
|
||||
0x1f83d9abU, 0x5be0cd19U};
|
||||
std::array<std::byte, 64> buf{};
|
||||
std::size_t buf_len{0};
|
||||
std::uint64_t total_bytes{0};
|
||||
|
||||
void compress(const std::byte* block) noexcept
|
||||
{
|
||||
std::array<std::uint32_t, 64> w{};
|
||||
for (std::size_t i = 0; i < 16; ++i) {
|
||||
w[i] = load_be32(block + i * 4);
|
||||
}
|
||||
for (std::size_t i = 16; i < 64; ++i) {
|
||||
const std::uint32_t s0 = std::rotr(w[i - 15], 7) ^
|
||||
std::rotr(w[i - 15], 18) ^
|
||||
(w[i - 15] >> 3U);
|
||||
const std::uint32_t s1 = std::rotr(w[i - 2], 17) ^
|
||||
std::rotr(w[i - 2], 19) ^
|
||||
(w[i - 2] >> 10U);
|
||||
w[i] = w[i - 16] + s0 + w[i - 7] + s1;
|
||||
}
|
||||
std::uint32_t a = h[0];
|
||||
std::uint32_t b = h[1];
|
||||
std::uint32_t c = h[2];
|
||||
std::uint32_t d = h[3];
|
||||
std::uint32_t e = h[4];
|
||||
std::uint32_t f = h[5];
|
||||
std::uint32_t g = h[6];
|
||||
std::uint32_t hv = h[7];
|
||||
|
||||
for (std::size_t i = 0; i < 64; ++i) {
|
||||
const std::uint32_t S1 = std::rotr(e, 6) ^
|
||||
std::rotr(e, 11) ^
|
||||
std::rotr(e, 25);
|
||||
const std::uint32_t ch = (e & f) ^ ((~e) & g);
|
||||
const std::uint32_t temp1 =
|
||||
hv + S1 + ch + kRound[i] + w[i];
|
||||
const std::uint32_t S0 = std::rotr(a, 2) ^
|
||||
std::rotr(a, 13) ^
|
||||
std::rotr(a, 22);
|
||||
const std::uint32_t maj =
|
||||
(a & b) ^ (a & c) ^ (b & c);
|
||||
const std::uint32_t temp2 = S0 + maj;
|
||||
|
||||
hv = g;
|
||||
g = f;
|
||||
f = e;
|
||||
e = d + temp1;
|
||||
d = c;
|
||||
c = b;
|
||||
b = a;
|
||||
a = temp1 + temp2;
|
||||
}
|
||||
|
||||
h[0] += a;
|
||||
h[1] += b;
|
||||
h[2] += c;
|
||||
h[3] += d;
|
||||
h[4] += e;
|
||||
h[5] += f;
|
||||
h[6] += g;
|
||||
h[7] += hv;
|
||||
builtin_secure_wipe(std::as_writable_bytes(std::span{w}));
|
||||
}
|
||||
|
||||
void update(std::span<const std::byte> data) noexcept
|
||||
{
|
||||
total_bytes += data.size();
|
||||
std::size_t off = 0;
|
||||
if (buf_len > 0) {
|
||||
const std::size_t take =
|
||||
std::min(data.size(), buf.size() - buf_len);
|
||||
std::memcpy(buf.data() + buf_len, data.data(), take);
|
||||
buf_len += take;
|
||||
off += take;
|
||||
if (buf_len == buf.size()) {
|
||||
compress(buf.data());
|
||||
buf_len = 0;
|
||||
}
|
||||
}
|
||||
while (off + buf.size() <= data.size()) {
|
||||
compress(data.data() + off);
|
||||
off += buf.size();
|
||||
}
|
||||
if (off < data.size()) {
|
||||
const std::size_t rem = data.size() - off;
|
||||
std::memcpy(buf.data(), data.data() + off, rem);
|
||||
buf_len = rem;
|
||||
}
|
||||
}
|
||||
|
||||
void finalize_into(std::span<std::byte> out32) noexcept
|
||||
{
|
||||
buf[buf_len++] = std::byte{0x80};
|
||||
if (buf_len > 56) {
|
||||
std::fill(buf.begin() + static_cast<std::ptrdiff_t>(buf_len),
|
||||
buf.end(), std::byte{0});
|
||||
compress(buf.data());
|
||||
buf_len = 0;
|
||||
}
|
||||
std::fill(buf.begin() + static_cast<std::ptrdiff_t>(buf_len),
|
||||
buf.begin() + 56, std::byte{0});
|
||||
store_be64(buf.data() + 56, total_bytes << 3U);
|
||||
compress(buf.data());
|
||||
for (std::size_t i = 0; i < 8; ++i) {
|
||||
store_be32(out32.data() + i * 4, h[i]);
|
||||
}
|
||||
wipe();
|
||||
}
|
||||
|
||||
void wipe() noexcept
|
||||
{
|
||||
builtin_secure_wipe(std::as_writable_bytes(std::span{h}));
|
||||
builtin_secure_wipe(buf);
|
||||
buf_len = 0;
|
||||
total_bytes = 0;
|
||||
}
|
||||
};
|
||||
|
||||
// ── FIPS 180-4 SHA-512 ───────────────────────────────────────────────
|
||||
|
||||
struct Sha512State {
|
||||
static constexpr std::array<std::uint64_t, 80> kRound = {
|
||||
0x428a2f98d728ae22ULL, 0x7137449123ef65cdULL,
|
||||
0xb5c0fbcfec4d3b2fULL, 0xe9b5dba58189dbbcULL,
|
||||
0x3956c25bf348b538ULL, 0x59f111f1b605d019ULL,
|
||||
0x923f82a4af194f9bULL, 0xab1c5ed5da6d8118ULL,
|
||||
0xd807aa98a3030242ULL, 0x12835b0145706fbeULL,
|
||||
0x243185be4ee4b28cULL, 0x550c7dc3d5ffb4e2ULL,
|
||||
0x72be5d74f27b896fULL, 0x80deb1fe3b1696b1ULL,
|
||||
0x9bdc06a725c71235ULL, 0xc19bf174cf692694ULL,
|
||||
0xe49b69c19ef14ad2ULL, 0xefbe4786384f25e3ULL,
|
||||
0x0fc19dc68b8cd5b5ULL, 0x240ca1cc77ac9c65ULL,
|
||||
0x2de92c6f592b0275ULL, 0x4a7484aa6ea6e483ULL,
|
||||
0x5cb0a9dcbd41fbd4ULL, 0x76f988da831153b5ULL,
|
||||
0x983e5152ee66dfabULL, 0xa831c66d2db43210ULL,
|
||||
0xb00327c898fb213fULL, 0xbf597fc7beef0ee4ULL,
|
||||
0xc6e00bf33da88fc2ULL, 0xd5a79147930aa725ULL,
|
||||
0x06ca6351e003826fULL, 0x142929670a0e6e70ULL,
|
||||
0x27b70a8546d22ffcULL, 0x2e1b21385c26c926ULL,
|
||||
0x4d2c6dfc5ac42aedULL, 0x53380d139d95b3dfULL,
|
||||
0x650a73548baf63deULL, 0x766a0abb3c77b2a8ULL,
|
||||
0x81c2c92e47edaee6ULL, 0x92722c851482353bULL,
|
||||
0xa2bfe8a14cf10364ULL, 0xa81a664bbc423001ULL,
|
||||
0xc24b8b70d0f89791ULL, 0xc76c51a30654be30ULL,
|
||||
0xd192e819d6ef5218ULL, 0xd69906245565a910ULL,
|
||||
0xf40e35855771202aULL, 0x106aa07032bbd1b8ULL,
|
||||
0x19a4c116b8d2d0c8ULL, 0x1e376c085141ab53ULL,
|
||||
0x2748774cdf8eeb99ULL, 0x34b0bcb5e19b48a8ULL,
|
||||
0x391c0cb3c5c95a63ULL, 0x4ed8aa4ae3418acbULL,
|
||||
0x5b9cca4f7763e373ULL, 0x682e6ff3d6b2b8a3ULL,
|
||||
0x748f82ee5defb2fcULL, 0x78a5636f43172f60ULL,
|
||||
0x84c87814a1f0ab72ULL, 0x8cc702081a6439ecULL,
|
||||
0x90befffa23631e28ULL, 0xa4506cebde82bde9ULL,
|
||||
0xbef9a3f7b2c67915ULL, 0xc67178f2e372532bULL,
|
||||
0xca273eceea26619cULL, 0xd186b8c721c0c207ULL,
|
||||
0xeada7dd6cde0eb1eULL, 0xf57d4f7fee6ed178ULL,
|
||||
0x06f067aa72176fbaULL, 0x0a637dc5a2c898a6ULL,
|
||||
0x113f9804bef90daeULL, 0x1b710b35131c471bULL,
|
||||
0x28db77f523047d84ULL, 0x32caab7b40c72493ULL,
|
||||
0x3c9ebe0a15c9bebcULL, 0x431d67c49c100d4cULL,
|
||||
0x4cc5d4becb3e42b6ULL, 0x597f299cfc657e2aULL,
|
||||
0x5fcb6fab3ad6faecULL, 0x6c44198c4a475817ULL};
|
||||
|
||||
std::array<std::uint64_t, 8> h{
|
||||
0x6a09e667f3bcc908ULL, 0xbb67ae8584caa73bULL,
|
||||
0x3c6ef372fe94f82bULL, 0xa54ff53a5f1d36f1ULL,
|
||||
0x510e527fade682d1ULL, 0x9b05688c2b3e6c1fULL,
|
||||
0x1f83d9abfb41bd6bULL, 0x5be0cd19137e2179ULL};
|
||||
std::array<std::byte, 128> buf{};
|
||||
std::size_t buf_len{0};
|
||||
std::uint64_t total_bytes{0};
|
||||
|
||||
void compress(const std::byte* block) noexcept
|
||||
{
|
||||
std::array<std::uint64_t, 80> w{};
|
||||
for (std::size_t i = 0; i < 16; ++i) {
|
||||
w[i] = load_be64(block + i * 8);
|
||||
}
|
||||
for (std::size_t i = 16; i < 80; ++i) {
|
||||
const std::uint64_t s0 = std::rotr(w[i - 15], 1) ^
|
||||
std::rotr(w[i - 15], 8) ^
|
||||
(w[i - 15] >> 7U);
|
||||
const std::uint64_t s1 = std::rotr(w[i - 2], 19) ^
|
||||
std::rotr(w[i - 2], 61) ^
|
||||
(w[i - 2] >> 6U);
|
||||
w[i] = w[i - 16] + s0 + w[i - 7] + s1;
|
||||
}
|
||||
std::uint64_t a = h[0];
|
||||
std::uint64_t b = h[1];
|
||||
std::uint64_t c = h[2];
|
||||
std::uint64_t d = h[3];
|
||||
std::uint64_t e = h[4];
|
||||
std::uint64_t f = h[5];
|
||||
std::uint64_t g = h[6];
|
||||
std::uint64_t hv = h[7];
|
||||
|
||||
for (std::size_t i = 0; i < 80; ++i) {
|
||||
const std::uint64_t S1 = std::rotr(e, 14) ^
|
||||
std::rotr(e, 18) ^
|
||||
std::rotr(e, 41);
|
||||
const std::uint64_t ch = (e & f) ^ ((~e) & g);
|
||||
const std::uint64_t temp1 =
|
||||
hv + S1 + ch + kRound[i] + w[i];
|
||||
const std::uint64_t S0 = std::rotr(a, 28) ^
|
||||
std::rotr(a, 34) ^
|
||||
std::rotr(a, 39);
|
||||
const std::uint64_t maj =
|
||||
(a & b) ^ (a & c) ^ (b & c);
|
||||
const std::uint64_t temp2 = S0 + maj;
|
||||
|
||||
hv = g;
|
||||
g = f;
|
||||
f = e;
|
||||
e = d + temp1;
|
||||
d = c;
|
||||
c = b;
|
||||
b = a;
|
||||
a = temp1 + temp2;
|
||||
}
|
||||
|
||||
h[0] += a;
|
||||
h[1] += b;
|
||||
h[2] += c;
|
||||
h[3] += d;
|
||||
h[4] += e;
|
||||
h[5] += f;
|
||||
h[6] += g;
|
||||
h[7] += hv;
|
||||
builtin_secure_wipe(std::as_writable_bytes(std::span{w}));
|
||||
}
|
||||
|
||||
void update(std::span<const std::byte> data) noexcept
|
||||
{
|
||||
total_bytes += data.size();
|
||||
std::size_t off = 0;
|
||||
if (buf_len > 0) {
|
||||
const std::size_t take =
|
||||
std::min(data.size(), buf.size() - buf_len);
|
||||
std::memcpy(buf.data() + buf_len, data.data(), take);
|
||||
buf_len += take;
|
||||
off += take;
|
||||
if (buf_len == buf.size()) {
|
||||
compress(buf.data());
|
||||
buf_len = 0;
|
||||
}
|
||||
}
|
||||
while (off + buf.size() <= data.size()) {
|
||||
compress(data.data() + off);
|
||||
off += buf.size();
|
||||
}
|
||||
if (off < data.size()) {
|
||||
const std::size_t rem = data.size() - off;
|
||||
std::memcpy(buf.data(), data.data() + off, rem);
|
||||
buf_len = rem;
|
||||
}
|
||||
}
|
||||
|
||||
void finalize_into(std::span<std::byte> out64) noexcept
|
||||
{
|
||||
buf[buf_len++] = std::byte{0x80};
|
||||
if (buf_len > 112) {
|
||||
std::fill(buf.begin() + static_cast<std::ptrdiff_t>(buf_len),
|
||||
buf.end(), std::byte{0});
|
||||
compress(buf.data());
|
||||
buf_len = 0;
|
||||
}
|
||||
std::fill(buf.begin() + static_cast<std::ptrdiff_t>(buf_len),
|
||||
buf.begin() + 112, std::byte{0});
|
||||
store_be64(buf.data() + 112, total_bytes >> 61U);
|
||||
store_be64(buf.data() + 120, total_bytes << 3U);
|
||||
compress(buf.data());
|
||||
for (std::size_t i = 0; i < 8; ++i) {
|
||||
store_be64(out64.data() + i * 8, h[i]);
|
||||
}
|
||||
wipe();
|
||||
}
|
||||
|
||||
void wipe() noexcept
|
||||
{
|
||||
builtin_secure_wipe(std::as_writable_bytes(std::span{h}));
|
||||
builtin_secure_wipe(buf);
|
||||
buf_len = 0;
|
||||
total_bytes = 0;
|
||||
}
|
||||
};
|
||||
|
||||
// ── RFC 7693 BLAKE2b ─────────────────────────────────────────────────
|
||||
|
||||
struct Blake2bState {
|
||||
static constexpr std::array<std::uint64_t, 8> kIv = {
|
||||
0x6a09e667f3bcc908ULL, 0xbb67ae8584caa73bULL,
|
||||
0x3c6ef372fe94f82bULL, 0xa54ff53a5f1d36f1ULL,
|
||||
0x510e527fade682d1ULL, 0x9b05688c2b3e6c1fULL,
|
||||
0x1f83d9abfb41bd6bULL, 0x5be0cd19137e2179ULL};
|
||||
|
||||
static constexpr std::array<std::array<std::uint8_t, 16>, 12>
|
||||
kSigma = {{
|
||||
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15},
|
||||
{14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3},
|
||||
{11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4},
|
||||
{7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8},
|
||||
{9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13},
|
||||
{2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9},
|
||||
{12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11},
|
||||
{13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10},
|
||||
{6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5},
|
||||
{10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0},
|
||||
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15},
|
||||
{14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3},
|
||||
}};
|
||||
|
||||
std::array<std::uint64_t, 8> h{kIv};
|
||||
std::array<std::uint64_t, 2> t{0, 0};
|
||||
std::array<std::byte, 128> buf{};
|
||||
std::size_t buf_len{0};
|
||||
std::size_t out_len{64};
|
||||
|
||||
void init(std::size_t digest_len) noexcept
|
||||
{
|
||||
h = kIv;
|
||||
out_len = digest_len;
|
||||
h[0] ^= 0x01010000ULL ^ static_cast<std::uint64_t>(out_len);
|
||||
t = {0, 0};
|
||||
buf.fill(std::byte{0});
|
||||
buf_len = 0;
|
||||
}
|
||||
|
||||
void add_counter(std::uint64_t inc) noexcept
|
||||
{
|
||||
t[0] += inc;
|
||||
if (t[0] < inc) {
|
||||
++t[1];
|
||||
}
|
||||
}
|
||||
|
||||
void compress(const std::byte* block, bool is_last) noexcept
|
||||
{
|
||||
std::array<std::uint64_t, 16> m{};
|
||||
for (std::size_t i = 0; i < 16; ++i) {
|
||||
m[i] = load_le64(block + i * 8);
|
||||
}
|
||||
std::array<std::uint64_t, 16> v{};
|
||||
for (std::size_t i = 0; i < 8; ++i) {
|
||||
v[i] = h[i];
|
||||
v[i + 8] = kIv[i];
|
||||
}
|
||||
v[12] ^= t[0];
|
||||
v[13] ^= t[1];
|
||||
if (is_last) {
|
||||
v[14] = ~v[14];
|
||||
}
|
||||
|
||||
auto mix = [&](std::size_t r, std::size_t p,
|
||||
std::size_t ia, std::size_t ib,
|
||||
std::size_t ic, std::size_t id) noexcept {
|
||||
const auto s0 = kSigma[r][2 * p];
|
||||
const auto s1 = kSigma[r][2 * p + 1];
|
||||
v[ia] = v[ia] + v[ib] + m[s0];
|
||||
v[id] = std::rotr(v[id] ^ v[ia], 32);
|
||||
v[ic] = v[ic] + v[id];
|
||||
v[ib] = std::rotr(v[ib] ^ v[ic], 24);
|
||||
v[ia] = v[ia] + v[ib] + m[s1];
|
||||
v[id] = std::rotr(v[id] ^ v[ia], 16);
|
||||
v[ic] = v[ic] + v[id];
|
||||
v[ib] = std::rotr(v[ib] ^ v[ic], 63);
|
||||
};
|
||||
|
||||
for (std::size_t r = 0; r < 12; ++r) {
|
||||
mix(r, 0, 0, 4, 8, 12);
|
||||
mix(r, 1, 1, 5, 9, 13);
|
||||
mix(r, 2, 2, 6, 10, 14);
|
||||
mix(r, 3, 3, 7, 11, 15);
|
||||
mix(r, 4, 0, 5, 10, 15);
|
||||
mix(r, 5, 1, 6, 11, 12);
|
||||
mix(r, 6, 2, 7, 8, 13);
|
||||
mix(r, 7, 3, 4, 9, 14);
|
||||
}
|
||||
|
||||
for (std::size_t i = 0; i < 8; ++i) {
|
||||
h[i] ^= v[i] ^ v[i + 8];
|
||||
}
|
||||
builtin_secure_wipe(std::as_writable_bytes(std::span{m}));
|
||||
builtin_secure_wipe(std::as_writable_bytes(std::span{v}));
|
||||
}
|
||||
|
||||
void update(std::span<const std::byte> data) noexcept
|
||||
{
|
||||
if (data.empty()) {
|
||||
return;
|
||||
}
|
||||
std::size_t off = 0;
|
||||
if (buf_len > 0) {
|
||||
const std::size_t take =
|
||||
std::min(data.size(), buf.size() - buf_len);
|
||||
std::memcpy(buf.data() + buf_len, data.data(), take);
|
||||
buf_len += take;
|
||||
off += take;
|
||||
// Only flush a full buffer when more bytes follow so
|
||||
// finalize() sees the true final block.
|
||||
if (off < data.size() && buf_len == buf.size()) {
|
||||
add_counter(128);
|
||||
compress(buf.data(), false);
|
||||
buf_len = 0;
|
||||
}
|
||||
}
|
||||
while (off + buf.size() < data.size()) {
|
||||
add_counter(128);
|
||||
compress(data.data() + off, false);
|
||||
off += buf.size();
|
||||
}
|
||||
if (off < data.size()) {
|
||||
const std::size_t rem = data.size() - off;
|
||||
std::memcpy(buf.data() + buf_len, data.data() + off,
|
||||
rem);
|
||||
buf_len += rem;
|
||||
}
|
||||
}
|
||||
|
||||
void finalize_into(std::span<std::byte> out) noexcept
|
||||
{
|
||||
add_counter(static_cast<std::uint64_t>(buf_len));
|
||||
std::fill(buf.begin() + static_cast<std::ptrdiff_t>(buf_len),
|
||||
buf.end(), std::byte{0});
|
||||
compress(buf.data(), true);
|
||||
std::array<std::byte, 64> full{};
|
||||
for (std::size_t i = 0; i < 8; ++i) {
|
||||
store_le64(full.data() + i * 8, h[i]);
|
||||
}
|
||||
std::memcpy(out.data(), full.data(), out_len);
|
||||
builtin_secure_wipe(full);
|
||||
wipe();
|
||||
}
|
||||
|
||||
void wipe() noexcept
|
||||
{
|
||||
builtin_secure_wipe(std::as_writable_bytes(std::span{h}));
|
||||
builtin_secure_wipe(std::as_writable_bytes(std::span{t}));
|
||||
builtin_secure_wipe(buf);
|
||||
buf_len = 0;
|
||||
}
|
||||
};
|
||||
} // namespace
|
||||
|
||||
void builtin_secure_wipe(std::span<std::byte> buffer) noexcept
|
||||
{
|
||||
if (buffer.empty()) {
|
||||
return;
|
||||
}
|
||||
volatile std::byte* p = buffer.data();
|
||||
for (std::size_t i = 0; i < buffer.size(); ++i) {
|
||||
p[i] = std::byte{0};
|
||||
}
|
||||
std::atomic_signal_fence(std::memory_order_seq_cst);
|
||||
}
|
||||
|
||||
bool builtin_constant_time_equal(std::span<const std::byte> lhs,
|
||||
std::span<const std::byte> rhs) noexcept
|
||||
{
|
||||
if (lhs.size() != rhs.size()) {
|
||||
return false;
|
||||
}
|
||||
volatile unsigned char diff = 0;
|
||||
for (std::size_t i = 0; i < lhs.size(); ++i) {
|
||||
const auto a = static_cast<unsigned char>(lhs[i]);
|
||||
const auto b = static_cast<unsigned char>(rhs[i]);
|
||||
diff = static_cast<unsigned char>(diff | (a ^ b));
|
||||
}
|
||||
std::atomic_signal_fence(std::memory_order_seq_cst);
|
||||
return diff == 0;
|
||||
}
|
||||
|
||||
struct BuiltinHasher::State {
|
||||
std::variant<std::monostate, Sha1State, Sha256State, Sha512State,
|
||||
Blake2bState>
|
||||
impl{};
|
||||
|
||||
void wipe() noexcept
|
||||
{
|
||||
std::visit(
|
||||
[](auto& st) {
|
||||
using T = std::decay_t<decltype(st)>;
|
||||
if constexpr (!std::is_same_v<T, std::monostate>) {
|
||||
st.wipe();
|
||||
}
|
||||
},
|
||||
impl);
|
||||
impl.template emplace<std::monostate>();
|
||||
}
|
||||
};
|
||||
|
||||
BuiltinHasher::~BuiltinHasher() noexcept { destroy(); }
|
||||
|
||||
BuiltinHasher::BuiltinHasher(BuiltinHasher&& other) noexcept
|
||||
: m_state(std::exchange(other.m_state, nullptr))
|
||||
{
|
||||
}
|
||||
|
||||
BuiltinHasher& BuiltinHasher::operator=(BuiltinHasher&& other) noexcept
|
||||
{
|
||||
if (this != &other) {
|
||||
destroy();
|
||||
m_state = std::exchange(other.m_state, nullptr);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
void BuiltinHasher::destroy() noexcept
|
||||
{
|
||||
if (m_state != nullptr) {
|
||||
m_state->wipe();
|
||||
delete m_state;
|
||||
m_state = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
bool BuiltinHasher::init(HashAlgorithm algorithm) noexcept
|
||||
{
|
||||
if (m_state == nullptr) {
|
||||
m_state = new (std::nothrow) State();
|
||||
if (m_state == nullptr) {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
m_state->wipe();
|
||||
}
|
||||
|
||||
switch (algorithm) {
|
||||
case HashAlgorithm::Sha1:
|
||||
m_state->impl.emplace<Sha1State>();
|
||||
return true;
|
||||
case HashAlgorithm::Sha256:
|
||||
m_state->impl.emplace<Sha256State>();
|
||||
return true;
|
||||
case HashAlgorithm::Sha512:
|
||||
m_state->impl.emplace<Sha512State>();
|
||||
return true;
|
||||
case HashAlgorithm::Blake2b256: {
|
||||
auto& b = m_state->impl.emplace<Blake2bState>();
|
||||
b.init(32);
|
||||
return true;
|
||||
}
|
||||
case HashAlgorithm::Blake2b512: {
|
||||
auto& b = m_state->impl.emplace<Blake2bState>();
|
||||
b.init(64);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void BuiltinHasher::update(std::span<const std::byte> data) noexcept
|
||||
{
|
||||
if (m_state == nullptr || data.empty()) {
|
||||
return;
|
||||
}
|
||||
std::visit(
|
||||
[&](auto& st) {
|
||||
using T = std::decay_t<decltype(st)>;
|
||||
if constexpr (!std::is_same_v<T, std::monostate>) {
|
||||
st.update(data);
|
||||
}
|
||||
},
|
||||
m_state->impl);
|
||||
}
|
||||
|
||||
Digest BuiltinHasher::finalize()
|
||||
{
|
||||
Digest out;
|
||||
if (m_state == nullptr) {
|
||||
return out;
|
||||
}
|
||||
std::visit(
|
||||
[&](auto& st) {
|
||||
using T = std::decay_t<decltype(st)>;
|
||||
if constexpr (std::is_same_v<T, Sha1State>) {
|
||||
out.resize(20);
|
||||
st.finalize_into(out);
|
||||
} else if constexpr (std::is_same_v<T, Sha256State>) {
|
||||
out.resize(32);
|
||||
st.finalize_into(out);
|
||||
} else if constexpr (std::is_same_v<T, Sha512State>) {
|
||||
out.resize(64);
|
||||
st.finalize_into(out);
|
||||
} else if constexpr (std::is_same_v<T, Blake2bState>) {
|
||||
out.resize(st.out_len);
|
||||
st.finalize_into(out);
|
||||
}
|
||||
},
|
||||
m_state->impl);
|
||||
return out;
|
||||
}
|
||||
|
||||
void builtin_hmac_sha256(std::span<const std::byte> secret_key,
|
||||
std::span<const std::byte> message,
|
||||
std::span<std::byte> output_32) noexcept
|
||||
{
|
||||
std::array<std::byte, 64> key_block{};
|
||||
if (secret_key.size() > 64) {
|
||||
Sha256State kh;
|
||||
kh.update(secret_key);
|
||||
kh.finalize_into(std::span{key_block}.subspan(0, 32));
|
||||
} else if (!secret_key.empty()) {
|
||||
std::memcpy(key_block.data(), secret_key.data(), secret_key.size());
|
||||
}
|
||||
|
||||
std::array<std::byte, 64> ipad{};
|
||||
std::array<std::byte, 64> opad{};
|
||||
for (std::size_t i = 0; i < 64; ++i) {
|
||||
ipad[i] = key_block[i] ^ std::byte{0x36};
|
||||
opad[i] = key_block[i] ^ std::byte{0x5C};
|
||||
}
|
||||
|
||||
std::array<std::byte, 32> inner_hash{};
|
||||
{
|
||||
Sha256State inner;
|
||||
inner.update(ipad);
|
||||
inner.update(message);
|
||||
inner.finalize_into(inner_hash);
|
||||
}
|
||||
{
|
||||
Sha256State outer;
|
||||
outer.update(opad);
|
||||
outer.update(inner_hash);
|
||||
outer.finalize_into(output_32);
|
||||
}
|
||||
|
||||
builtin_secure_wipe(key_block);
|
||||
builtin_secure_wipe(ipad);
|
||||
builtin_secure_wipe(opad);
|
||||
builtin_secure_wipe(inner_hash);
|
||||
}
|
||||
|
||||
void builtin_hkdf_sha256(std::span<const std::byte> secret_input,
|
||||
std::span<const std::byte> salt,
|
||||
std::span<const std::byte> context,
|
||||
std::span<std::byte> secret_output) noexcept
|
||||
{
|
||||
std::array<std::byte, 32> zero_salt{};
|
||||
const auto effective_salt =
|
||||
salt.empty() ? std::span<const std::byte>{zero_salt} : salt;
|
||||
|
||||
std::array<std::byte, 32> prk{};
|
||||
builtin_hmac_sha256(effective_salt, secret_input, prk);
|
||||
|
||||
std::array<std::byte, 32> t{};
|
||||
std::size_t t_len = 0;
|
||||
std::size_t written = 0;
|
||||
std::uint8_t counter = 1;
|
||||
|
||||
while (written < secret_output.size()) {
|
||||
std::array<std::byte, 64> ipad{};
|
||||
std::array<std::byte, 64> opad{};
|
||||
for (std::size_t i = 0; i < 32; ++i) {
|
||||
ipad[i] = prk[i] ^ std::byte{0x36};
|
||||
opad[i] = prk[i] ^ std::byte{0x5C};
|
||||
}
|
||||
for (std::size_t i = 32; i < 64; ++i) {
|
||||
ipad[i] = std::byte{0x36};
|
||||
opad[i] = std::byte{0x5C};
|
||||
}
|
||||
|
||||
std::array<std::byte, 32> inner_hash{};
|
||||
Sha256State inner;
|
||||
inner.update(ipad);
|
||||
if (t_len > 0) {
|
||||
inner.update(std::span<const std::byte>{t.data(), t_len});
|
||||
}
|
||||
if (!context.empty()) {
|
||||
inner.update(context);
|
||||
}
|
||||
const std::byte ctr_byte = static_cast<std::byte>(counter);
|
||||
inner.update(std::span<const std::byte>{&ctr_byte, 1});
|
||||
inner.finalize_into(inner_hash);
|
||||
|
||||
Sha256State outer;
|
||||
outer.update(opad);
|
||||
outer.update(inner_hash);
|
||||
outer.finalize_into(t);
|
||||
t_len = 32;
|
||||
|
||||
const std::size_t copy_n =
|
||||
std::min<std::size_t>(32, secret_output.size() - written);
|
||||
std::memcpy(secret_output.data() + written, t.data(), copy_n);
|
||||
written += copy_n;
|
||||
++counter;
|
||||
|
||||
builtin_secure_wipe(ipad);
|
||||
builtin_secure_wipe(opad);
|
||||
builtin_secure_wipe(inner_hash);
|
||||
}
|
||||
|
||||
builtin_secure_wipe(prk);
|
||||
builtin_secure_wipe(t);
|
||||
}
|
||||
|
||||
} // namespace Void::Crypto::Detail
|
||||
@@ -0,0 +1,49 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Crypto/Crypto.hpp>
|
||||
#include <Void/Crypto/Types.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <span>
|
||||
|
||||
namespace Void::Crypto::Detail
|
||||
{
|
||||
void builtin_secure_wipe(std::span<std::byte> buffer) noexcept;
|
||||
|
||||
[[nodiscard]] bool
|
||||
builtin_constant_time_equal(std::span<const std::byte> lhs,
|
||||
std::span<const std::byte> rhs) noexcept;
|
||||
|
||||
class BuiltinHasher
|
||||
{
|
||||
public:
|
||||
|
||||
BuiltinHasher() noexcept = default;
|
||||
~BuiltinHasher() noexcept;
|
||||
|
||||
BuiltinHasher(BuiltinHasher&& other) noexcept;
|
||||
BuiltinHasher& operator=(BuiltinHasher&& other) noexcept;
|
||||
BuiltinHasher(const BuiltinHasher&) = delete;
|
||||
BuiltinHasher& operator=(const BuiltinHasher&) = delete;
|
||||
|
||||
[[nodiscard]] bool init(HashAlgorithm algorithm) noexcept;
|
||||
void update(std::span<const std::byte> data) noexcept;
|
||||
[[nodiscard]] Digest finalize();
|
||||
|
||||
private:
|
||||
|
||||
struct State;
|
||||
State* m_state{nullptr};
|
||||
void destroy() noexcept;
|
||||
};
|
||||
|
||||
void builtin_hmac_sha256(std::span<const std::byte> secret_key,
|
||||
std::span<const std::byte> message,
|
||||
std::span<std::byte> output_32) noexcept;
|
||||
|
||||
void builtin_hkdf_sha256(std::span<const std::byte> secret_input,
|
||||
std::span<const std::byte> salt,
|
||||
std::span<const std::byte> context,
|
||||
std::span<std::byte> secret_output) noexcept;
|
||||
|
||||
} // namespace Void::Crypto::Detail
|
||||
+297
-24
@@ -1,19 +1,24 @@
|
||||
#include <Void/Crypto/Crypto.hpp>
|
||||
|
||||
#include "BuiltinHash.hpp"
|
||||
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <format>
|
||||
#include <fstream>
|
||||
#include <limits>
|
||||
#include <optional>
|
||||
#include <utility>
|
||||
|
||||
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
|
||||
#include <openssl/core_names.h>
|
||||
#include <openssl/crypto.h>
|
||||
#include <openssl/err.h>
|
||||
#include <openssl/evp.h>
|
||||
#include <openssl/kdf.h>
|
||||
#include <openssl/params.h>
|
||||
#endif
|
||||
|
||||
namespace Void::Crypto
|
||||
{
|
||||
@@ -42,6 +47,36 @@ namespace Void::Crypto
|
||||
std::format("{}: injected crypto backend fault", operation));
|
||||
}
|
||||
|
||||
[[nodiscard]] bool spans_overlap(std::span<const std::byte> a,
|
||||
std::span<const std::byte> b) noexcept
|
||||
{
|
||||
if (a.empty() || b.empty()) {
|
||||
return false;
|
||||
}
|
||||
const auto a_begin = reinterpret_cast<std::uintptr_t>(a.data());
|
||||
const auto a_end = a_begin + a.size();
|
||||
const auto b_begin = reinterpret_cast<std::uintptr_t>(b.data());
|
||||
const auto b_end = b_begin + b.size();
|
||||
return a_begin < b_end && b_begin < a_end;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool use_builtin_hash(
|
||||
HashAlgorithm algorithm, const ProviderOptions& provider) noexcept
|
||||
{
|
||||
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
|
||||
if (provider.prefer_builtin ||
|
||||
algorithm == HashAlgorithm::Blake2b256) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
#else
|
||||
(void)algorithm;
|
||||
(void)provider;
|
||||
return true;
|
||||
#endif
|
||||
}
|
||||
|
||||
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
|
||||
[[nodiscard]] const char*
|
||||
algorithm_name(HashAlgorithm algorithm) noexcept
|
||||
{
|
||||
@@ -52,6 +87,10 @@ namespace Void::Crypto
|
||||
return "SHA256";
|
||||
case HashAlgorithm::Sha512:
|
||||
return "SHA512";
|
||||
case HashAlgorithm::Blake2b256:
|
||||
return nullptr;
|
||||
case HashAlgorithm::Blake2b512:
|
||||
return "BLAKE2B512";
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
@@ -78,19 +117,6 @@ namespace Void::Crypto
|
||||
code, std::format("{}: {}", operation, buffer.data()));
|
||||
}
|
||||
|
||||
[[nodiscard]] bool spans_overlap(std::span<const std::byte> a,
|
||||
std::span<const std::byte> b) noexcept
|
||||
{
|
||||
if (a.empty() || b.empty()) {
|
||||
return false;
|
||||
}
|
||||
const auto a_begin = reinterpret_cast<std::uintptr_t>(a.data());
|
||||
const auto a_end = a_begin + a.size();
|
||||
const auto b_begin = reinterpret_cast<std::uintptr_t>(b.data());
|
||||
const auto b_end = b_begin + b.size();
|
||||
return a_begin < b_end && b_begin < a_end;
|
||||
}
|
||||
|
||||
using EvpMdPtr = std::unique_ptr<EVP_MD, decltype(&EVP_MD_free)>;
|
||||
using EvpMdCtxPtr =
|
||||
std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>;
|
||||
@@ -110,6 +136,7 @@ namespace Void::Crypto
|
||||
? &kEmptyByte
|
||||
: reinterpret_cast<const unsigned char*>(span.data());
|
||||
}
|
||||
#endif
|
||||
|
||||
[[nodiscard]] Void::Result::Result<bool>
|
||||
verify_ed25519_impl(std::span<const std::byte> message,
|
||||
@@ -144,6 +171,12 @@ namespace Void::Crypto
|
||||
return std::unexpected{std::move(*fault)};
|
||||
}
|
||||
|
||||
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
|
||||
if (provider.prefer_builtin) {
|
||||
return std::unexpected{make_crypto_error(
|
||||
CryptoErrorCode::unsupported_algorithm,
|
||||
"Crypto::verifyEd25519: Ed25519 requires OpenSSL backend")};
|
||||
}
|
||||
ERR_clear_error();
|
||||
const char* propq = propq_or_null(provider);
|
||||
EvpPkeyPtr key{EVP_PKEY_new_raw_public_key_ex(
|
||||
@@ -182,14 +215,33 @@ namespace Void::Crypto
|
||||
}
|
||||
ERR_clear_error();
|
||||
return result == 1;
|
||||
#else
|
||||
(void)provider;
|
||||
return std::unexpected{make_crypto_error(
|
||||
CryptoErrorCode::unsupported_algorithm,
|
||||
"Crypto::verifyEd25519: built without OpenSSL backend")};
|
||||
#endif
|
||||
}
|
||||
} // namespace
|
||||
|
||||
bool has_openssl_backend() noexcept
|
||||
{
|
||||
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
|
||||
return true;
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
void secure_wipe(std::span<std::byte> buffer) noexcept
|
||||
{
|
||||
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
|
||||
if (!buffer.empty()) {
|
||||
OPENSSL_cleanse(buffer.data(), buffer.size());
|
||||
}
|
||||
#else
|
||||
Detail::builtin_secure_wipe(buffer);
|
||||
#endif
|
||||
}
|
||||
|
||||
bool constant_time_equal(std::span<const std::byte> lhs,
|
||||
@@ -201,7 +253,11 @@ namespace Void::Crypto
|
||||
if (lhs.empty()) {
|
||||
return true;
|
||||
}
|
||||
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
|
||||
return CRYPTO_memcmp(lhs.data(), rhs.data(), lhs.size()) == 0;
|
||||
#else
|
||||
return Detail::builtin_constant_time_equal(lhs, rhs);
|
||||
#endif
|
||||
}
|
||||
|
||||
ScopedFaultGuard::ScopedFaultGuard(FaultConfig config) noexcept
|
||||
@@ -218,8 +274,12 @@ namespace Void::Crypto
|
||||
}
|
||||
|
||||
struct Hasher::Impl {
|
||||
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
|
||||
EvpMdCtxPtr context{nullptr, &EVP_MD_CTX_free};
|
||||
EvpMdPtr algorithm{nullptr, &EVP_MD_free};
|
||||
#endif
|
||||
Detail::BuiltinHasher builtin{};
|
||||
bool using_builtin{false};
|
||||
HasherState state{HasherState::Ready};
|
||||
};
|
||||
|
||||
@@ -244,18 +304,50 @@ namespace Void::Crypto
|
||||
Void::Result::Result<Hasher>
|
||||
Hasher::create(HashAlgorithm algorithm, const ProviderOptions& provider)
|
||||
{
|
||||
const char* md_name = algorithm_name(algorithm);
|
||||
if (md_name == nullptr) {
|
||||
return std::unexpected{make_crypto_error(
|
||||
CryptoErrorCode::unsupported_algorithm,
|
||||
"Crypto::Hasher: unsupported algorithm")};
|
||||
switch (algorithm) {
|
||||
case HashAlgorithm::Sha1:
|
||||
case HashAlgorithm::Sha256:
|
||||
case HashAlgorithm::Sha512:
|
||||
case HashAlgorithm::Blake2b256:
|
||||
case HashAlgorithm::Blake2b512:
|
||||
break;
|
||||
default:
|
||||
return std::unexpected{make_crypto_error(
|
||||
CryptoErrorCode::unsupported_algorithm,
|
||||
"Crypto::Hasher: unsupported algorithm")};
|
||||
}
|
||||
|
||||
if (auto fault = maybe_inject_fault(FaultOperation::hash_create,
|
||||
"Crypto::Hasher::create");
|
||||
fault.has_value()) {
|
||||
return std::unexpected{std::move(*fault)};
|
||||
}
|
||||
|
||||
if (use_builtin_hash(algorithm, provider)) {
|
||||
if (!provider.property_query.empty()) {
|
||||
return std::unexpected{make_crypto_error(
|
||||
CryptoErrorCode::provider_error,
|
||||
"Crypto::Hasher: property_query unavailable on built-in "
|
||||
"backend")};
|
||||
}
|
||||
auto impl = std::make_unique<Impl>();
|
||||
if (!impl->builtin.init(algorithm)) {
|
||||
return std::unexpected{make_crypto_error(
|
||||
CryptoErrorCode::backend_error,
|
||||
"Crypto::Hasher: built-in initialization failed")};
|
||||
}
|
||||
impl->using_builtin = true;
|
||||
impl->state = HasherState::Ready;
|
||||
return Hasher{std::move(impl)};
|
||||
}
|
||||
|
||||
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
|
||||
const char* md_name = algorithm_name(algorithm);
|
||||
if (md_name == nullptr) {
|
||||
return std::unexpected{make_crypto_error(
|
||||
CryptoErrorCode::unsupported_algorithm,
|
||||
"Crypto::Hasher: unsupported OpenSSL digest algorithm")};
|
||||
}
|
||||
ERR_clear_error();
|
||||
auto impl = std::make_unique<Impl>();
|
||||
impl->algorithm = EvpMdPtr{
|
||||
@@ -278,8 +370,14 @@ namespace Void::Crypto
|
||||
CryptoErrorCode::provider_error,
|
||||
"Crypto::Hasher: digest initialization failed")};
|
||||
}
|
||||
impl->using_builtin = false;
|
||||
impl->state = HasherState::Ready;
|
||||
return Hasher{std::move(impl)};
|
||||
#else
|
||||
return std::unexpected{make_crypto_error(
|
||||
CryptoErrorCode::backend_error,
|
||||
"Crypto::Hasher: OpenSSL backend unavailable")};
|
||||
#endif
|
||||
}
|
||||
|
||||
Void::Result::Result<void> Hasher::update(std::span<const std::byte> data)
|
||||
@@ -301,6 +399,12 @@ namespace Void::Crypto
|
||||
m_impl->state = HasherState::Failed;
|
||||
return std::unexpected{std::move(*fault)};
|
||||
}
|
||||
if (m_impl->using_builtin) {
|
||||
m_impl->builtin.update(data);
|
||||
m_impl->state = HasherState::Updating;
|
||||
return {};
|
||||
}
|
||||
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
|
||||
if (!data.empty() &&
|
||||
EVP_DigestUpdate(m_impl->context.get(), data.data(),
|
||||
data.size()) != 1) {
|
||||
@@ -311,6 +415,12 @@ namespace Void::Crypto
|
||||
}
|
||||
m_impl->state = HasherState::Updating;
|
||||
return {};
|
||||
#else
|
||||
m_impl->state = HasherState::Failed;
|
||||
return std::unexpected{make_crypto_error(
|
||||
CryptoErrorCode::backend_error,
|
||||
"Crypto::Hasher::update: invalid backend")};
|
||||
#endif
|
||||
}
|
||||
|
||||
Void::Result::Result<void> Hasher::update(std::string_view data)
|
||||
@@ -337,6 +447,12 @@ namespace Void::Crypto
|
||||
m_impl->state = HasherState::Failed;
|
||||
return std::unexpected{std::move(*fault)};
|
||||
}
|
||||
if (m_impl->using_builtin) {
|
||||
Digest digest = m_impl->builtin.finalize();
|
||||
m_impl->state = HasherState::Finalized;
|
||||
return digest;
|
||||
}
|
||||
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
|
||||
const int digest_size = EVP_MD_get_size(m_impl->algorithm.get());
|
||||
if (digest_size <= 0) {
|
||||
m_impl->state = HasherState::Failed;
|
||||
@@ -357,6 +473,12 @@ namespace Void::Crypto
|
||||
m_impl->state = HasherState::Finalized;
|
||||
digest.resize(written);
|
||||
return digest;
|
||||
#else
|
||||
m_impl->state = HasherState::Failed;
|
||||
return std::unexpected{make_crypto_error(
|
||||
CryptoErrorCode::backend_error,
|
||||
"Crypto::Hasher::finalize: invalid backend")};
|
||||
#endif
|
||||
}
|
||||
|
||||
auto hash(HashAlgorithm algorithm, std::span<const std::byte> data)
|
||||
@@ -388,18 +510,31 @@ namespace Void::Crypto
|
||||
auto hashFile(HashAlgorithm algorithm, const std::filesystem::path& path)
|
||||
-> Void::Result::Result<Digest>
|
||||
{
|
||||
return hashFile(algorithm, path, ProviderOptions{});
|
||||
return hash_file(algorithm, path, ProviderOptions{});
|
||||
}
|
||||
|
||||
auto hashFile(HashAlgorithm algorithm, const std::filesystem::path& path,
|
||||
const ProviderOptions& provider)
|
||||
-> Void::Result::Result<Digest>
|
||||
{
|
||||
return hash_file(algorithm, path, provider);
|
||||
}
|
||||
|
||||
auto hash_file(HashAlgorithm algorithm, const std::filesystem::path& path)
|
||||
-> Void::Result::Result<Digest>
|
||||
{
|
||||
return hash_file(algorithm, path, ProviderOptions{});
|
||||
}
|
||||
|
||||
auto hash_file(HashAlgorithm algorithm, const std::filesystem::path& path,
|
||||
const ProviderOptions& provider)
|
||||
-> Void::Result::Result<Digest>
|
||||
{
|
||||
std::ifstream input{path, std::ios::binary};
|
||||
if (!input.is_open()) {
|
||||
return std::unexpected{make_crypto_error(
|
||||
CryptoErrorCode::io_error,
|
||||
std::format("Crypto::hashFile: cannot open '{}'",
|
||||
std::format("Crypto::hash_file: cannot open '{}'",
|
||||
path.string()))};
|
||||
}
|
||||
auto hasher = Hasher::create(algorithm, provider);
|
||||
@@ -422,7 +557,7 @@ namespace Void::Crypto
|
||||
if (input.bad() || (!input.eof() && input.fail())) {
|
||||
return std::unexpected{make_crypto_error(
|
||||
CryptoErrorCode::io_error,
|
||||
std::format("Crypto::hashFile: I/O error reading '{}'",
|
||||
std::format("Crypto::hash_file: I/O error reading '{}'",
|
||||
path.string()))};
|
||||
}
|
||||
return hasher->finalize();
|
||||
@@ -452,21 +587,63 @@ namespace Void::Crypto
|
||||
{
|
||||
return hash(HashAlgorithm::Sha512, data);
|
||||
}
|
||||
Void::Result::Result<Digest> blake2b256(std::span<const std::byte> data)
|
||||
{
|
||||
return hash(HashAlgorithm::Blake2b256, data);
|
||||
}
|
||||
Void::Result::Result<Digest> blake2b256(std::string_view data)
|
||||
{
|
||||
return hash(HashAlgorithm::Blake2b256, data);
|
||||
}
|
||||
Void::Result::Result<Digest> blake2b512(std::span<const std::byte> data)
|
||||
{
|
||||
return hash(HashAlgorithm::Blake2b512, data);
|
||||
}
|
||||
Void::Result::Result<Digest> blake2b512(std::string_view data)
|
||||
{
|
||||
return hash(HashAlgorithm::Blake2b512, data);
|
||||
}
|
||||
Void::Result::Result<Digest> sha1File(const std::filesystem::path& path)
|
||||
{
|
||||
return hashFile(HashAlgorithm::Sha1, path);
|
||||
return hash_file(HashAlgorithm::Sha1, path);
|
||||
}
|
||||
Void::Result::Result<Digest> sha256File(const std::filesystem::path& path)
|
||||
{
|
||||
return hashFile(HashAlgorithm::Sha256, path);
|
||||
return hash_file(HashAlgorithm::Sha256, path);
|
||||
}
|
||||
Void::Result::Result<Digest> sha512File(const std::filesystem::path& path)
|
||||
{
|
||||
return hashFile(HashAlgorithm::Sha512, path);
|
||||
return hash_file(HashAlgorithm::Sha512, path);
|
||||
}
|
||||
Void::Result::Result<Digest> sha1_file(const std::filesystem::path& path)
|
||||
{
|
||||
return hash_file(HashAlgorithm::Sha1, path);
|
||||
}
|
||||
Void::Result::Result<Digest> sha256_file(const std::filesystem::path& path)
|
||||
{
|
||||
return hash_file(HashAlgorithm::Sha256, path);
|
||||
}
|
||||
Void::Result::Result<Digest> sha512_file(const std::filesystem::path& path)
|
||||
{
|
||||
return hash_file(HashAlgorithm::Sha512, path);
|
||||
}
|
||||
Void::Result::Result<Digest>
|
||||
blake2b256_file(const std::filesystem::path& path)
|
||||
{
|
||||
return hash_file(HashAlgorithm::Blake2b256, path);
|
||||
}
|
||||
Void::Result::Result<Digest>
|
||||
blake2b512_file(const std::filesystem::path& path)
|
||||
{
|
||||
return hash_file(HashAlgorithm::Blake2b512, path);
|
||||
}
|
||||
|
||||
struct Ed25519PrivateKey::Impl {
|
||||
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
|
||||
EvpPkeyPtr pkey{nullptr, &EVP_PKEY_free};
|
||||
#else
|
||||
std::uint8_t unused{0};
|
||||
#endif
|
||||
};
|
||||
|
||||
Ed25519PrivateKey::Ed25519PrivateKey(std::unique_ptr<Impl> impl) noexcept
|
||||
@@ -481,7 +658,11 @@ namespace Void::Crypto
|
||||
|
||||
bool Ed25519PrivateKey::valid() const noexcept
|
||||
{
|
||||
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
|
||||
return m_impl != nullptr && m_impl->pkey != nullptr;
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
Void::Result::Result<Ed25519PrivateKey>
|
||||
@@ -492,6 +673,12 @@ namespace Void::Crypto
|
||||
fault.has_value()) {
|
||||
return std::unexpected{std::move(*fault)};
|
||||
}
|
||||
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
|
||||
if (provider.prefer_builtin) {
|
||||
return std::unexpected{make_crypto_error(
|
||||
CryptoErrorCode::unsupported_algorithm,
|
||||
"Crypto::Ed25519PrivateKey::generate requires OpenSSL backend")};
|
||||
}
|
||||
ERR_clear_error();
|
||||
EvpPkeyPtr key{
|
||||
EVP_PKEY_Q_keygen(nullptr, propq_or_null(provider), "ED25519"),
|
||||
@@ -504,6 +691,13 @@ namespace Void::Crypto
|
||||
auto impl = std::make_unique<Impl>();
|
||||
impl->pkey = std::move(key);
|
||||
return Ed25519PrivateKey{std::move(impl)};
|
||||
#else
|
||||
(void)provider;
|
||||
return std::unexpected{make_crypto_error(
|
||||
CryptoErrorCode::unsupported_algorithm,
|
||||
"Crypto::Ed25519PrivateKey::generate: built without OpenSSL "
|
||||
"backend")};
|
||||
#endif
|
||||
}
|
||||
|
||||
Void::Result::Result<Ed25519PrivateKey>
|
||||
@@ -523,6 +717,13 @@ namespace Void::Crypto
|
||||
fault.has_value()) {
|
||||
return std::unexpected{std::move(*fault)};
|
||||
}
|
||||
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
|
||||
if (provider.prefer_builtin) {
|
||||
return std::unexpected{make_crypto_error(
|
||||
CryptoErrorCode::unsupported_algorithm,
|
||||
"Crypto::Ed25519PrivateKey::from_raw_seed requires OpenSSL "
|
||||
"backend")};
|
||||
}
|
||||
ERR_clear_error();
|
||||
EvpPkeyPtr key{EVP_PKEY_new_raw_private_key_ex(
|
||||
nullptr, "ED25519", propq_or_null(provider),
|
||||
@@ -536,6 +737,13 @@ namespace Void::Crypto
|
||||
auto impl = std::make_unique<Impl>();
|
||||
impl->pkey = std::move(key);
|
||||
return Ed25519PrivateKey{std::move(impl)};
|
||||
#else
|
||||
(void)provider;
|
||||
return std::unexpected{make_crypto_error(
|
||||
CryptoErrorCode::unsupported_algorithm,
|
||||
"Crypto::Ed25519PrivateKey::from_raw_seed: built without OpenSSL "
|
||||
"backend")};
|
||||
#endif
|
||||
}
|
||||
|
||||
Void::Result::Result<Ed25519PublicKey> Ed25519PrivateKey::public_key() const
|
||||
@@ -546,6 +754,7 @@ namespace Void::Crypto
|
||||
"Crypto::Ed25519PrivateKey::public_key: invalid or moved-from "
|
||||
"key")};
|
||||
}
|
||||
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
|
||||
Ed25519PublicKey pub;
|
||||
std::size_t len = pub.bytes.size();
|
||||
if (EVP_PKEY_get_raw_public_key(
|
||||
@@ -558,6 +767,12 @@ namespace Void::Crypto
|
||||
"Crypto::Ed25519PrivateKey::public_key failed")};
|
||||
}
|
||||
return pub;
|
||||
#else
|
||||
return std::unexpected{make_crypto_error(
|
||||
CryptoErrorCode::unsupported_algorithm,
|
||||
"Crypto::Ed25519PrivateKey::public_key: built without OpenSSL "
|
||||
"backend")};
|
||||
#endif
|
||||
}
|
||||
|
||||
Void::Result::Result<Ed25519Seed> Ed25519PrivateKey::export_raw_seed() const
|
||||
@@ -568,6 +783,7 @@ namespace Void::Crypto
|
||||
"Crypto::Ed25519PrivateKey::export_raw_seed: invalid or "
|
||||
"moved-from key")};
|
||||
}
|
||||
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
|
||||
std::array<std::byte, Ed25519SeedSize> raw{};
|
||||
std::size_t len = raw.size();
|
||||
if (EVP_PKEY_get_raw_private_key(
|
||||
@@ -582,6 +798,12 @@ namespace Void::Crypto
|
||||
auto result = Ed25519Seed::from_bytes(raw);
|
||||
secure_wipe(raw);
|
||||
return result;
|
||||
#else
|
||||
return std::unexpected{make_crypto_error(
|
||||
CryptoErrorCode::unsupported_algorithm,
|
||||
"Crypto::Ed25519PrivateKey::export_raw_seed: built without OpenSSL "
|
||||
"backend")};
|
||||
#endif
|
||||
}
|
||||
|
||||
Void::Result::Result<Ed25519Signature>
|
||||
@@ -607,6 +829,12 @@ namespace Void::Crypto
|
||||
return std::unexpected{std::move(*fault)};
|
||||
}
|
||||
|
||||
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
|
||||
if (provider.prefer_builtin) {
|
||||
return std::unexpected{make_crypto_error(
|
||||
CryptoErrorCode::unsupported_algorithm,
|
||||
"Crypto::sign_ed25519 requires OpenSSL backend")};
|
||||
}
|
||||
ERR_clear_error();
|
||||
EvpMdCtxPtr context{EVP_MD_CTX_new(), &EVP_MD_CTX_free};
|
||||
if (!context) {
|
||||
@@ -635,6 +863,12 @@ namespace Void::Crypto
|
||||
"Crypto::sign_ed25519 failed")};
|
||||
}
|
||||
return signature;
|
||||
#else
|
||||
(void)provider;
|
||||
return std::unexpected{make_crypto_error(
|
||||
CryptoErrorCode::unsupported_algorithm,
|
||||
"Crypto::sign_ed25519: built without OpenSSL backend")};
|
||||
#endif
|
||||
}
|
||||
|
||||
Void::Result::Result<bool> verifyEd25519(std::span<const std::byte> message,
|
||||
@@ -682,6 +916,19 @@ namespace Void::Crypto
|
||||
return std::unexpected{std::move(*fault)};
|
||||
}
|
||||
|
||||
if (use_builtin_hash(HashAlgorithm::Sha256, provider)) {
|
||||
if (!provider.property_query.empty()) {
|
||||
secure_wipe(output);
|
||||
return std::unexpected{make_crypto_error(
|
||||
CryptoErrorCode::provider_error,
|
||||
"Crypto::hmac_sha256_into: property_query unavailable on "
|
||||
"built-in backend")};
|
||||
}
|
||||
Detail::builtin_hmac_sha256(secret_key, message, output);
|
||||
return {};
|
||||
}
|
||||
|
||||
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
|
||||
ERR_clear_error();
|
||||
EvpMacPtr mac{EVP_MAC_fetch(nullptr, "HMAC", propq_or_null(provider)),
|
||||
&EVP_MAC_free};
|
||||
@@ -732,6 +979,12 @@ namespace Void::Crypto
|
||||
"Crypto::hmac_sha256_into: EVP_MAC_final failed")};
|
||||
}
|
||||
return {};
|
||||
#else
|
||||
secure_wipe(output);
|
||||
return std::unexpected{make_crypto_error(
|
||||
CryptoErrorCode::backend_error,
|
||||
"Crypto::hmac_sha256_into: OpenSSL backend unavailable")};
|
||||
#endif
|
||||
}
|
||||
|
||||
Void::Result::Result<Digest> hmac_sha256(std::span<const std::byte> secret_key,
|
||||
@@ -780,6 +1033,20 @@ namespace Void::Crypto
|
||||
return std::unexpected{std::move(*fault)};
|
||||
}
|
||||
|
||||
if (use_builtin_hash(HashAlgorithm::Sha256, provider)) {
|
||||
if (!provider.property_query.empty()) {
|
||||
secure_wipe(secret_output);
|
||||
return std::unexpected{make_crypto_error(
|
||||
CryptoErrorCode::provider_error,
|
||||
"Crypto::hkdf_sha256: property_query unavailable on "
|
||||
"built-in backend")};
|
||||
}
|
||||
Detail::builtin_hkdf_sha256(secret_input, salt, context,
|
||||
secret_output);
|
||||
return {};
|
||||
}
|
||||
|
||||
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
|
||||
ERR_clear_error();
|
||||
EvpKdfPtr kdf{EVP_KDF_fetch(nullptr, "HKDF", propq_or_null(provider)),
|
||||
&EVP_KDF_free};
|
||||
@@ -825,6 +1092,12 @@ namespace Void::Crypto
|
||||
"Crypto::hkdf_sha256: EVP_KDF_derive failed")};
|
||||
}
|
||||
return {};
|
||||
#else
|
||||
secure_wipe(secret_output);
|
||||
return std::unexpected{make_crypto_error(
|
||||
CryptoErrorCode::backend_error,
|
||||
"Crypto::hkdf_sha256: OpenSSL backend unavailable")};
|
||||
#endif
|
||||
}
|
||||
|
||||
} // namespace Void::Crypto
|
||||
+16
-1
@@ -1,6 +1,21 @@
|
||||
set(_void_crypto_ext_deps "")
|
||||
set(_void_crypto_has_openssl 0)
|
||||
if(NOT CMAKE_DISABLE_FIND_PACKAGE_OpenSSL)
|
||||
if(NOT TARGET OpenSSL::Crypto)
|
||||
find_package(OpenSSL QUIET)
|
||||
endif()
|
||||
if(TARGET OpenSSL::Crypto)
|
||||
list(APPEND _void_crypto_ext_deps OpenSSL::Crypto)
|
||||
set(_void_crypto_has_openssl 1)
|
||||
endif()
|
||||
endif()
|
||||
|
||||
void_add_module(Crypto
|
||||
INTERNAL_DEPS Functional
|
||||
EXTERNAL_DEPS OpenSSL::Crypto
|
||||
EXTERNAL_DEPS ${_void_crypto_ext_deps}
|
||||
EXCLUDE_HEADERS
|
||||
Void/Crypto/AsyncHash.hpp
|
||||
)
|
||||
target_compile_definitions(Void_Crypto PUBLIC
|
||||
VOID_CRYPTO_HAS_OPENSSL=${_void_crypto_has_openssl}
|
||||
)
|
||||
@@ -12,8 +12,12 @@ int main()
|
||||
.content = {std::byte{'h'}, std::byte{'i'}},
|
||||
},
|
||||
}};
|
||||
Void::Archive::CreationOptions opts;
|
||||
opts.compression = Void::Archive::has_libarchive_backend()
|
||||
? Void::Archive::ArchiveCompression::Zstd
|
||||
: Void::Archive::ArchiveCompression::None;
|
||||
Void::Archive::VectorByteSink sink;
|
||||
if (!Void::Archive::create_archive(sink, entries).has_value()) {
|
||||
if (!Void::Archive::create(sink, entries, opts).has_value()) {
|
||||
return 1;
|
||||
}
|
||||
Void::Archive::SpanByteSource src{sink.bytes()};
|
||||
|
||||
@@ -9,23 +9,33 @@ int main()
|
||||
if (!digest.has_value() || digest->size() != 32) {
|
||||
return 1;
|
||||
}
|
||||
auto key = Void::Crypto::Ed25519PrivateKey::generate();
|
||||
if (!key.has_value()) {
|
||||
return 2;
|
||||
}
|
||||
auto pub = key->public_key();
|
||||
if (!pub.has_value()) {
|
||||
return 3;
|
||||
auto b2 = Void::Crypto::blake2b256("abc");
|
||||
if (!b2.has_value() || b2->size() != 32) {
|
||||
return 6;
|
||||
}
|
||||
const std::array<std::byte, 4> msg{std::byte{1}, std::byte{2}, std::byte{3},
|
||||
std::byte{4}};
|
||||
auto sig = Void::Crypto::sign_ed25519(msg, *key);
|
||||
if (!sig.has_value()) {
|
||||
return 4;
|
||||
auto mac = Void::Crypto::hmac_sha256(msg, msg);
|
||||
if (!mac.has_value() || mac->size() != Void::Crypto::HmacSha256Size) {
|
||||
return 7;
|
||||
}
|
||||
auto ok = Void::Crypto::verify_ed25519(msg, *sig, *pub);
|
||||
if (!ok.has_value() || !*ok) {
|
||||
return 5;
|
||||
if (Void::Crypto::has_openssl_backend()) {
|
||||
auto key = Void::Crypto::Ed25519PrivateKey::generate();
|
||||
if (!key.has_value()) {
|
||||
return 2;
|
||||
}
|
||||
auto pub = key->public_key();
|
||||
if (!pub.has_value()) {
|
||||
return 3;
|
||||
}
|
||||
auto sig = Void::Crypto::sign_ed25519(msg, *key);
|
||||
if (!sig.has_value()) {
|
||||
return 4;
|
||||
}
|
||||
auto ok = Void::Crypto::verify_ed25519(msg, *sig, *pub);
|
||||
if (!ok.has_value() || !*ok) {
|
||||
return 5;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -3,8 +3,10 @@
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <cstring>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <memory>
|
||||
@@ -13,23 +15,95 @@
|
||||
#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;
|
||||
unsigned int type{AE_IFREG};
|
||||
FixtureEntryType type{FixtureEntryType::Regular};
|
||||
std::string_view link;
|
||||
};
|
||||
|
||||
void write_archive(const std::filesystem::path &path,
|
||||
std::span<const ArchiveEntry>
|
||||
entries)
|
||||
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)>;
|
||||
@@ -47,14 +121,21 @@ namespace
|
||||
writer.get(), path.c_str()) == ARCHIVE_OK);
|
||||
#endif
|
||||
|
||||
for (const auto &specification : entries) {
|
||||
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());
|
||||
archive_entry_set_filetype(entry.get(), specification.type);
|
||||
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 == AE_IFDIR ? 0755 : 0644);
|
||||
if (specification.type == AE_IFREG) {
|
||||
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()));
|
||||
@@ -78,18 +159,22 @@ namespace
|
||||
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,
|
||||
void write_archive(const std::filesystem::path& path,
|
||||
std::string_view entryPath, std::string_view contents,
|
||||
unsigned int type = AE_IFREG, std::string_view link = {})
|
||||
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)
|
||||
extraction_file_visible(const std::filesystem::path& destination)
|
||||
{
|
||||
std::error_code error;
|
||||
if (std::filesystem::exists(destination / "anchor", error)) {
|
||||
@@ -129,8 +214,9 @@ 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/", {}, AE_IFDIR},
|
||||
ArchiveEntry{"bin/tool", "payload"}};
|
||||
const std::array entries{
|
||||
ArchiveEntry{"bin/", {}, FixtureEntryType::Directory},
|
||||
ArchiveEntry{"bin/tool", "payload"}};
|
||||
write_archive(source, entries);
|
||||
|
||||
auto extracted = Void::Archive::extract(source, destination);
|
||||
@@ -154,7 +240,8 @@ Void::Testing::Test archive_rejects_traversal_and_links()
|
||||
Void::Testing::expect(
|
||||
!std::filesystem::exists(temporary.path() / "escape"));
|
||||
const auto symlink = temporary / "symlink.tar.zst";
|
||||
write_archive(symlink, "link", {}, AE_IFLNK, "/tmp/escape");
|
||||
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";
|
||||
|
||||
@@ -3,12 +3,16 @@
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
|
||||
#include <archive.h>
|
||||
#include <archive_entry.h>
|
||||
#endif
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstring>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <memory>
|
||||
@@ -16,6 +20,8 @@
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <sys/stat.h>
|
||||
#include <thread>
|
||||
#include <tuple>
|
||||
#include <vector>
|
||||
|
||||
namespace
|
||||
@@ -39,6 +45,72 @@ namespace
|
||||
std::istreambuf_iterator<char>{}};
|
||||
}
|
||||
|
||||
void write_octal(std::span<std::byte> dst, std::uint64_t val)
|
||||
{
|
||||
dst.back() = std::byte{0};
|
||||
std::size_t pos = dst.size() - 1;
|
||||
while (pos > 0) {
|
||||
--pos;
|
||||
dst[pos] = static_cast<std::byte>('0' + (val & 7ULL));
|
||||
val >>= 3ULL;
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::byte> make_raw_tar_ustar(
|
||||
std::span<const std::tuple<std::string_view, std::string_view, char,
|
||||
std::string_view>>
|
||||
entries)
|
||||
{
|
||||
std::vector<std::byte> out;
|
||||
for (const auto& [path, content, typeflag, link] : entries) {
|
||||
std::array<std::byte, 512> hdr{};
|
||||
std::memcpy(hdr.data(), path.data(),
|
||||
std::min<std::size_t>(path.size(), 100));
|
||||
write_octal(std::span{hdr}.subspan(100, 8),
|
||||
typeflag == '5' ? 0755ULL : 0644ULL);
|
||||
write_octal(std::span{hdr}.subspan(108, 8), 0);
|
||||
write_octal(std::span{hdr}.subspan(116, 8), 0);
|
||||
const std::uint64_t sz = (typeflag == '0') ? content.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, std::byte{' '});
|
||||
hdr[156] = static_cast<std::byte>(typeflag);
|
||||
if (!link.empty()) {
|
||||
std::memcpy(hdr.data() + 157, link.data(),
|
||||
std::min<std::size_t>(link.size(), 100));
|
||||
}
|
||||
std::memcpy(hdr.data() + 257, "ustar\0", 6);
|
||||
hdr[263] = std::byte{'0'};
|
||||
hdr[264] = std::byte{'0'};
|
||||
std::uint32_t sum = 0;
|
||||
for (const std::byte b : hdr) {
|
||||
sum += static_cast<std::uint8_t>(b);
|
||||
}
|
||||
write_octal(std::span{hdr}.subspan(148, 7), sum);
|
||||
hdr[155] = std::byte{' '};
|
||||
|
||||
out.insert(out.end(), hdr.begin(), hdr.end());
|
||||
if (typeflag == '0' && !content.empty()) {
|
||||
const auto cb =
|
||||
std::as_bytes(std::span{content.data(), content.size()});
|
||||
out.insert(out.end(), cb.begin(), cb.end());
|
||||
const std::size_t rem = content.size() % 512U;
|
||||
if (rem != 0) {
|
||||
out.resize(out.size() + (512U - rem), std::byte{0});
|
||||
}
|
||||
}
|
||||
}
|
||||
out.resize(out.size() + 1024U, std::byte{0});
|
||||
return out;
|
||||
}
|
||||
|
||||
ArchiveCompression default_test_compression() noexcept
|
||||
{
|
||||
return has_libarchive_backend() ? ArchiveCompression::Zstd
|
||||
: ArchiveCompression::None;
|
||||
}
|
||||
|
||||
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
|
||||
std::vector<std::byte> make_raw_tar(
|
||||
std::span<const std::tuple<std::string_view, std::string_view,
|
||||
unsigned int, std::string_view>>
|
||||
@@ -95,6 +167,7 @@ namespace
|
||||
Void::Testing::require(archive_write_close(writer.get()) == ARCHIVE_OK);
|
||||
return out;
|
||||
}
|
||||
#endif
|
||||
} // namespace
|
||||
|
||||
Void::Testing::Test archive_reader_reproducible_skip_and_forensic_listing()
|
||||
@@ -116,7 +189,7 @@ Void::Testing::Test archive_reader_reproducible_skip_and_forensic_listing()
|
||||
|
||||
VectorByteSink sink_a;
|
||||
VectorByteSink sink_b;
|
||||
CreationOptions copts{.compression = ArchiveCompression::Zstd,
|
||||
CreationOptions copts{.compression = default_test_compression(),
|
||||
.reproducible = true};
|
||||
Void::Testing::require(create_archive(sink_a, order_a, copts).has_value());
|
||||
Void::Testing::require(create_archive(sink_b, order_b, copts).has_value());
|
||||
@@ -173,8 +246,26 @@ Void::Testing::Test archive_reader_reproducible_skip_and_forensic_listing()
|
||||
Void::Testing::expect(zero_entries.validate().has_value());
|
||||
}
|
||||
|
||||
// 4. File-as-parent conflict rejected cleanly (both orderings).
|
||||
// 4. File-as-parent conflict rejected cleanly (pure USTAR works with and
|
||||
// without LibArchive; additionally exercise zstd when LibArchive exists).
|
||||
{
|
||||
const std::array<
|
||||
std::tuple<std::string_view, std::string_view, char,
|
||||
std::string_view>,
|
||||
2>
|
||||
conflict_ustar{{
|
||||
{"foo", "file-bytes", '0', ""},
|
||||
{"foo/child", "nested", '0', ""},
|
||||
}};
|
||||
const auto raw_ustar = make_raw_tar_ustar(conflict_ustar);
|
||||
SpanByteSource src{raw_ustar};
|
||||
auto listed = list_entries(src, {}, false);
|
||||
Void::Testing::require(!listed.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
listed.error().code().value,
|
||||
static_cast<std::int32_t>(ArchiveErrorCode::unsafe_entry));
|
||||
|
||||
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
|
||||
const std::array<
|
||||
std::tuple<std::string_view, std::string_view, unsigned int,
|
||||
std::string_view>,
|
||||
@@ -184,26 +275,27 @@ Void::Testing::Test archive_reader_reproducible_skip_and_forensic_listing()
|
||||
{"foo/child", "nested", AE_IFREG, ""},
|
||||
}};
|
||||
const auto raw = make_raw_tar(conflict_entries);
|
||||
SpanByteSource src{raw};
|
||||
auto listed = list_entries(src, {}, false);
|
||||
Void::Testing::require(!listed.has_value());
|
||||
SpanByteSource src_la{raw};
|
||||
auto listed_la = list_entries(src_la, {}, false);
|
||||
Void::Testing::require(!listed_la.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
listed.error().code().value,
|
||||
listed_la.error().code().value,
|
||||
static_cast<std::int32_t>(ArchiveErrorCode::unsafe_entry));
|
||||
#endif
|
||||
}
|
||||
|
||||
// 5. Normal vs forensic listing + sanitized diagnostics.
|
||||
{
|
||||
const std::array<
|
||||
std::tuple<std::string_view, std::string_view, unsigned int,
|
||||
std::tuple<std::string_view, std::string_view, char,
|
||||
std::string_view>,
|
||||
3>
|
||||
mixed{{
|
||||
{"safe.txt", "ok", AE_IFREG, ""},
|
||||
{"bad\nlink", "", AE_IFLNK, "/etc/passwd"},
|
||||
{"../escape", "nope", AE_IFREG, ""},
|
||||
mixed_ustar{{
|
||||
{"safe.txt", "ok", '0', ""},
|
||||
{"bad\nlink", "", '2', "/etc/passwd"},
|
||||
{"../escape", "nope", '0', ""},
|
||||
}};
|
||||
const auto raw = make_raw_tar(mixed);
|
||||
const auto raw = make_raw_tar_ustar(mixed_ustar);
|
||||
|
||||
SpanByteSource src1{raw};
|
||||
Void::Testing::expect(!list_entries(src1, {}, false).has_value());
|
||||
@@ -226,10 +318,123 @@ Void::Testing::Test archive_reader_reproducible_skip_and_forensic_listing()
|
||||
std::string{"a\\nb\\rc"});
|
||||
}
|
||||
|
||||
Void::Testing::Test archive_create_formats_builtin_ustar_pax_and_gzip()
|
||||
{
|
||||
Void::FileSystem::TempDir tmp{"void_archive_formats_"};
|
||||
|
||||
// Built-in pure-C++ USTAR/PAX creation works regardless of LibArchive,
|
||||
// handles long PAX paths (>120 bytes), custom canonical metadata, and
|
||||
// produces byte-identical output across runs and entry permutations.
|
||||
const std::string long_path =
|
||||
"very/deep/nested/package/hierarchy/with/many/subdirectories/"
|
||||
"extending/well/past/one/hundred/bytes/component/artifact.txt";
|
||||
const std::array<CreateEntry, 3> entries_a{{
|
||||
CreateEntry{.path = long_path,
|
||||
.type = EntryType::RegularFile,
|
||||
.executable = false,
|
||||
.content = to_bytes("pax-long-path-content")},
|
||||
CreateEntry{.path = "bin/tool",
|
||||
.type = EntryType::RegularFile,
|
||||
.executable = false,
|
||||
.content = to_bytes("tool-bytes"),
|
||||
.mode = 0755U},
|
||||
CreateEntry{.path = "bin/", .type = EntryType::Directory},
|
||||
}};
|
||||
const std::array<CreateEntry, 3> entries_b{
|
||||
entries_a[2], entries_a[0], entries_a[1]};
|
||||
|
||||
CreationOptions builtin_opts{
|
||||
.compression = ArchiveCompression::None,
|
||||
.reproducible = true,
|
||||
.canonical_mtime = 1700000000,
|
||||
.canonical_uid = 1000,
|
||||
.canonical_gid = 1000,
|
||||
.prefer_builtin_tar = true,
|
||||
};
|
||||
|
||||
VectorByteSink raw1;
|
||||
VectorByteSink raw2;
|
||||
Void::Testing::require(create(raw1, entries_a, builtin_opts).has_value());
|
||||
Void::Testing::require(create(raw2, entries_b, builtin_opts).has_value());
|
||||
Void::Testing::expect_eq(raw1.bytes(), raw2.bytes());
|
||||
|
||||
const auto tar_file = tmp / "builtin.tar";
|
||||
Void::Testing::require(create(tar_file, entries_a, builtin_opts).has_value());
|
||||
auto extracted = extract(tar_file, tmp / "unpacked_tar");
|
||||
Void::Testing::require(extracted.has_value());
|
||||
Void::Testing::expect_eq(read_file_str(tmp / "unpacked_tar" / long_path),
|
||||
std::string{"pax-long-path-content"});
|
||||
Void::Testing::expect_eq(read_file_str(tmp / "unpacked_tar/bin/tool"),
|
||||
std::string{"tool-bytes"});
|
||||
|
||||
struct stat st_tool{};
|
||||
Void::Testing::require(::stat((tmp / "unpacked_tar/bin/tool").c_str(),
|
||||
&st_tool) == 0);
|
||||
Void::Testing::expect_eq(st_tool.st_mode & 0777, mode_t{0755});
|
||||
|
||||
// Staged extraction over built-in tar also succeeds (exercising
|
||||
// LibArchive interop when LibArchive is linked, or built-in Reader when
|
||||
// LibArchive is absent).
|
||||
auto staged_tar = extract_staged(tar_file, tmp / "staged_tar");
|
||||
Void::Testing::require(staged_tar.has_value());
|
||||
auto pub_tar = staged_tar->publish("v1");
|
||||
Void::Testing::require(pub_tar.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
read_file_str(tmp / "staged_tar/v1" / long_path),
|
||||
std::string{"pax-long-path-content"});
|
||||
|
||||
if (has_libarchive_backend()) {
|
||||
CreationOptions gzip_opts{
|
||||
.compression = ArchiveCompression::Gzip,
|
||||
.reproducible = true,
|
||||
.canonical_mtime = 1700000000,
|
||||
};
|
||||
VectorByteSink gz1;
|
||||
VectorByteSink gz2;
|
||||
Void::Testing::require(create(gz1, entries_a, gzip_opts).has_value());
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds{15});
|
||||
Void::Testing::require(create(gz2, entries_b, gzip_opts).has_value());
|
||||
Void::Testing::expect_eq(gz1.bytes(), gz2.bytes());
|
||||
|
||||
const auto gz_path = tmp / "bundle.tar.gz";
|
||||
Void::Testing::require(
|
||||
create(gz_path, entries_a, gzip_opts).has_value());
|
||||
auto gz_ext = extract(gz_path, tmp / "unpacked_gz");
|
||||
Void::Testing::require(gz_ext.has_value());
|
||||
Void::Testing::expect_eq(read_file_str(tmp / "unpacked_gz" / long_path),
|
||||
std::string{"pax-long-path-content"});
|
||||
|
||||
auto gz_staged = extract_staged(gz_path, tmp / "staged_gz");
|
||||
Void::Testing::require(gz_staged.has_value());
|
||||
Void::Testing::require(gz_staged->publish("v1").has_value());
|
||||
Void::Testing::expect_eq(
|
||||
read_file_str(tmp / "staged_gz/v1/bin/tool"),
|
||||
std::string{"tool-bytes"});
|
||||
} else {
|
||||
VectorByteSink unused;
|
||||
auto zst_err =
|
||||
create(unused, entries_a,
|
||||
CreationOptions{.compression = ArchiveCompression::Zstd});
|
||||
Void::Testing::require(!zst_err.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
zst_err.error().code().value,
|
||||
static_cast<std::int32_t>(ArchiveErrorCode::unsupported_format));
|
||||
|
||||
auto gz_err =
|
||||
create(unused, entries_a,
|
||||
CreationOptions{.compression = ArchiveCompression::Gzip});
|
||||
Void::Testing::require(!gz_err.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
gz_err.error().code().value,
|
||||
static_cast<std::int32_t>(ArchiveErrorCode::unsupported_format));
|
||||
}
|
||||
}
|
||||
|
||||
Void::Testing::Test archive_staged_extraction_atomic_publish_unknown_and_cleanup()
|
||||
{
|
||||
Void::FileSystem::TempDir tmp{"void_archive_staged_"};
|
||||
const auto archive_path = tmp / "pkg.tar.zst";
|
||||
const auto archive_path =
|
||||
tmp / (has_libarchive_backend() ? "pkg.tar.zst" : "pkg.tar");
|
||||
const auto parent_dir = tmp / "versions";
|
||||
std::filesystem::create_directories(parent_dir);
|
||||
|
||||
@@ -243,7 +448,9 @@ Void::Testing::Test archive_staged_extraction_atomic_publish_unknown_and_cleanup
|
||||
.executable = false,
|
||||
.content = to_bytes("key=val")},
|
||||
}};
|
||||
Void::Testing::require(create_archive(archive_path, entries).has_value());
|
||||
const CreationOptions create_opts{.compression = default_test_compression()};
|
||||
Void::Testing::require(
|
||||
create_archive(archive_path, entries, create_opts).has_value());
|
||||
|
||||
// 1. Staged extraction + atomic no-replace publication + safe modes.
|
||||
std::size_t progress_calls = 0;
|
||||
@@ -344,7 +551,8 @@ Void::Testing::Test archive_isolated_worker_extracts_verifies_and_publishes()
|
||||
{
|
||||
#ifdef VOID_ARCHIVE_WORKER_PATH
|
||||
Void::FileSystem::TempDir tmp{"void_archive_iso_"};
|
||||
const auto archive_path = tmp / "untrusted.tar.zst";
|
||||
const auto archive_path =
|
||||
tmp / (has_libarchive_backend() ? "untrusted.tar.zst" : "untrusted.tar");
|
||||
const auto parent_dir = tmp / "out";
|
||||
std::filesystem::create_directories(parent_dir);
|
||||
|
||||
@@ -358,7 +566,10 @@ Void::Testing::Test archive_isolated_worker_extracts_verifies_and_publishes()
|
||||
.executable = false,
|
||||
.content = to_bytes("verified-by-parent")},
|
||||
}};
|
||||
Void::Testing::require(create_archive(archive_path, entries).has_value());
|
||||
Void::Testing::require(
|
||||
create_archive(archive_path, entries,
|
||||
CreationOptions{.compression = default_test_compression()})
|
||||
.has_value());
|
||||
|
||||
IsolationOptions iso{};
|
||||
iso.worker_executable = VOID_ARCHIVE_WORKER_PATH;
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
|
||||
#include <array>
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
|
||||
namespace
|
||||
{
|
||||
@@ -20,19 +21,122 @@ Void::Testing::Test crypto_known_hash_vectors()
|
||||
auto sha1 = Void::Crypto::sha1("abc");
|
||||
auto sha256 = Void::Crypto::sha256("abc");
|
||||
auto sha512 = Void::Crypto::sha512("abc");
|
||||
auto b2_256 = Void::Crypto::blake2b256("abc");
|
||||
auto b2_512 = Void::Crypto::blake2b512("abc");
|
||||
Void::Testing::require(sha1.has_value());
|
||||
Void::Testing::require(sha256.has_value());
|
||||
Void::Testing::require(sha512.has_value());
|
||||
Void::Testing::require(b2_256.has_value());
|
||||
Void::Testing::require(b2_512.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
hex(*sha1), std::string{"a9993e364706816aba3e25717850c26c9cd0d89d"});
|
||||
Void::Testing::expect_eq(hex(*sha256),
|
||||
std::string{"ba7816bf8f01cfea414140de5dae2223b0036"
|
||||
"1a396177a9cb410ff61f20015ad"});
|
||||
Void::Testing::expect_eq(
|
||||
hex(*sha256),
|
||||
std::string{"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f"
|
||||
"20015ad"});
|
||||
Void::Testing::expect_eq(
|
||||
hex(*sha512),
|
||||
std::string{
|
||||
"ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a21"
|
||||
"92992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f"});
|
||||
Void::Testing::expect_eq(
|
||||
hex(*b2_256),
|
||||
std::string{"bddd813c634239723171ef3fee98579b94964e3bb1cb3e427262c8c06"
|
||||
"8d52319"});
|
||||
Void::Testing::expect_eq(
|
||||
hex(*b2_512),
|
||||
std::string{
|
||||
"ba80a53f981c4d0d6a2797b69f12f6e94c212f14685ac4b74b12bb6fdbffa2d17d"
|
||||
"87c5392aab792dc252d5de4533cc9518d38aa8dbf1925ab92386edd4009923"});
|
||||
|
||||
// NIST CAVP multi-block & empty vectors on built-in backend and OpenSSL
|
||||
// backend (when available).
|
||||
const Void::Crypto::ProviderOptions builtin_opts{.prefer_builtin = true};
|
||||
const auto empty_bytes = std::span<const std::byte>{};
|
||||
auto b_sha256_empty =
|
||||
Void::Crypto::hash(Void::Crypto::HashAlgorithm::Sha256, empty_bytes,
|
||||
builtin_opts);
|
||||
Void::Testing::require(b_sha256_empty.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
hex(*b_sha256_empty),
|
||||
std::string{"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7"
|
||||
"852b855"});
|
||||
|
||||
constexpr std::string_view k448 =
|
||||
"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq";
|
||||
auto b_sha256_448 = Void::Crypto::hash(
|
||||
Void::Crypto::HashAlgorithm::Sha256,
|
||||
std::as_bytes(std::span{k448.data(), k448.size()}), builtin_opts);
|
||||
Void::Testing::require(b_sha256_448.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
hex(*b_sha256_448),
|
||||
std::string{"248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd41"
|
||||
"9db06c1"});
|
||||
|
||||
constexpr std::string_view k896 =
|
||||
"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmno"
|
||||
"ijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu";
|
||||
auto b_sha512_896 = Void::Crypto::hash(
|
||||
Void::Crypto::HashAlgorithm::Sha512,
|
||||
std::as_bytes(std::span{k896.data(), k896.size()}), builtin_opts);
|
||||
Void::Testing::require(b_sha512_896.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
hex(*b_sha512_896),
|
||||
std::string{
|
||||
"8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb688901850"
|
||||
"1d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909"});
|
||||
|
||||
auto b_b2_256_empty =
|
||||
Void::Crypto::hash(Void::Crypto::HashAlgorithm::Blake2b256, empty_bytes,
|
||||
builtin_opts);
|
||||
auto b_b2_512_empty =
|
||||
Void::Crypto::hash(Void::Crypto::HashAlgorithm::Blake2b512, empty_bytes,
|
||||
builtin_opts);
|
||||
Void::Testing::require(b_b2_256_empty.has_value());
|
||||
Void::Testing::require(b_b2_512_empty.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
hex(*b_b2_256_empty),
|
||||
std::string{"0e5751c026e543b2e8ab2eb06099daa1d1e5df47778f7787faab45cdf"
|
||||
"12fe3a8"});
|
||||
Void::Testing::expect_eq(
|
||||
hex(*b_b2_512_empty),
|
||||
std::string{
|
||||
"786a02f742015903c6c6fd852552d272912f4740e15847618a86e217f71f5419d2"
|
||||
"5e1031afee585313896444934eb04b903a685b1448b755d56f701afe9be2ce"});
|
||||
|
||||
// 1,000,000 x 'a' FIPS 180-4 SHA-256 test vector on built-in backend.
|
||||
{
|
||||
auto h = Void::Crypto::Hasher::create(Void::Crypto::HashAlgorithm::Sha256,
|
||||
builtin_opts);
|
||||
Void::Testing::require(h.has_value());
|
||||
const std::string chunk(1000, 'a');
|
||||
for (int i = 0; i < 1000; ++i) {
|
||||
Void::Testing::require(h->update(chunk).has_value());
|
||||
}
|
||||
auto big = h->finalize();
|
||||
Void::Testing::require(big.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
hex(*big),
|
||||
std::string{"cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39c"
|
||||
"cc7112cd0"});
|
||||
}
|
||||
|
||||
// Verify OpenSSL & built-in parity when OpenSSL is linked.
|
||||
if (Void::Crypto::has_openssl_backend()) {
|
||||
for (const auto alg : {Void::Crypto::HashAlgorithm::Sha1,
|
||||
Void::Crypto::HashAlgorithm::Sha256,
|
||||
Void::Crypto::HashAlgorithm::Sha512,
|
||||
Void::Crypto::HashAlgorithm::Blake2b512}) {
|
||||
auto d_ossl = Void::Crypto::hash(
|
||||
alg, std::as_bytes(std::span{k896.data(), k896.size()}));
|
||||
auto d_builtin = Void::Crypto::hash(
|
||||
alg, std::as_bytes(std::span{k896.data(), k896.size()}),
|
||||
builtin_opts);
|
||||
Void::Testing::require(d_ossl.has_value());
|
||||
Void::Testing::require(d_builtin.has_value());
|
||||
Void::Testing::expect_eq(*d_ossl, *d_builtin);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Void::Testing::Test crypto_streaming_and_file_hash_match()
|
||||
@@ -50,8 +154,45 @@ Void::Testing::Test crypto_streaming_and_file_hash_match()
|
||||
const auto path = temporary / "data";
|
||||
std::ofstream{path, std::ios::binary} << "abc";
|
||||
auto file = Void::Crypto::sha256File(path);
|
||||
auto file_snake = Void::Crypto::sha256_file(path);
|
||||
Void::Testing::require(file.has_value());
|
||||
Void::Testing::require(file_snake.has_value());
|
||||
Void::Testing::expect_eq(*file, *streamed);
|
||||
Void::Testing::expect_eq(*file_snake, *streamed);
|
||||
|
||||
// Odd-size streaming checks across block boundaries for built-in SHA-256 &
|
||||
// BLAKE2b (1, 7, 63, 64, 65, 127, 128, 129, 257).
|
||||
const std::string sample(300, 'x');
|
||||
const Void::Crypto::ProviderOptions builtin_opts{.prefer_builtin = true};
|
||||
for (const auto alg : {Void::Crypto::HashAlgorithm::Sha256,
|
||||
Void::Crypto::HashAlgorithm::Sha512,
|
||||
Void::Crypto::HashAlgorithm::Blake2b256,
|
||||
Void::Crypto::HashAlgorithm::Blake2b512}) {
|
||||
auto one_shot = Void::Crypto::hash(
|
||||
alg, std::as_bytes(std::span{sample.data(), sample.size()}),
|
||||
builtin_opts);
|
||||
Void::Testing::require(one_shot.has_value());
|
||||
for (const std::size_t step : {1U, 7U, 63U, 64U, 65U, 127U, 128U, 129U}) {
|
||||
auto sh = Void::Crypto::Hasher::create(alg, builtin_opts);
|
||||
Void::Testing::require(sh.has_value());
|
||||
for (std::size_t off = 0; off < sample.size(); off += step) {
|
||||
const auto len = std::min(step, sample.size() - off);
|
||||
Void::Testing::require(
|
||||
sh->update(std::string_view{sample}.substr(off, len))
|
||||
.has_value());
|
||||
}
|
||||
auto fin = sh->finalize();
|
||||
Void::Testing::require(fin.has_value());
|
||||
Void::Testing::expect_eq(*fin, *one_shot);
|
||||
}
|
||||
}
|
||||
|
||||
auto b2_256_f = Void::Crypto::blake2b256_file(path);
|
||||
auto b2_512_f = Void::Crypto::blake2b512_file(path);
|
||||
Void::Testing::require(b2_256_f.has_value());
|
||||
Void::Testing::require(b2_512_f.has_value());
|
||||
Void::Testing::expect_eq(*b2_256_f, *Void::Crypto::blake2b256("abc"));
|
||||
Void::Testing::expect_eq(*b2_512_f, *Void::Crypto::blake2b512("abc"));
|
||||
}
|
||||
|
||||
Void::Testing::Test crypto_ed25519_rfc8032_vector()
|
||||
@@ -67,6 +208,15 @@ Void::Testing::Test crypto_ed25519_rfc8032_vector()
|
||||
std::as_bytes(std::span{publicText->data(), publicText->size()});
|
||||
const auto signature =
|
||||
std::as_bytes(std::span{signatureText->data(), signatureText->size()});
|
||||
if (!Void::Crypto::has_openssl_backend()) {
|
||||
auto unavail = Void::Crypto::verifyEd25519({}, signature, publicKey);
|
||||
Void::Testing::require(!unavail.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
unavail.error().code().value,
|
||||
static_cast<std::int32_t>(
|
||||
Void::Crypto::CryptoErrorCode::unsupported_algorithm));
|
||||
return;
|
||||
}
|
||||
auto valid = Void::Crypto::verifyEd25519({}, signature, publicKey);
|
||||
Void::Testing::require(valid.has_value());
|
||||
Void::Testing::expect(*valid);
|
||||
|
||||
@@ -123,6 +123,35 @@ Void::Testing::Test crypto_ed25519_signing_vectors_and_boundaries()
|
||||
{
|
||||
using namespace Void::Crypto;
|
||||
|
||||
if (!has_openssl_backend()) {
|
||||
auto gen_unavail = Ed25519PrivateKey::generate();
|
||||
Void::Testing::require(!gen_unavail.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
gen_unavail.error().code().value,
|
||||
static_cast<std::int32_t>(CryptoErrorCode::unsupported_algorithm));
|
||||
|
||||
const std::array<std::byte, Ed25519PublicKeySize> dummy_pub{};
|
||||
const std::array<std::byte, Ed25519SignatureSize> dummy_sig{};
|
||||
for (const std::size_t bad_key_len : {0U, 1U, 31U, 33U, 64U}) {
|
||||
std::vector<std::byte> bad_key(bad_key_len, std::byte{0x11});
|
||||
auto r = verifyEd25519({}, dummy_sig, bad_key);
|
||||
Void::Testing::require(!r.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
r.error().code().value,
|
||||
static_cast<std::int32_t>(CryptoErrorCode::invalid_key_size));
|
||||
}
|
||||
for (const std::size_t bad_sig_len : {0U, 1U, 63U, 65U}) {
|
||||
std::vector<std::byte> bad_sig(bad_sig_len, std::byte{0x22});
|
||||
auto r = verifyEd25519({}, bad_sig, dummy_pub);
|
||||
Void::Testing::require(!r.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
r.error().code().value,
|
||||
static_cast<std::int32_t>(
|
||||
CryptoErrorCode::invalid_signature_size));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
struct Rfc8032Vector {
|
||||
std::string_view seed_hex;
|
||||
std::string_view pub_hex;
|
||||
@@ -357,6 +386,30 @@ Void::Testing::Test crypto_hmac_sha256_and_hkdf_sha256_vectors_and_guards()
|
||||
[](std::byte b) { return b == std::byte{0x00}; }));
|
||||
}
|
||||
|
||||
// Also verify built-in HMAC-SHA-256 and HKDF-SHA-256 produce identical
|
||||
// outputs without OpenSSL.
|
||||
{
|
||||
const ProviderOptions builtin_opts{.prefer_builtin = true};
|
||||
const std::vector<std::byte> key(20, std::byte{0x0b});
|
||||
auto mac = hmac_sha256(key, as_bytes("Hi There"), builtin_opts);
|
||||
Void::Testing::require(mac.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
to_hex(*mac),
|
||||
std::string{"b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e93"
|
||||
"76c2e32cff7"});
|
||||
|
||||
const std::vector<std::byte> ikm(22, std::byte{0x0b});
|
||||
const auto salt = from_hex("000102030405060708090a0b0c");
|
||||
const auto info = from_hex("f0f1f2f3f4f5f6f7f8f9");
|
||||
std::array<std::byte, 42> okm{};
|
||||
auto r = hkdf_sha256(ikm, salt, info, okm, builtin_opts);
|
||||
Void::Testing::require(r.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
to_hex(okm),
|
||||
std::string{"3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02"
|
||||
"d56ecc4c5bf34007208d5b887185865"});
|
||||
}
|
||||
|
||||
// constant_time_equal checks
|
||||
const auto a = from_hex("01020304");
|
||||
const auto b = from_hex("01020304");
|
||||
|
||||
Reference in new issue
Block a user