Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
285 changes: 285 additions & 0 deletions src/Storages/ObjectStorage/DataLakes/Iceberg/Encryption.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,285 @@
#include "config.h"

#include <Storages/ObjectStorage/DataLakes/Iceberg/Encryption.h>

#include <Common/Base64.h>
#include <Common/Exception.h>
#include <Storages/ObjectStorage/DataLakes/Iceberg/Constant.h>

#include <Poco/JSON/Array.h>
#include <Poco/Util/AbstractConfiguration.h>

#include <limits>

#if USE_SSL
# include <openssl/evp.h>
#endif

namespace DB
{

namespace ErrorCodes
{
extern const int BAD_ARGUMENTS;
extern const int ICEBERG_SPECIFICATION_VIOLATION;
extern const int INCORRECT_DATA;
extern const int SUPPORT_IS_DISABLED;
}

namespace Iceberg
{

namespace
{

constexpr auto encryption_keys_field = "encryption-keys";
constexpr auto encrypted_key_metadata_field = "encrypted-key-metadata";
constexpr auto encrypted_by_id_field = "encrypted-by-id";
constexpr auto key_timestamp_property = "KEY_TIMESTAMP";
constexpr auto table_key_id_property = "encryption.key-id";
constexpr auto master_keys_config = "iceberg_encryption_master_keys";

constexpr size_t nonce_length = 12;
constexpr size_t tag_length = 16;
constexpr size_t plain_block_size = 1024 * 1024;
constexpr size_t cipher_block_size = plain_block_size + nonce_length + tag_length;
constexpr std::string_view stream_magic = "AGS1";
constexpr size_t stream_header_length = 8;
constexpr char key_metadata_version = 1;

/// Decrypts `nonce | ciphertext | tag`, the layout of the AES GCM ciphers of Iceberg.
String decryptAesGcm(std::string_view key, std::string_view ciphertext, std::string_view aad)
{
#if USE_SSL
const EVP_CIPHER * cipher = nullptr;
switch (key.size())
{
case 16: cipher = EVP_aes_128_gcm(); break;
case 24: cipher = EVP_aes_192_gcm(); break;
case 32: cipher = EVP_aes_256_gcm(); break;
default:
throw Exception(ErrorCodes::INCORRECT_DATA, "Invalid AES key length {}: must be 16, 24 or 32 bytes", key.size());
}
if (ciphertext.size() < nonce_length + tag_length)
throw Exception(
ErrorCodes::INCORRECT_DATA, "Cannot decrypt {} bytes with AES GCM: shorter than the nonce and the tag", ciphertext.size());
if (ciphertext.size() > static_cast<size_t>(std::numeric_limits<int>::max()) || aad.size() > static_cast<size_t>(std::numeric_limits<int>::max()))
throw Exception(ErrorCodes::INCORRECT_DATA, "Cannot decrypt {} bytes with AES GCM: too large", ciphertext.size());

const auto * nonce = reinterpret_cast<const unsigned char *>(ciphertext.data());
const auto data = ciphertext.substr(nonce_length, ciphertext.size() - nonce_length - tag_length);
String tag(ciphertext.substr(ciphertext.size() - tag_length));
String plaintext(data.size(), '\0');
auto * out = reinterpret_cast<unsigned char *>(plaintext.data());

std::unique_ptr<EVP_CIPHER_CTX, decltype(&EVP_CIPHER_CTX_free)> ctx(EVP_CIPHER_CTX_new(), &EVP_CIPHER_CTX_free);
int len = 0;
const bool decrypted = ctx
&& EVP_DecryptInit_ex(ctx.get(), cipher, nullptr, nullptr, nullptr) == 1
&& EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_IVLEN, static_cast<int>(nonce_length), nullptr) == 1
&& EVP_DecryptInit_ex(ctx.get(), nullptr, nullptr, reinterpret_cast<const unsigned char *>(key.data()), nonce) == 1
&& (aad.empty()
|| EVP_DecryptUpdate(ctx.get(), nullptr, &len, reinterpret_cast<const unsigned char *>(aad.data()), static_cast<int>(aad.size())) == 1)
&& (data.empty()
|| EVP_DecryptUpdate(ctx.get(), out, &len, reinterpret_cast<const unsigned char *>(data.data()), static_cast<int>(data.size())) == 1)
&& EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_TAG, static_cast<int>(tag_length), tag.data()) == 1
&& EVP_DecryptFinal_ex(ctx.get(), out + data.size(), &len) == 1;
if (!decrypted)
throw Exception(ErrorCodes::INCORRECT_DATA, "AES GCM decryption failed: the key is wrong, or the data is corrupted");
return plaintext;
#else
UNUSED(key, ciphertext, aad);
throw Exception(ErrorCodes::SUPPORT_IS_DISABLED, "Reading encrypted Iceberg tables requires a build with SSL");
#endif
}

/// `StandardKeyMetadata` of iceberg-java: a version byte, then an Avro record of
/// `encryption_key: bytes`, `aad_prefix: union {null, bytes}` and `file_length: union {null, long}`.
struct StandardKeyMetadata
{
String encryption_key;
String aad_prefix;
std::optional<Int64> file_length;
};

class KeyMetadataReader
{
public:
explicit KeyMetadataReader(std::string_view buffer_) : buffer(buffer_) {}

Int64 readLong()
{
UInt64 value = 0;
for (size_t shift = 0;; shift += 7)
{
if (pos >= buffer.size() || shift > 63)
throw Exception(ErrorCodes::INCORRECT_DATA, "Malformed Iceberg key metadata");
const auto byte = static_cast<UInt8>(buffer[pos++]);
value |= static_cast<UInt64>(byte & 0x7F) << shift;
if ((byte & 0x80) == 0)
break;
}
return static_cast<Int64>((value >> 1) ^ (0 - (value & 1)));
}

String readBytes()
{
const Int64 length = readLong();
if (length < 0 || static_cast<UInt64>(length) > buffer.size() - pos)
throw Exception(ErrorCodes::INCORRECT_DATA, "Malformed Iceberg key metadata: invalid length {}", length);
String result(buffer.substr(pos, static_cast<size_t>(length)));
pos += static_cast<size_t>(length);
return result;
}

/// The branch of a `union {null, T}`: whether T is present.
bool readOptionalBranch()
{
const Int64 branch = readLong();
if (branch != 0 && branch != 1)
throw Exception(ErrorCodes::INCORRECT_DATA, "Malformed Iceberg key metadata: invalid union branch {}", branch);
return branch == 1;
}

private:
std::string_view buffer;
size_t pos = 0;
};

StandardKeyMetadata parseKeyMetadata(std::string_view buffer)
{
if (buffer.empty() || buffer[0] != key_metadata_version)
throw Exception(ErrorCodes::INCORRECT_DATA, "Unsupported Iceberg key metadata version");
KeyMetadataReader reader(buffer.substr(1));
StandardKeyMetadata result;
result.encryption_key = reader.readBytes();
if (reader.readOptionalBranch())
result.aad_prefix = reader.readBytes();
if (reader.readOptionalBranch())
result.file_length = reader.readLong();
return result;
}

String getMasterKey(const Poco::Util::AbstractConfiguration & config, const String & key_id)
{
Poco::Util::AbstractConfiguration::Keys keys;
config.keys(master_keys_config, keys);
for (const auto & key : keys)
{
const String path = fmt::format("{}.{}", master_keys_config, key);
if (config.getString(path + "[@id]", "") == key_id)
return base64Decode(config.getString(path));
}
throw Exception(
ErrorCodes::BAD_ARGUMENTS,
"The master key `{}` of the encrypted Iceberg table is not in the server configuration `{}`",
key_id,
master_keys_config);
}

Poco::JSON::Object::Ptr findEncryptionKey(const Poco::JSON::Object::Ptr & metadata, const String & key_id)
{
if (metadata->has(encryption_keys_field))
{
const auto keys = metadata->getArray(encryption_keys_field);
for (UInt32 i = 0; keys && i < keys->size(); ++i)
{
auto key = keys->getObject(i);
if (key->getValue<String>(f_key_id) == key_id)
return key;
}
}
throw Exception(ErrorCodes::ICEBERG_SPECIFICATION_VIOLATION, "Cannot find the encryption key `{}` in the table metadata", key_id);
}

String getEncryptedById(const Poco::JSON::Object::Ptr & key)
{
if (!key->has(encrypted_by_id_field) || key->isNull(encrypted_by_id_field))
throw Exception(
ErrorCodes::ICEBERG_SPECIFICATION_VIOLATION, "The encryption key `{}` has no `{}`", key->getValue<String>(f_key_id), encrypted_by_id_field);
return key->getValue<String>(encrypted_by_id_field);
}

}

std::optional<String> getManifestListKeyMetadata(
const Poco::JSON::Object::Ptr & metadata, const Poco::JSON::Object::Ptr & snapshot, const Poco::Util::AbstractConfiguration & config)
{
if (!snapshot->has(f_key_id) || snapshot->isNull(f_key_id))
return std::nullopt;
const String manifest_list_key_id = snapshot->getValue<String>(f_key_id);

String table_key_id;
if (metadata->has(f_properties) && !metadata->isNull(f_properties))
table_key_id = metadata->getObject(f_properties)->optValue<String>(table_key_id_property, "");
if (table_key_id.empty())
throw Exception(
ErrorCodes::ICEBERG_SPECIFICATION_VIOLATION,
"The manifest list of a snapshot is encrypted with the key `{}`, but the table has no `{}` property",
manifest_list_key_id,
table_key_id_property);

const auto manifest_list_key = findEncryptionKey(metadata, manifest_list_key_id);
const String kek_id = getEncryptedById(manifest_list_key);
if (kek_id == table_key_id)
throw Exception(ErrorCodes::ICEBERG_SPECIFICATION_VIOLATION, "The encryption key `{}` is not a manifest list key", manifest_list_key_id);

const auto kek_entry = findEncryptionKey(metadata, kek_id);
if (getEncryptedById(kek_entry) != table_key_id)
throw Exception(
ErrorCodes::ICEBERG_SPECIFICATION_VIOLATION, "The key encryption key `{}` is not wrapped by the table key `{}`", kek_id, table_key_id);

String timestamp;
if (kek_entry->has(f_properties) && !kek_entry->isNull(f_properties))
timestamp = kek_entry->getObject(f_properties)->optValue<String>(key_timestamp_property, "");
if (timestamp.empty())
throw Exception(ErrorCodes::ICEBERG_SPECIFICATION_VIOLATION, "The key encryption key `{}` has no `{}`", kek_id, key_timestamp_property);

/// The KMS wraps a KEK with AES GCM under the master key. The KEK timestamp is the AAD of the key metadata,
/// so that the timestamp cannot be changed.
const String kek = decryptAesGcm(getMasterKey(config, table_key_id), base64Decode(kek_entry->getValue<String>(encrypted_key_metadata_field)), "");
return decryptAesGcm(kek, base64Decode(manifest_list_key->getValue<String>(encrypted_key_metadata_field)), timestamp);
}

String decryptAesGcmStream(const String & encrypted, const String & key_metadata, const String & file_path)
{
const auto key = parseKeyMetadata(key_metadata);

/// The length in the key metadata is trusted, so it detects a truncated file.
if (key.file_length && *key.file_length != static_cast<Int64>(encrypted.size()))
throw Exception(
ErrorCodes::INCORRECT_DATA,
"The encrypted file {} has {} bytes, but its key metadata says {}",
file_path,
encrypted.size(),
*key.file_length);

const std::string_view data(encrypted);
if (data.size() < stream_header_length + nonce_length + tag_length || !data.starts_with(stream_magic))
throw Exception(ErrorCodes::INCORRECT_DATA, "The file {} is not an AES GCM stream", file_path);
UInt32 block_size = 0;
for (size_t i = 0; i < 4; ++i)
block_size |= static_cast<UInt32>(static_cast<UInt8>(data[stream_magic.size() + i])) << (8 * i);
if (block_size != plain_block_size)
throw Exception(ErrorCodes::INCORRECT_DATA, "The AES GCM stream {} has an unsupported block size {}", file_path, block_size);

const auto stream = data.substr(stream_header_length);
String result;
result.reserve(stream.size());
UInt32 block_index = 0;
for (size_t offset = 0; offset < stream.size(); offset += cipher_block_size, ++block_index)
{
if (block_index > static_cast<UInt32>(std::numeric_limits<Int32>::max()))
throw Exception(ErrorCodes::INCORRECT_DATA, "The AES GCM stream {} has too many blocks", file_path);
/// The AAD of a block is the AAD prefix and the block index as a little-endian int32.
String aad = key.aad_prefix;
for (size_t i = 0; i < 4; ++i)
aad.push_back(static_cast<char>((block_index >> (8 * i)) & 0xFF));
result += decryptAesGcm(key.encryption_key, stream.substr(offset, cipher_block_size), aad);
}
return result;
}

}

}
34 changes: 34 additions & 0 deletions src/Storages/ObjectStorage/DataLakes/Iceberg/Encryption.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#pragma once

#include <Core/Types.h>

#include <Poco/JSON/Object.h>

#include <optional>

namespace Poco::Util
{
class AbstractConfiguration;
}

namespace DB::Iceberg
{

/// Reading of Iceberg tables with envelope encryption, compatible with `StandardEncryptionManager` of iceberg-java.
///
/// The table master key `encryption.key-id` is in a KMS. Key encryption keys (KEKs) are wrapped by the master key and
/// stored in `encryption-keys` of the table metadata. The key metadata of the manifest list of a snapshot (its `key-id`)
/// is also there, encrypted by a KEK. The manifest list and the manifests are AES GCM streams (AGS1), and the manifest
/// list holds the key metadata of each manifest.
///
/// The KMS is the server configuration: the master keys are the base64 values of
/// `<iceberg_encryption_master_keys><key id="...">...</key></iceberg_encryption_master_keys>`.

/// The serialized `StandardKeyMetadata` of the manifest list of `snapshot`, or nullopt if the manifest list is not encrypted.
std::optional<String> getManifestListKeyMetadata(
const Poco::JSON::Object::Ptr & metadata, const Poco::JSON::Object::Ptr & snapshot, const Poco::Util::AbstractConfiguration & config);

/// Decrypts the contents of an AES GCM stream file with its serialized `StandardKeyMetadata`.
String decryptAesGcmStream(const String & encrypted, const String & key_metadata, const String & file_path);

}
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@
#include <Disks/DiskObjectStorage/ObjectStorages/IObjectStorage.h>
#include <Storages/ColumnsDescription.h>
#include <Storages/ObjectStorage/DataLakes/Common/AvroForIcebergDeserializer.h>
#include <Storages/ObjectStorage/DataLakes/Iceberg/Encryption.h>
#include <Interpreters/ProcessList.h>
#include <Storages/ObjectStorage/DataLakes/Iceberg/BinPackRewrite.h>
#include <Storages/ObjectStorage/DataLakes/Iceberg/Constant.h>
Expand Down Expand Up @@ -436,7 +437,8 @@ void IcebergMetadata::backgroundMetadataPrefetcherThread()
auto manifest_file_ptr = Iceberg::getManifestFile(
object_storage, persistent_components, ctx, log,
entry.manifest_file_path,
*external_storages);
*external_storages,
entry.key_metadata);
}
}

Expand Down Expand Up @@ -585,7 +587,9 @@ IcebergDataSnapshotPtr IcebergMetadata::createIcebergDataSnapshotFromSnapshotJSO
Int32 schema_id = snapshot_object->getValue<Int32>(f_schema_id);

return std::make_shared<IcebergDataSnapshot>(
getManifestList(object_storage, persistent_components, local_context, manifest_list_file_path, log, *external_storages),
getManifestList(
object_storage, persistent_components, local_context, manifest_list_file_path, log, *external_storages,
getManifestListKeyMetadata(metadata_object, snapshot_object, local_context->getConfigRef())),
snapshot_id,
schema_id,
total_rows,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,8 @@ struct ManifestFileCacheKey
Iceberg::PartitionFieldSummaries partition_summaries;
Int64 live_files_count;
std::optional<UInt64> first_row_id;
/// Serialized `StandardKeyMetadata` of an encrypted manifest.
std::optional<String> key_metadata = {};
};

using ManifestFileCacheKeys = std::vector<ManifestFileCacheKey>;
Expand Down Expand Up @@ -117,6 +119,8 @@ struct IcebergMetadataFilesCacheCell : private boost::noncopyable
for (const auto & entry: manifest_file_cache_keys)
{
total_size += sizeof(ManifestFileCacheKey) + entry.manifest_file_path.serialize().capacity();
if (entry.key_metadata.has_value())
total_size += entry.key_metadata->capacity();
total_size += entry.partition_summaries.capacity() * sizeof(Iceberg::PartitionFieldSummary);
for (const auto & summary : entry.partition_summaries)
{
Expand Down
Loading
Loading