mirror of
https://github.com/openziti/ziti-sdk-c.git
synced 2026-11-07 03:00:42 +00:00
remove AES-GCM e2ee backends
This commit is contained in:
@@ -41,7 +41,6 @@ typedef enum {
|
||||
ziti_crypto_invalid = -1,
|
||||
ziti_crypto_none = 0,
|
||||
ziti_crypto_libsodium,
|
||||
ziti_crypto_aes_gcm,
|
||||
ziti_crypto_tls,
|
||||
} ziti_crypto_method;
|
||||
|
||||
|
||||
@@ -116,91 +116,9 @@ SET(ZITI_SRC_FILES
|
||||
e2ee/e2ee_none.c
|
||||
)
|
||||
|
||||
if (WIN32)
|
||||
list(APPEND ZITI_SRC_FILES e2ee/e2ee_aes_gcm_wincrypto.c)
|
||||
elseif (APPLE)
|
||||
list(APPEND ZITI_SRC_FILES e2ee/e2ee_aes_gcm_apple.c)
|
||||
else ()
|
||||
list(APPEND ZITI_SRC_FILES e2ee/e2ee_aes_gcm_ossl.c)
|
||||
endif ()
|
||||
|
||||
FILE(GLOB zitilib_FILES ${CMAKE_CURRENT_LIST_DIR}/zitilib/*.c)
|
||||
LIST(APPEND ZITI_SRC_FILES ${zitilib_FILES})
|
||||
|
||||
# AES-GCM for the Apple e2ee backend lives in CryptoKit, which is Swift-only, so
|
||||
# e2ee_aes_gcm_cryptokit.swift is compiled here and its object is archived into libziti
|
||||
# like any other. Deliberately NOT enable_language(Swift): that makes CMake pick swiftc as
|
||||
# the linker driver for every target that links ziti -- including downstream consumers --
|
||||
# and swiftc rejects flags like -pthread. Handing CMake a finished object keeps the build,
|
||||
# and every consumer's link line, plain C. The Swift runtime is part of the OS and is
|
||||
# autolinked from the object, so `clang prog.c libziti.a` needs no extra flags.
|
||||
if (APPLE)
|
||||
find_program(SWIFTC swiftc REQUIRED)
|
||||
|
||||
if (CMAKE_OSX_ARCHITECTURES)
|
||||
set(cryptokit_arch ${CMAKE_OSX_ARCHITECTURES})
|
||||
else ()
|
||||
set(cryptokit_arch ${CMAKE_SYSTEM_PROCESSOR})
|
||||
endif ()
|
||||
list(LENGTH cryptokit_arch cryptokit_arch_count)
|
||||
if (cryptokit_arch_count GREATER 1)
|
||||
message(FATAL_ERROR "e2ee CryptoKit shim: one architecture at a time, got '${cryptokit_arch}'")
|
||||
endif ()
|
||||
|
||||
# CryptoKit floors: macOS 10.15, iOS 13. arm64 macOS itself does not exist before 11.0.
|
||||
if (CMAKE_SYSTEM_NAME STREQUAL "iOS")
|
||||
# distinguish device vs simulator with CMAKE_OSX_SYSROOT
|
||||
if (CMAKE_OSX_SYSROOT MATCHES "[Ss]imulator")
|
||||
set(cryptokit_target ${cryptokit_arch}-apple-ios13.0-simulator)
|
||||
set(cryptokit_sdk iphonesimulator)
|
||||
else ()
|
||||
set(cryptokit_target ${cryptokit_arch}-apple-ios13.0)
|
||||
set(cryptokit_sdk iphoneos)
|
||||
endif ()
|
||||
elseif (cryptokit_arch STREQUAL "arm64")
|
||||
set(cryptokit_target ${cryptokit_arch}-apple-macosx11.0)
|
||||
set(cryptokit_sdk macosx)
|
||||
else ()
|
||||
set(cryptokit_target ${cryptokit_arch}-apple-macosx10.15)
|
||||
set(cryptokit_sdk macosx)
|
||||
endif ()
|
||||
|
||||
# CMAKE_OSX_SYSROOT is empty unless a toolchain set it
|
||||
if (CMAKE_OSX_SYSROOT)
|
||||
set(cryptokit_sysroot ${CMAKE_OSX_SYSROOT})
|
||||
else ()
|
||||
execute_process(COMMAND xcrun --sdk ${cryptokit_sdk} --show-sdk-path
|
||||
OUTPUT_VARIABLE cryptokit_sysroot OUTPUT_STRIP_TRAILING_WHITESPACE)
|
||||
endif ()
|
||||
|
||||
if (CMAKE_BUILD_TYPE STREQUAL "Debug")
|
||||
set(cryptokit_opt -Onone)
|
||||
else ()
|
||||
set(cryptokit_opt -O)
|
||||
endif ()
|
||||
|
||||
set(ZITI_CRYPTOKIT_OBJECT ${CMAKE_CURRENT_BINARY_DIR}/e2ee_aes_gcm_cryptokit.o)
|
||||
add_custom_command(
|
||||
OUTPUT ${ZITI_CRYPTOKIT_OBJECT}
|
||||
COMMAND ${SWIFTC} -c ${CMAKE_CURRENT_LIST_DIR}/e2ee/e2ee_aes_gcm_cryptokit.swift
|
||||
-o ${ZITI_CRYPTOKIT_OBJECT}
|
||||
-module-name ziti_cryptokit
|
||||
-parse-as-library
|
||||
-target ${cryptokit_target}
|
||||
# back-deploying below macOS 12.3 makes swiftc emit force-load references
|
||||
# to libswiftCompatibility*.a, which only exist in the Xcode toolchain and
|
||||
# would have to be added to every consumer's link line. This shim uses no
|
||||
# concurrency and no generics over Obj-C, so it needs none of those fixups.
|
||||
-runtime-compatibility-version none
|
||||
-sdk ${cryptokit_sysroot}
|
||||
${cryptokit_opt}
|
||||
DEPENDS ${CMAKE_CURRENT_LIST_DIR}/e2ee/e2ee_aes_gcm_cryptokit.swift
|
||||
COMMENT "Building Swift object e2ee_aes_gcm_cryptokit.o"
|
||||
VERBATIM)
|
||||
set_source_files_properties(${ZITI_CRYPTOKIT_OBJECT}
|
||||
PROPERTIES EXTERNAL_OBJECT TRUE GENERATED TRUE)
|
||||
endif ()
|
||||
|
||||
SET(ZITI_INCLUDE_DIRS
|
||||
PUBLIC ../includes
|
||||
PRIVATE ../inc_internal
|
||||
@@ -217,10 +135,6 @@ set(ziti_compile_defs
|
||||
PRIVATE ZITI_LOG_MODULE="${PROJECT_NAME}"
|
||||
)
|
||||
|
||||
if (NOT WIN32)
|
||||
find_package(OpenSSL REQUIRED)
|
||||
endif ()
|
||||
|
||||
function(define_file_basename_for_sources targetname)
|
||||
get_target_property(source_files "${targetname}" SOURCES)
|
||||
foreach(sourcefile ${source_files})
|
||||
@@ -262,21 +176,8 @@ function(config_ziti_library target)
|
||||
target_link_libraries(${target} PUBLIC atomic)
|
||||
endif ()
|
||||
|
||||
if (APPLE)
|
||||
# e2ee_aes_gcm_apple.c: P-256/ECDH via Security.framework, HKDF via CommonCrypto (libSystem)
|
||||
# e2ee_aes_gcm_cryptokit.swift: AES-GCM via CryptoKit
|
||||
target_link_libraries(${target}
|
||||
PUBLIC "-framework Security"
|
||||
PUBLIC "-framework CoreFoundation"
|
||||
PUBLIC "-framework CryptoKit"
|
||||
PUBLIC "-framework Foundation"
|
||||
)
|
||||
target_sources(${target} PRIVATE ${ZITI_CRYPTOKIT_OBJECT})
|
||||
endif ()
|
||||
|
||||
if (NOT WIN32)
|
||||
target_link_libraries(${target} PUBLIC m)
|
||||
target_link_libraries(${target} PUBLIC OpenSSL::Crypto)
|
||||
endif ()
|
||||
|
||||
|
||||
|
||||
@@ -571,7 +571,6 @@ static void bind_reply_cb(void *ctx, message *msg, int code) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
if (msg->header.content == ContentTypeStateConnected) {
|
||||
CONN_LOG(TRACE, "received msg ct[%s] code[%d]", content_type_id(msg->header.content), code);
|
||||
CONN_LOG(DEBUG, "bound successfully on router[%s]", zch_get_name(b->ch));
|
||||
|
||||
@@ -19,7 +19,6 @@
|
||||
|
||||
extern e2ee_t *new_libsodium_e2ee(void);
|
||||
extern e2ee_t *new_none_e2ee(void);
|
||||
extern e2ee_t *new_aes_gcm_e2ee(void);
|
||||
extern e2ee_t *new_tls_e2ee(bool server, tls_context *tls);
|
||||
|
||||
e2ee_t* create_e2ee(ziti_crypto_method impl, bool server, tls_context *tls) {
|
||||
@@ -28,8 +27,6 @@ e2ee_t* create_e2ee(ziti_crypto_method impl, bool server, tls_context *tls) {
|
||||
return new_none_e2ee();
|
||||
case ziti_crypto_libsodium:
|
||||
return new_libsodium_e2ee();
|
||||
case ziti_crypto_aes_gcm:
|
||||
return new_aes_gcm_e2ee();
|
||||
case ziti_crypto_tls:
|
||||
return new_tls_e2ee(server, tls);
|
||||
default:
|
||||
@@ -43,8 +40,6 @@ const char *e2ee_method_id(ziti_crypto_method mode) {
|
||||
return "none";
|
||||
case ziti_crypto_libsodium:
|
||||
return "libsodium";
|
||||
case ziti_crypto_aes_gcm:
|
||||
return "aes-gcm";
|
||||
case ziti_crypto_tls:
|
||||
return "tls";
|
||||
default:
|
||||
@@ -58,7 +53,6 @@ ziti_crypto_method e2ee_method_from_id(const char *id) {
|
||||
|
||||
if (strcmp(id, "none") == 0) return ziti_crypto_none;
|
||||
if (strcmp(id, "libsodium") == 0) return ziti_crypto_libsodium;
|
||||
if (strcmp(id, "aes-gcm") == 0) return ziti_crypto_aes_gcm;
|
||||
if (strcmp(id, "tls") == 0) return ziti_crypto_tls;
|
||||
return ziti_crypto_invalid;
|
||||
}
|
||||
|
||||
@@ -1,461 +0,0 @@
|
||||
// Copyright (c) 2026. NetFoundry Inc
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
|
||||
#include <string.h>
|
||||
|
||||
#include <CoreFoundation/CoreFoundation.h>
|
||||
#include <Security/Security.h>
|
||||
#include <CommonCrypto/CommonCrypto.h>
|
||||
|
||||
#include "crypto.h"
|
||||
#include "ziti/ziti_log.h"
|
||||
|
||||
// AES-256-GCM comes from CryptoKit via the @_cdecl wrappers in e2ee_aes_gcm_cryptokit.swift.
|
||||
// Apple exposes no raw AES-GCM to C -- `GCM` appears nowhere in the public CommonCrypto headers
|
||||
// of any Apple SDK, and Security.framework offers only whole-scheme ECIES, which picks its own
|
||||
// key and nonce -- so the Swift hop is what keeps this backend free of undocumented SPI.
|
||||
#ifdef __cplusplus
|
||||
// the unit tests #include this file inside a namespace to find its static functions
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
extern int ziti_cryptokit_aes_gcm_seal(const uint8_t *key, size_t key_len,
|
||||
const uint8_t *nonce, size_t nonce_len,
|
||||
const uint8_t *plaintext, size_t pt_len,
|
||||
uint8_t *ciphertext,
|
||||
uint8_t *tag, size_t tag_len);
|
||||
|
||||
extern int ziti_cryptokit_aes_gcm_open(const uint8_t *key, size_t key_len,
|
||||
const uint8_t *nonce, size_t nonce_len,
|
||||
const uint8_t *ciphertext, size_t ct_len,
|
||||
const uint8_t *tag, size_t tag_len,
|
||||
uint8_t *plaintext);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#define AES_GCM_TAG_LEN 16
|
||||
#define AES_GCM_NONCE_LEN 12
|
||||
#define AES_GCM_NONCE_PREFIX_LEN 4
|
||||
|
||||
#define AES_GCM_KEY_LEN 32
|
||||
#define P256_PUB_KEY_LEN 65
|
||||
|
||||
#if AES_GCM_NONCE_LEN > E2EE_MAX_HEADER_LEN
|
||||
#error "AES_GCM_NONCE_LEN is too large"
|
||||
#endif
|
||||
|
||||
#if AES_GCM_TAG_LEN > E2EE_MAX_MSG_OVERHEAD
|
||||
#error "AES_GCM_TAG_LEN is too large"
|
||||
#endif
|
||||
|
||||
struct aes_gcm_e2ee {
|
||||
e2ee_t e2ee;
|
||||
// released and cleared by init(): key material must not outlive the key exchange
|
||||
SecKeyRef privkey;
|
||||
uint8_t pub_key[P256_PUB_KEY_LEN];
|
||||
size_t pub_key_len;
|
||||
|
||||
uint8_t rx_key[AES_GCM_KEY_LEN];
|
||||
uint8_t tx_key[AES_GCM_KEY_LEN];
|
||||
uint8_t rx_iv_prefix[AES_GCM_NONCE_PREFIX_LEN];
|
||||
uint8_t tx_iv_prefix[AES_GCM_NONCE_PREFIX_LEN];
|
||||
uint64_t tx_counter;
|
||||
uint64_t rx_counter;
|
||||
bool header_sent;
|
||||
};
|
||||
|
||||
static void log_cf_error(const char *msg, CFErrorRef err) {
|
||||
if (err == NULL) {
|
||||
ZITI_LOG(ERROR, "%s", msg);
|
||||
return;
|
||||
}
|
||||
|
||||
char buf[256] = "unknown error";
|
||||
CFStringRef desc = CFErrorCopyDescription(err);
|
||||
if (desc != NULL) {
|
||||
CFStringGetCString(desc, buf, sizeof(buf), kCFStringEncodingUTF8);
|
||||
CFRelease(desc);
|
||||
}
|
||||
ZITI_LOG(ERROR, "%s: %s", msg, buf);
|
||||
}
|
||||
|
||||
static void build_nonce(uint8_t out[AES_GCM_NONCE_LEN], const uint8_t *initial, uint64_t counter) {
|
||||
memcpy(out, initial, AES_GCM_NONCE_PREFIX_LEN);
|
||||
int shift = 0;
|
||||
for (int i = AES_GCM_NONCE_LEN; i > AES_GCM_NONCE_PREFIX_LEN; i--) {
|
||||
out[i - 1] = (counter >> shift) & 0xff;
|
||||
shift += 8;
|
||||
}
|
||||
}
|
||||
|
||||
// RFC 5869 HKDF-SHA256 with an empty salt, matching EVP_PKEY_HKDF with no salt set.
|
||||
// An absent salt is defined as HashLen zero bytes; HMAC zero-pads its key to the block size,
|
||||
// so that is identical to the zero-length key the extract step would otherwise use.
|
||||
static int hkdf_sha256(const uint8_t *ikm, size_t ikm_len,
|
||||
const uint8_t *info, size_t info_len,
|
||||
uint8_t *out, size_t out_len) {
|
||||
const uint8_t salt[CC_SHA256_DIGEST_LENGTH] = {0};
|
||||
uint8_t prk[CC_SHA256_DIGEST_LENGTH];
|
||||
uint8_t t[CC_SHA256_DIGEST_LENGTH];
|
||||
size_t t_len = 0;
|
||||
size_t done = 0;
|
||||
|
||||
if (out_len > 255 * CC_SHA256_DIGEST_LENGTH) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
// extract
|
||||
CCHmac(kCCHmacAlgSHA256, salt, sizeof(salt), ikm, ikm_len, prk);
|
||||
|
||||
// expand: T(n) = HMAC(PRK, T(n-1) || info || n)
|
||||
for (uint8_t counter = 1; done < out_len; counter++) {
|
||||
CCHmacContext ctx;
|
||||
CCHmacInit(&ctx, kCCHmacAlgSHA256, prk, sizeof(prk));
|
||||
CCHmacUpdate(&ctx, t, t_len);
|
||||
CCHmacUpdate(&ctx, info, info_len);
|
||||
CCHmacUpdate(&ctx, &counter, sizeof(counter));
|
||||
CCHmacFinal(&ctx, t);
|
||||
t_len = sizeof(t);
|
||||
|
||||
size_t chunk = out_len - done < t_len ? out_len - done : t_len;
|
||||
memcpy(out + done, t, chunk);
|
||||
done += chunk;
|
||||
}
|
||||
|
||||
sodium_memzero(prk, sizeof(prk));
|
||||
sodium_memzero(t, sizeof(t));
|
||||
return 0;
|
||||
}
|
||||
|
||||
static SecKeyRef import_peer_key(const uint8_t *peer_key, size_t peer_key_len) {
|
||||
SecKeyRef peer = NULL;
|
||||
CFErrorRef err = NULL;
|
||||
const int bits = 256;
|
||||
|
||||
CFNumberRef size = CFNumberCreate(NULL, kCFNumberIntType, &bits);
|
||||
const void *keys[] = {kSecAttrKeyType, kSecAttrKeyClass, kSecAttrKeySizeInBits};
|
||||
const void *vals[] = {kSecAttrKeyTypeECSECPrimeRandom, kSecAttrKeyClassPublic, size};
|
||||
CFDictionaryRef attrs = CFDictionaryCreate(NULL, keys, vals, 3,
|
||||
&kCFTypeDictionaryKeyCallBacks,
|
||||
&kCFTypeDictionaryValueCallBacks);
|
||||
CFDataRef data = CFDataCreate(NULL, peer_key, (CFIndex) peer_key_len);
|
||||
|
||||
peer = SecKeyCreateWithData(data, attrs, &err);
|
||||
if (peer == NULL) {
|
||||
log_cf_error("failed to import peer P-256 public key", err);
|
||||
if (err) CFRelease(err);
|
||||
}
|
||||
|
||||
CFRelease(data);
|
||||
CFRelease(attrs);
|
||||
CFRelease(size);
|
||||
return peer;
|
||||
}
|
||||
|
||||
static int derive_session_keys(struct aes_gcm_e2ee *e, const uint8_t *peer_key, size_t peer_key_len, bool server) {
|
||||
uint8_t shared_secret[AES_GCM_KEY_LEN] = {0};
|
||||
// HKDF output per direction: AES-256 key (32 bytes) || GCM IV fixed_field (4 bytes)
|
||||
uint8_t derived[sizeof(e->rx_key) + sizeof(e->rx_iv_prefix)] = {0};
|
||||
// role_byte + my_pub + peer_pub
|
||||
uint8_t info[1 + sizeof(e->pub_key) * 2];
|
||||
int ret = -1;
|
||||
|
||||
SecKeyRef peer = import_peer_key(peer_key, peer_key_len);
|
||||
if (peer == NULL) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
CFErrorRef err = NULL;
|
||||
CFDictionaryRef params = CFDictionaryCreate(NULL, NULL, NULL, 0,
|
||||
&kCFTypeDictionaryKeyCallBacks,
|
||||
&kCFTypeDictionaryValueCallBacks);
|
||||
CFDataRef ss = SecKeyCopyKeyExchangeResult(e->privkey, kSecKeyAlgorithmECDHKeyExchangeStandard,
|
||||
peer, params, &err);
|
||||
CFRelease(params);
|
||||
CFRelease(peer);
|
||||
|
||||
if (ss == NULL) {
|
||||
log_cf_error("ECDH key exchange failed", err);
|
||||
if (err) CFRelease(err);
|
||||
return -1;
|
||||
}
|
||||
if (CFDataGetLength(ss) != (CFIndex) sizeof(shared_secret)) {
|
||||
ZITI_LOG(ERROR, "unexpected ECDH shared secret length: %ld", (long) CFDataGetLength(ss));
|
||||
CFRelease(ss);
|
||||
return -1;
|
||||
}
|
||||
memcpy(shared_secret, CFDataGetBytePtr(ss), sizeof(shared_secret));
|
||||
CFRelease(ss);
|
||||
|
||||
// Include role + both public keys in info so server and client derive complementary material.
|
||||
info[0] = server ? 1 : 0;
|
||||
memcpy(info + 1, e->pub_key, e->pub_key_len);
|
||||
memcpy(info + 1 + e->pub_key_len, peer_key, peer_key_len);
|
||||
if (hkdf_sha256(shared_secret, sizeof(shared_secret), info, sizeof(info),
|
||||
derived, sizeof(derived)) != 0) {
|
||||
goto cleanup;
|
||||
}
|
||||
memcpy(e->rx_key, derived, sizeof(e->rx_key));
|
||||
memcpy(e->rx_iv_prefix, derived + sizeof(e->rx_key), sizeof(e->rx_iv_prefix));
|
||||
|
||||
// Derive tx material with different info (flip role byte, swap pub-key order)
|
||||
info[0] = server ? 0 : 1;
|
||||
memcpy(info + 1, peer_key, peer_key_len);
|
||||
memcpy(info + 1 + peer_key_len, e->pub_key, e->pub_key_len);
|
||||
if (hkdf_sha256(shared_secret, sizeof(shared_secret), info, sizeof(info),
|
||||
derived, sizeof(derived)) != 0) {
|
||||
goto cleanup;
|
||||
}
|
||||
memcpy(e->tx_key, derived, sizeof(e->tx_key));
|
||||
memcpy(e->tx_iv_prefix, derived + sizeof(e->tx_key), sizeof(e->tx_iv_prefix));
|
||||
|
||||
ret = 0;
|
||||
|
||||
cleanup:
|
||||
if (ret != 0) {
|
||||
ZITI_LOG(ERROR, "Failed to derive session keys");
|
||||
}
|
||||
sodium_memzero(shared_secret, sizeof(shared_secret));
|
||||
sodium_memzero(derived, sizeof(derived));
|
||||
return ret;
|
||||
}
|
||||
|
||||
static e2ee_pub_t aes_gcm_pub(struct e2ee *e2ee) {
|
||||
struct aes_gcm_e2ee *e = (struct aes_gcm_e2ee *)e2ee;
|
||||
e2ee_pub_t pub = {};
|
||||
pub.key = e->pub_key;
|
||||
pub.key_len = e->pub_key_len;
|
||||
return pub;
|
||||
}
|
||||
|
||||
static int aes_gcm_init(struct e2ee *e2ee, const uint8_t *peer_key, size_t peer_key_len, bool server) {
|
||||
struct aes_gcm_e2ee *e = (struct aes_gcm_e2ee *)e2ee;
|
||||
|
||||
if (peer_key_len != e->pub_key_len) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Already initialized
|
||||
if (!sodium_is_zero(e->rx_key, sizeof(e->rx_key)) || !sodium_is_zero(e->tx_key, sizeof(e->tx_key))) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
int ret = derive_session_keys(e, peer_key, peer_key_len, server);
|
||||
|
||||
// Release secret key material regardless of outcome
|
||||
CFRelease(e->privkey);
|
||||
e->privkey = NULL;
|
||||
|
||||
if (ret != 0) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
e->tx_counter = 1;
|
||||
e->rx_counter = 1;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
static ssize_t aes_gcm_get_header(struct e2ee *e2ee, uint8_t header[E2EE_MAX_HEADER_LEN]) {
|
||||
struct aes_gcm_e2ee *e = (struct aes_gcm_e2ee *)e2ee;
|
||||
if (header == NULL) {
|
||||
return -1;
|
||||
}
|
||||
if (e->header_sent) {
|
||||
return -1;
|
||||
}
|
||||
// IV prefix and counter origin are agreed during init via HKDF; nothing to send.
|
||||
e->header_sent = true;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static ssize_t aes_gcm_encrypt(e2ee_t *e2ee, const uint8_t *plaintext, size_t plaintext_len, uint8_t *ciphertext, size_t ciphertext_len) {
|
||||
struct aes_gcm_e2ee *e = (struct aes_gcm_e2ee *)e2ee;
|
||||
size_t required = plaintext_len + AES_GCM_TAG_LEN;
|
||||
if (ciphertext_len < required) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (e->tx_counter == UINT64_MAX) {
|
||||
ZITI_LOG(ERROR, "AES-GCM encryption counter overflow");
|
||||
return -1;
|
||||
}
|
||||
|
||||
uint8_t iv[AES_GCM_NONCE_LEN];
|
||||
build_nonce(iv, e->tx_iv_prefix, e->tx_counter);
|
||||
|
||||
if (ziti_cryptokit_aes_gcm_seal(e->tx_key, sizeof(e->tx_key),
|
||||
iv, sizeof(iv),
|
||||
plaintext, plaintext_len,
|
||||
ciphertext, ciphertext + plaintext_len,
|
||||
AES_GCM_TAG_LEN) != 0) {
|
||||
ZITI_LOG(ERROR, "aes-gcm encryption failed");
|
||||
return -1;
|
||||
}
|
||||
|
||||
e->tx_counter++;
|
||||
return (ssize_t)required;
|
||||
}
|
||||
|
||||
static ssize_t aes_gcm_decrypt(e2ee_t *e2ee, const uint8_t *ciphertext, size_t ciphertext_len, uint8_t *plaintext, size_t plaintext_len) {
|
||||
struct aes_gcm_e2ee *e = (struct aes_gcm_e2ee *)e2ee;
|
||||
|
||||
if (ciphertext_len <= AES_GCM_TAG_LEN) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
size_t ct_data_len = ciphertext_len - AES_GCM_TAG_LEN;
|
||||
if (plaintext_len < ct_data_len) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (e->rx_counter == UINT64_MAX) {
|
||||
ZITI_LOG(ERROR, "AES-GCM decryption counter overflow");
|
||||
return -1;
|
||||
}
|
||||
|
||||
uint8_t iv[AES_GCM_NONCE_LEN];
|
||||
build_nonce(iv, e->rx_iv_prefix, e->rx_counter);
|
||||
|
||||
if (ziti_cryptokit_aes_gcm_open(e->rx_key, sizeof(e->rx_key),
|
||||
iv, sizeof(iv),
|
||||
ciphertext, ct_data_len,
|
||||
ciphertext + ct_data_len, AES_GCM_TAG_LEN,
|
||||
plaintext) != 0) {
|
||||
ZITI_LOG(WARN, "aes-gcm decryption failed");
|
||||
return -1;
|
||||
}
|
||||
|
||||
e->rx_counter++;
|
||||
return (ssize_t)ct_data_len;
|
||||
}
|
||||
|
||||
static struct e2ee *aes_gcm_clone(struct e2ee *e2ee) {
|
||||
struct aes_gcm_e2ee *e = (struct aes_gcm_e2ee *)e2ee;
|
||||
|
||||
if (e->privkey == NULL) {
|
||||
ZITI_LOG(ERROR, "cannot clone aes-gcm e2ee after init was called");
|
||||
abort();
|
||||
}
|
||||
|
||||
struct aes_gcm_e2ee *clone = (struct aes_gcm_e2ee*)calloc(1, sizeof(struct aes_gcm_e2ee));
|
||||
if (clone == NULL) {
|
||||
ZITI_LOG(ERROR, "failed to allocate aes-gcm e2ee: out of memory");
|
||||
abort();
|
||||
}
|
||||
|
||||
clone->e2ee = e->e2ee;
|
||||
|
||||
// SecKeyRef is immutable and only read until init(), so each clone can share it
|
||||
// behind its own reference: releasing one clone's handle cannot disturb a sibling.
|
||||
clone->privkey = (SecKeyRef) CFRetain(e->privkey);
|
||||
|
||||
memcpy(clone->pub_key, e->pub_key, e->pub_key_len);
|
||||
clone->pub_key_len = e->pub_key_len;
|
||||
|
||||
return &clone->e2ee;
|
||||
}
|
||||
|
||||
static void aes_gcm_free(e2ee_t *e2ee) {
|
||||
struct aes_gcm_e2ee *e = (struct aes_gcm_e2ee *)e2ee;
|
||||
if (e->privkey) {
|
||||
CFRelease(e->privkey);
|
||||
}
|
||||
sodium_memzero(e, sizeof(struct aes_gcm_e2ee));
|
||||
free(e);
|
||||
}
|
||||
|
||||
static e2ee_t aes_gcm_e2ee_impl = {
|
||||
.method = ziti_crypto_aes_gcm,
|
||||
.clone = aes_gcm_clone,
|
||||
.pub = aes_gcm_pub,
|
||||
.init = aes_gcm_init,
|
||||
.get_header = aes_gcm_get_header,
|
||||
.encrypt = aes_gcm_encrypt,
|
||||
.decrypt = aes_gcm_decrypt,
|
||||
.free = aes_gcm_free,
|
||||
};
|
||||
|
||||
// Generate a memory-only P-256 keypair. Never persisted: kSecAttrIsPermanent is
|
||||
// explicitly false so nothing reaches the user's keychain.
|
||||
static SecKeyRef generate_keypair(void) {
|
||||
const int bits = 256;
|
||||
CFNumberRef size = CFNumberCreate(NULL, kCFNumberIntType, &bits);
|
||||
const void *keys[] = {kSecAttrKeyType, kSecAttrKeySizeInBits, kSecAttrIsPermanent};
|
||||
const void *vals[] = {kSecAttrKeyTypeECSECPrimeRandom, size, kCFBooleanFalse};
|
||||
CFDictionaryRef attrs = CFDictionaryCreate(NULL, keys, vals, 3,
|
||||
&kCFTypeDictionaryKeyCallBacks,
|
||||
&kCFTypeDictionaryValueCallBacks);
|
||||
|
||||
CFErrorRef err = NULL;
|
||||
SecKeyRef key = SecKeyCreateRandomKey(attrs, &err);
|
||||
if (key == NULL) {
|
||||
log_cf_error("failed to generate P-256 keypair", err);
|
||||
if (err) CFRelease(err);
|
||||
}
|
||||
|
||||
CFRelease(attrs);
|
||||
CFRelease(size);
|
||||
return key;
|
||||
}
|
||||
|
||||
struct aes_gcm_e2ee *new_aes_gcm_e2ee(void) {
|
||||
struct aes_gcm_e2ee *e = (struct aes_gcm_e2ee*)calloc(1, sizeof(struct aes_gcm_e2ee));
|
||||
if (e == NULL) {
|
||||
ZITI_LOG(ERROR, "failed to allocate aes-gcm e2ee: out of memory");
|
||||
abort();
|
||||
}
|
||||
|
||||
e->e2ee = aes_gcm_e2ee_impl;
|
||||
|
||||
e->privkey = generate_keypair();
|
||||
if (e->privkey == NULL) {
|
||||
aes_gcm_free((e2ee_t *)e);
|
||||
abort();
|
||||
}
|
||||
|
||||
// export the public part as an uncompressed X9.63 point (0x04 || X || Y)
|
||||
SecKeyRef pub = SecKeyCopyPublicKey(e->privkey);
|
||||
if (pub == NULL) {
|
||||
ZITI_LOG(ERROR, "failed to get public key from P-256 keypair");
|
||||
aes_gcm_free((e2ee_t *)e);
|
||||
abort();
|
||||
}
|
||||
|
||||
CFErrorRef err = NULL;
|
||||
CFDataRef data = SecKeyCopyExternalRepresentation(pub, &err);
|
||||
CFRelease(pub);
|
||||
if (data == NULL) {
|
||||
log_cf_error("failed to export P-256 public key", err);
|
||||
if (err) CFRelease(err);
|
||||
aes_gcm_free((e2ee_t *)e);
|
||||
abort();
|
||||
}
|
||||
if (CFDataGetLength(data) != (CFIndex) sizeof(e->pub_key)) {
|
||||
ZITI_LOG(ERROR, "unexpected P-256 public key length: %ld", (long) CFDataGetLength(data));
|
||||
CFRelease(data);
|
||||
aes_gcm_free((e2ee_t *)e);
|
||||
abort();
|
||||
}
|
||||
memcpy(e->pub_key, CFDataGetBytePtr(data), sizeof(e->pub_key));
|
||||
e->pub_key_len = sizeof(e->pub_key);
|
||||
CFRelease(data);
|
||||
|
||||
return e;
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
// Copyright (c) 2026. NetFoundry Inc
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
// AES-256-GCM for the Apple e2ee backend.
|
||||
//
|
||||
// CryptoKit is Swift-only, so these two thin wrappers are the C entry points that
|
||||
// e2ee_aes_gcm_apple.c calls. They exist so the backend does not have to declare
|
||||
// Apple's undocumented CCCryptorGCMOneshot* SPI: everything used here is public API.
|
||||
//
|
||||
// @_cdecl is an underscored attribute, but it is the only way to give a Swift function
|
||||
// C linkage in the shipping toolchain (the evolution-approved @cdecl is not yet in
|
||||
// Apple's Swift 6.3). Both functions are leaf, allocation-light and re-entrant: they hold
|
||||
// no state between calls, so they are safe to call from any thread.
|
||||
|
||||
import Foundation
|
||||
import CryptoKit
|
||||
|
||||
/// AES-256-GCM seal. `ciphertext` receives `ptLen` bytes, `tag` receives 16.
|
||||
/// Returns 0 on success, -1 on failure.
|
||||
@_cdecl("ziti_cryptokit_aes_gcm_seal")
|
||||
func zitiCryptoKitAesGcmSeal(_ key: UnsafePointer<UInt8>, _ keyLen: Int,
|
||||
_ nonce: UnsafePointer<UInt8>, _ nonceLen: Int,
|
||||
_ plaintext: UnsafePointer<UInt8>?, _ ptLen: Int,
|
||||
_ ciphertext: UnsafeMutablePointer<UInt8>,
|
||||
_ tag: UnsafeMutablePointer<UInt8>,
|
||||
_ tagLen: Int) -> Int32 {
|
||||
let key = SymmetricKey(data: UnsafeRawBufferPointer(start: key, count: keyLen))
|
||||
guard let nonce = try? AES.GCM.Nonce(data: UnsafeRawBufferPointer(start: nonce, count: nonceLen)) else {
|
||||
return -1
|
||||
}
|
||||
|
||||
// an empty payload is legal and arrives as (NULL, 0); CryptoKit traps on a null base
|
||||
// pointer even at zero length, so it gets an empty Data instead of a raw buffer
|
||||
let sealed: AES.GCM.SealedBox?
|
||||
if let plaintext, ptLen > 0 {
|
||||
sealed = try? AES.GCM.seal(UnsafeRawBufferPointer(start: plaintext, count: ptLen),
|
||||
using: key, nonce: nonce)
|
||||
} else {
|
||||
sealed = try? AES.GCM.seal(Data(), using: key, nonce: nonce)
|
||||
}
|
||||
guard let sealed, sealed.tag.count == tagLen else {
|
||||
return -1
|
||||
}
|
||||
|
||||
if ptLen > 0 {
|
||||
sealed.ciphertext.copyBytes(to: UnsafeMutableRawBufferPointer(start: ciphertext, count: ptLen))
|
||||
}
|
||||
sealed.tag.copyBytes(to: UnsafeMutableRawBufferPointer(start: tag, count: tagLen))
|
||||
return 0
|
||||
}
|
||||
|
||||
/// AES-256-GCM open. `plaintext` receives `ctLen` bytes on success.
|
||||
/// Returns 0 on success, -1 if the tag does not verify or any input is malformed.
|
||||
@_cdecl("ziti_cryptokit_aes_gcm_open")
|
||||
func zitiCryptoKitAesGcmOpen(_ key: UnsafePointer<UInt8>, _ keyLen: Int,
|
||||
_ nonce: UnsafePointer<UInt8>, _ nonceLen: Int,
|
||||
_ ciphertext: UnsafePointer<UInt8>?, _ ctLen: Int,
|
||||
_ tag: UnsafePointer<UInt8>, _ tagLen: Int,
|
||||
_ plaintext: UnsafeMutablePointer<UInt8>) -> Int32 {
|
||||
let key = SymmetricKey(data: UnsafeRawBufferPointer(start: key, count: keyLen))
|
||||
guard let nonce = try? AES.GCM.Nonce(data: UnsafeRawBufferPointer(start: nonce, count: nonceLen)) else {
|
||||
return -1
|
||||
}
|
||||
|
||||
// see the note in seal: (NULL, 0) must not reach CryptoKit as a null base pointer
|
||||
let tagBuffer = UnsafeRawBufferPointer(start: tag, count: tagLen)
|
||||
let sealed: AES.GCM.SealedBox?
|
||||
if let ciphertext, ctLen > 0 {
|
||||
sealed = try? AES.GCM.SealedBox(nonce: nonce,
|
||||
ciphertext: UnsafeRawBufferPointer(start: ciphertext, count: ctLen),
|
||||
tag: tagBuffer)
|
||||
} else {
|
||||
sealed = try? AES.GCM.SealedBox(nonce: nonce, ciphertext: Data(), tag: tagBuffer)
|
||||
}
|
||||
|
||||
// open throws on tag mismatch, which is the authentication check
|
||||
guard let sealed, let opened = try? AES.GCM.open(sealed, using: key) else {
|
||||
return -1
|
||||
}
|
||||
|
||||
if ctLen > 0 {
|
||||
opened.copyBytes(to: UnsafeMutableRawBufferPointer(start: plaintext, count: ctLen))
|
||||
}
|
||||
return 0
|
||||
}
|
||||
@@ -1,375 +0,0 @@
|
||||
// Copyright (c) 2026. NetFoundry Inc
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
|
||||
#include <string.h>
|
||||
|
||||
#include <openssl/core_names.h>
|
||||
#include <openssl/crypto.h>
|
||||
#include <openssl/ec.h>
|
||||
#include <openssl/err.h>
|
||||
#include <openssl/evp.h>
|
||||
#include <openssl/kdf.h>
|
||||
|
||||
#include "crypto.h"
|
||||
#include "ziti/ziti_log.h"
|
||||
|
||||
|
||||
#if !defined(EVP_MAX_AEAD_TAG_LENGTH)
|
||||
#define EVP_MAX_AEAD_TAG_LENGTH 16
|
||||
#endif
|
||||
|
||||
#define AES_GCM_TAG_LEN EVP_MAX_AEAD_TAG_LENGTH
|
||||
#define AES_GCM_NONCE_LEN 12
|
||||
#define AES_GCM_NONCE_PREFIX_LEN 4
|
||||
|
||||
#if AES_GCM_NONCE_LEN > EVP_MAX_IV_LENGTH
|
||||
#error "AES_GCM_NONCE_LEN is too large"
|
||||
#endif
|
||||
|
||||
#if AES_GCM_NONCE_LEN > E2EE_MAX_HEADER_LEN
|
||||
#error "AES_GCM_NONCE_LEN is too large"
|
||||
#endif
|
||||
|
||||
struct aes_gcm_e2ee {
|
||||
e2ee_t e2ee;
|
||||
EVP_PKEY *pkey;
|
||||
uint8_t pub_key[65];
|
||||
size_t pub_key_len;
|
||||
|
||||
EVP_CIPHER_CTX *tx;
|
||||
EVP_CIPHER_CTX *rx;
|
||||
|
||||
uint8_t rx_key[32];
|
||||
uint8_t tx_key[32];
|
||||
uint8_t rx_iv_prefix[AES_GCM_NONCE_PREFIX_LEN];
|
||||
uint8_t tx_iv_prefix[AES_GCM_NONCE_PREFIX_LEN];
|
||||
uint64_t tx_counter;
|
||||
uint64_t rx_counter;
|
||||
bool header_sent;
|
||||
};
|
||||
|
||||
static void build_nonce(uint8_t out[AES_GCM_NONCE_LEN], const uint8_t *initial, uint64_t counter) {
|
||||
memcpy(out, initial, AES_GCM_NONCE_PREFIX_LEN);
|
||||
int shift = 0;
|
||||
for (int i = AES_GCM_NONCE_LEN; i > AES_GCM_NONCE_PREFIX_LEN; i--) {
|
||||
out[i - 1] = (counter >> shift) & 0xff;
|
||||
shift += 8;
|
||||
}
|
||||
}
|
||||
|
||||
static int derive_session_keys(struct aes_gcm_e2ee *e, const uint8_t *peer_key, size_t peer_key_len, bool server) {
|
||||
EVP_PKEY_CTX *derive_ctx = NULL;
|
||||
EVP_PKEY_CTX *hkdf_ctx = NULL;
|
||||
uint8_t shared_secret[32] = {0};
|
||||
size_t shared_secret_len = sizeof(shared_secret);
|
||||
// HKDF output per direction: AES-256 key (32 bytes) || GCM IV fixed_field (4 bytes)
|
||||
uint8_t derived[sizeof(e->rx_key) + sizeof(e->rx_iv_prefix)] = {0};
|
||||
size_t derived_len = sizeof(derived);
|
||||
int ret = -1;
|
||||
|
||||
EVP_PKEY *peer_pub = EVP_PKEY_new();
|
||||
if (EVP_PKEY_copy_parameters(peer_pub, e->pkey) != 1) goto cleanup;
|
||||
if (EVP_PKEY_set1_encoded_public_key(peer_pub, peer_key, peer_key_len) != 1) goto cleanup;
|
||||
|
||||
// ECDH derive
|
||||
derive_ctx = EVP_PKEY_CTX_new(e->pkey, NULL);
|
||||
if (derive_ctx == NULL) goto cleanup;
|
||||
|
||||
if (EVP_PKEY_derive_init(derive_ctx) != 1) goto cleanup;
|
||||
if (EVP_PKEY_derive_set_peer(derive_ctx, peer_pub) != 1) goto cleanup;
|
||||
if (EVP_PKEY_derive(derive_ctx, shared_secret, &shared_secret_len) != 1) goto cleanup;
|
||||
|
||||
// HKDF-SHA256 to derive (rx_key || rx_iv_prefix) and (tx_key || tx_iv_prefix).
|
||||
// Include role + both public keys in info so server and client derive complementary material.
|
||||
uint8_t info[1 + sizeof(e->pub_key) * 2]; // role_byte + my_pub + peer_pub
|
||||
info[0] = server ? 1 : 0;
|
||||
memcpy(info + 1, e->pub_key, e->pub_key_len);
|
||||
memcpy(info + 1 + e->pub_key_len, peer_key, peer_key_len);
|
||||
|
||||
hkdf_ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_HKDF, NULL);
|
||||
if (hkdf_ctx == NULL) goto cleanup;
|
||||
if (EVP_PKEY_derive_init(hkdf_ctx) <= 0) goto cleanup;
|
||||
if (EVP_PKEY_CTX_set_hkdf_md(hkdf_ctx, EVP_sha256()) <= 0) goto cleanup;
|
||||
if (EVP_PKEY_CTX_set1_hkdf_key(hkdf_ctx, shared_secret, (int)shared_secret_len) <= 0) goto cleanup;
|
||||
if (EVP_PKEY_CTX_add1_hkdf_info(hkdf_ctx, info, (int)sizeof(info)) <= 0) goto cleanup;
|
||||
if (EVP_PKEY_derive(hkdf_ctx, derived, &derived_len) <= 0) goto cleanup;
|
||||
memcpy(e->rx_key, derived, sizeof(e->rx_key));
|
||||
memcpy(e->rx_iv_prefix, derived + sizeof(e->rx_key), sizeof(e->rx_iv_prefix));
|
||||
|
||||
// Derive tx material with different info (flip role byte, swap pub-key order)
|
||||
info[0] = server ? 0 : 1;
|
||||
memcpy(info + 1, peer_key, peer_key_len);
|
||||
memcpy(info + 1 + peer_key_len, e->pub_key, e->pub_key_len);
|
||||
EVP_PKEY_CTX_free(hkdf_ctx);
|
||||
hkdf_ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_HKDF, NULL);
|
||||
if (hkdf_ctx == NULL) goto cleanup;
|
||||
if (EVP_PKEY_derive_init(hkdf_ctx) <= 0) goto cleanup;
|
||||
if (EVP_PKEY_CTX_set_hkdf_md(hkdf_ctx, EVP_sha256()) <= 0) goto cleanup;
|
||||
if (EVP_PKEY_CTX_set1_hkdf_key(hkdf_ctx, shared_secret, (int)shared_secret_len) <= 0) goto cleanup;
|
||||
if (EVP_PKEY_CTX_add1_hkdf_info(hkdf_ctx, info, (int)sizeof(info)) <= 0) goto cleanup;
|
||||
derived_len = sizeof(derived);
|
||||
if (EVP_PKEY_derive(hkdf_ctx, derived, &derived_len) <= 0) goto cleanup;
|
||||
memcpy(e->tx_key, derived, sizeof(e->tx_key));
|
||||
memcpy(e->tx_iv_prefix, derived + sizeof(e->tx_key), sizeof(e->tx_iv_prefix));
|
||||
|
||||
ret = 0;
|
||||
|
||||
cleanup:
|
||||
if (ret != 0) {
|
||||
ZITI_LOG(ERROR, "Failed to derive session keys: %s", ERR_error_string(ERR_get_error(), NULL));
|
||||
}
|
||||
OPENSSL_cleanse(shared_secret, sizeof(shared_secret));
|
||||
OPENSSL_cleanse(derived, sizeof(derived));
|
||||
if (peer_pub) EVP_PKEY_free(peer_pub);
|
||||
if (hkdf_ctx) EVP_PKEY_CTX_free(hkdf_ctx);
|
||||
if (derive_ctx) EVP_PKEY_CTX_free(derive_ctx);
|
||||
return ret;
|
||||
}
|
||||
|
||||
static e2ee_pub_t aes_gcm_pub(struct e2ee *e2ee) {
|
||||
struct aes_gcm_e2ee *e = (struct aes_gcm_e2ee *)e2ee;
|
||||
e2ee_pub_t pub = {};
|
||||
pub.key = e->pub_key;
|
||||
pub.key_len = e->pub_key_len;
|
||||
return pub;
|
||||
}
|
||||
|
||||
static int aes_gcm_init(struct e2ee *e2ee, const uint8_t *peer_key, size_t peer_key_len, bool server) {
|
||||
struct aes_gcm_e2ee *e = (struct aes_gcm_e2ee *)e2ee;
|
||||
|
||||
if (peer_key_len != e->pub_key_len) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Already initialized
|
||||
if (!sodium_is_zero(e->rx_key, sizeof(e->rx_key)) || !sodium_is_zero(e->tx_key, sizeof(e->tx_key))) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
int ret = derive_session_keys(e, peer_key, peer_key_len, server);
|
||||
|
||||
// Zero out secret key material regardless of outcome
|
||||
EVP_PKEY_free(e->pkey);
|
||||
e->pkey = NULL;
|
||||
|
||||
if (ret != 0) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
e->tx_counter = 1;
|
||||
e->rx_counter = 1;
|
||||
|
||||
e->tx = EVP_CIPHER_CTX_new();
|
||||
e->rx = EVP_CIPHER_CTX_new();
|
||||
if (e->tx == NULL || e->rx == NULL) {
|
||||
ZITI_LOG(ERROR, "Failed to allocate AES-GCM cipher contexts");
|
||||
return -1;
|
||||
}
|
||||
if (EVP_EncryptInit_ex(e->tx, EVP_aes_256_gcm(), NULL, NULL, NULL) != 1 ||
|
||||
EVP_CIPHER_CTX_ctrl(e->tx, EVP_CTRL_GCM_SET_IVLEN, AES_GCM_NONCE_LEN, NULL) != 1 ||
|
||||
EVP_DecryptInit_ex(e->rx, EVP_aes_256_gcm(), NULL, NULL, NULL) != 1 ||
|
||||
EVP_CIPHER_CTX_ctrl(e->rx, EVP_CTRL_GCM_SET_IVLEN, AES_GCM_NONCE_LEN, NULL) != 1) {
|
||||
ZITI_LOG(ERROR, "Failed to initialize AES-GCM cipher contexts: %s", ERR_error_string(ERR_get_error(), NULL));
|
||||
return -1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
static ssize_t aes_gcm_get_header(struct e2ee *e2ee, uint8_t header[E2EE_MAX_HEADER_LEN]) {
|
||||
struct aes_gcm_e2ee *e = (struct aes_gcm_e2ee *)e2ee;
|
||||
if (header == NULL) {
|
||||
return -1;
|
||||
}
|
||||
if (e->header_sent) {
|
||||
return -1;
|
||||
}
|
||||
// IV prefix and counter origin are agreed during init via HKDF; nothing to send.
|
||||
e->header_sent = true;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static ssize_t aes_gcm_encrypt(e2ee_t *e2ee, const uint8_t *plaintext, size_t plaintext_len, uint8_t *ciphertext, size_t ciphertext_len) {
|
||||
struct aes_gcm_e2ee *e = (struct aes_gcm_e2ee *)e2ee;
|
||||
size_t required = plaintext_len + AES_GCM_TAG_LEN;
|
||||
if (ciphertext_len < required) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (e->tx_counter == UINT64_MAX) {
|
||||
ZITI_LOG(ERROR, "AES-GCM encryption counter overflow");
|
||||
return -1;
|
||||
}
|
||||
|
||||
int out_len = 0;
|
||||
int final_len = 0;
|
||||
|
||||
uint8_t iv[AES_GCM_NONCE_LEN];
|
||||
build_nonce(iv, e->tx_iv_prefix, e->tx_counter);
|
||||
if (EVP_EncryptInit_ex(e->tx, NULL, NULL, e->tx_key, iv) != 1) goto err;
|
||||
if (EVP_EncryptUpdate(e->tx, ciphertext, &out_len, plaintext, (int)plaintext_len) != 1) goto err;
|
||||
if (EVP_EncryptFinal_ex(e->tx, ciphertext + out_len, &final_len) != 1) goto err;
|
||||
|
||||
out_len += final_len;
|
||||
|
||||
if (EVP_CIPHER_CTX_ctrl(e->tx, EVP_CTRL_GCM_GET_TAG, AES_GCM_TAG_LEN, ciphertext + out_len) != 1) goto err;
|
||||
out_len += AES_GCM_TAG_LEN;
|
||||
e->tx_counter++;
|
||||
|
||||
return (ssize_t)out_len;
|
||||
|
||||
err:
|
||||
ZITI_LOG(ERROR, "aes-gcm encryption failed: %s", ERR_error_string(ERR_get_error(), NULL));
|
||||
return -1;
|
||||
}
|
||||
|
||||
static ssize_t aes_gcm_decrypt(e2ee_t *e2ee, const uint8_t *ciphertext, size_t ciphertext_len, uint8_t *plaintext, size_t plaintext_len) {
|
||||
struct aes_gcm_e2ee *e = (struct aes_gcm_e2ee *)e2ee;
|
||||
|
||||
if (ciphertext_len <= AES_GCM_TAG_LEN) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
size_t ct_data_len = ciphertext_len - AES_GCM_TAG_LEN;
|
||||
if (plaintext_len < ct_data_len) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (e->rx_counter == UINT64_MAX) {
|
||||
ZITI_LOG(ERROR, "AES-GCM decryption counter overflow");
|
||||
return -1;
|
||||
}
|
||||
|
||||
int out_len = 0;
|
||||
int final_len = 0;
|
||||
|
||||
uint8_t iv[AES_GCM_NONCE_LEN];
|
||||
build_nonce(iv, e->rx_iv_prefix, e->rx_counter);
|
||||
if (EVP_DecryptInit_ex(e->rx, NULL, NULL, e->rx_key, iv) != 1) {
|
||||
goto err;
|
||||
}
|
||||
|
||||
if (EVP_DecryptUpdate(e->rx, plaintext, &out_len, ciphertext, (int)ct_data_len) != 1) goto err;
|
||||
if (EVP_CIPHER_CTX_ctrl(e->rx, EVP_CTRL_GCM_SET_TAG, AES_GCM_TAG_LEN, (uint8_t *)ciphertext + ct_data_len) != 1) goto err;
|
||||
if (EVP_DecryptFinal_ex(e->rx, plaintext + out_len, &final_len) != 1) goto err;
|
||||
|
||||
out_len += final_len;
|
||||
e->rx_counter++;
|
||||
return (ssize_t)out_len;
|
||||
|
||||
err:
|
||||
ZITI_LOG(WARN, "aes-gcm decryption failed: %s", ERR_error_string(ERR_get_error(), NULL));
|
||||
return -1;
|
||||
}
|
||||
|
||||
static struct e2ee *aes_gcm_clone(struct e2ee *e2ee) {
|
||||
struct aes_gcm_e2ee *e = (struct aes_gcm_e2ee *)e2ee;
|
||||
|
||||
if (e->pkey == NULL) {
|
||||
ZITI_LOG(ERROR, "cannot clone aes-gcm e2ee after init was called");
|
||||
abort();
|
||||
}
|
||||
|
||||
struct aes_gcm_e2ee *clone = (struct aes_gcm_e2ee*)calloc(1, sizeof(struct aes_gcm_e2ee));
|
||||
if (clone == NULL) {
|
||||
ZITI_LOG(ERROR, "failed to allocate aes-gcm e2ee: out of memory");
|
||||
abort();
|
||||
}
|
||||
|
||||
clone->e2ee = e->e2ee;
|
||||
|
||||
// Deep copy the keypair
|
||||
clone->pkey = EVP_PKEY_dup(e->pkey);
|
||||
if (clone->pkey == NULL) {
|
||||
ZITI_LOG(ERROR, "failed to duplicate aes-gcm keypair");
|
||||
free(clone);
|
||||
abort();
|
||||
}
|
||||
|
||||
memcpy(clone->pub_key, e->pub_key, e->pub_key_len);
|
||||
clone->pub_key_len = e->pub_key_len;
|
||||
|
||||
return &clone->e2ee;
|
||||
}
|
||||
|
||||
static void aes_gcm_free(e2ee_t *e2ee) {
|
||||
struct aes_gcm_e2ee *e = (struct aes_gcm_e2ee *)e2ee;
|
||||
if (e->pkey) {
|
||||
EVP_PKEY_free(e->pkey);
|
||||
}
|
||||
if (e->tx) {
|
||||
EVP_CIPHER_CTX_free(e->tx);
|
||||
}
|
||||
if (e->rx) {
|
||||
EVP_CIPHER_CTX_free(e->rx);
|
||||
}
|
||||
OPENSSL_cleanse(e, sizeof(struct aes_gcm_e2ee));
|
||||
free(e);
|
||||
}
|
||||
|
||||
static e2ee_t aes_gcm_e2ee_impl = {
|
||||
.method = ziti_crypto_aes_gcm,
|
||||
.clone = aes_gcm_clone,
|
||||
.pub = aes_gcm_pub,
|
||||
.init = aes_gcm_init,
|
||||
.get_header = aes_gcm_get_header,
|
||||
.encrypt = aes_gcm_encrypt,
|
||||
.decrypt = aes_gcm_decrypt,
|
||||
.free = aes_gcm_free,
|
||||
};
|
||||
|
||||
struct aes_gcm_e2ee *new_aes_gcm_e2ee(void) {
|
||||
struct aes_gcm_e2ee *e = (struct aes_gcm_e2ee*)calloc(1, sizeof(struct aes_gcm_e2ee));
|
||||
if (e == NULL) {
|
||||
ZITI_LOG(ERROR, "failed to allocate aes-gcm e2ee: out of memory");
|
||||
abort();
|
||||
}
|
||||
|
||||
e->e2ee = aes_gcm_e2ee_impl;
|
||||
|
||||
// Generate P-256 keypair
|
||||
EVP_PKEY_CTX *gen_ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_EC, NULL);
|
||||
if (gen_ctx == NULL || EVP_PKEY_keygen_init(gen_ctx) <= 0) {
|
||||
ZITI_LOG(ERROR, "failed to init P-256 keygen");
|
||||
EVP_PKEY_CTX_free(gen_ctx);
|
||||
aes_gcm_free((e2ee_t *)e);
|
||||
abort();
|
||||
}
|
||||
if (EVP_PKEY_CTX_set_ec_paramgen_curve_nid(gen_ctx, NID_X9_62_prime256v1) <= 0) {
|
||||
ZITI_LOG(ERROR, "failed to set P-256 curve");
|
||||
EVP_PKEY_CTX_free(gen_ctx);
|
||||
aes_gcm_free((e2ee_t *)e);
|
||||
abort();
|
||||
}
|
||||
if (EVP_PKEY_keygen(gen_ctx, &e->pkey) <= 0) {
|
||||
ZITI_LOG(ERROR, "failed to generate P-256 keypair");
|
||||
EVP_PKEY_CTX_free(gen_ctx);
|
||||
aes_gcm_free((e2ee_t *)e);
|
||||
abort();
|
||||
}
|
||||
EVP_PKEY_CTX_free(gen_ctx);
|
||||
|
||||
if (EVP_PKEY_get_octet_string_param(e->pkey, OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY, e->pub_key,
|
||||
sizeof(e->pub_key), &e->pub_key_len) != 1) {
|
||||
ZITI_LOG(ERROR, "failed to get public key from P-256 keypair");
|
||||
aes_gcm_free((e2ee_t *)e);
|
||||
abort();
|
||||
}
|
||||
|
||||
return e;
|
||||
}
|
||||
|
||||
@@ -1,444 +0,0 @@
|
||||
// Copyright (c) 2026. NetFoundry Inc
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef _WIN32
|
||||
#error "This file is only for Windows builds"
|
||||
#endif
|
||||
|
||||
#include "crypto.h"
|
||||
#include "e2ee_common.h"
|
||||
#include "ziti/ziti_log.h"
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <windows.h>
|
||||
#include <bcrypt.h>
|
||||
|
||||
// missing in mingw
|
||||
#ifndef BCRYPT_HKDF_ALG_HANDLE
|
||||
#define BCRYPT_HKDF_ALG_HANDLE ((BCRYPT_ALG_HANDLE)0x00000391)
|
||||
#endif
|
||||
|
||||
#ifndef BCRYPT_ECDH_P256_ALG_HANDLE
|
||||
#define BCRYPT_ECDH_P256_ALG_HANDLE ((BCRYPT_ALG_HANDLE)0x02A1)
|
||||
#endif
|
||||
|
||||
#ifndef BCRYPT_AES_GCM_ALG_HANDLE
|
||||
#define BCRYPT_AES_GCM_ALG_HANDLE ((BCRYPT_ALG_HANDLE)0x000001E1)
|
||||
#endif
|
||||
|
||||
|
||||
// Wire-format constants — see plan: must match e2ee_aes_gcm_ossl.c byte-for-byte.
|
||||
#define AES_GCM_TAG_LEN 16
|
||||
#define AES_GCM_NONCE_LEN 12
|
||||
#define AES_GCM_NONCE_PREFIX_LEN 4
|
||||
#define AES_KEY_LEN 32
|
||||
#define ECDH_P256_COORD_LEN 32
|
||||
#define ECDH_P256_PUB_LEN 65 // 0x04 || X(32) || Y(32) — uncompressed wire form
|
||||
#define ECDH_P256_BLOB_LEN (sizeof(BCRYPT_ECCKEY_BLOB) + 2 * ECDH_P256_COORD_LEN) // 72
|
||||
#define HKDF_OUT_LEN (AES_KEY_LEN + AES_GCM_NONCE_PREFIX_LEN) // 36
|
||||
#define HKDF_INFO_LEN (1 + 2 * ECDH_P256_PUB_LEN) // 131
|
||||
|
||||
#if AES_GCM_NONCE_LEN > E2EE_MAX_HEADER_LEN
|
||||
#error "AES_GCM_NONCE_LEN exceeds E2EE_MAX_HEADER_LEN"
|
||||
#endif
|
||||
|
||||
// Algorithm pseudo-handles (BCRYPT_*_ALG_HANDLE constants) require Win10 1809+.
|
||||
// They are static handles — no Open/Close lifecycle, no chain-mode property to set
|
||||
// (BCRYPT_AES_GCM_ALG_HANDLE already has BCRYPT_CHAIN_MODE_GCM bound).
|
||||
|
||||
struct aes_gcm_e2ee {
|
||||
e2ee_t e2ee;
|
||||
|
||||
bool clone;
|
||||
BCRYPT_KEY_HANDLE ecdh_key; // own keypair; destroyed after init() scrubs private material
|
||||
|
||||
uint8_t pub_key[ECDH_P256_PUB_LEN];
|
||||
size_t pub_key_len;
|
||||
|
||||
BCRYPT_KEY_HANDLE tx_aes_key;
|
||||
BCRYPT_KEY_HANDLE rx_aes_key;
|
||||
|
||||
uint8_t rx_key[AES_KEY_LEN]; // kept for sodium_is_zero double-init guard
|
||||
uint8_t tx_key[AES_KEY_LEN];
|
||||
uint8_t rx_iv_prefix[AES_GCM_NONCE_PREFIX_LEN];
|
||||
uint8_t tx_iv_prefix[AES_GCM_NONCE_PREFIX_LEN];
|
||||
uint64_t tx_counter;
|
||||
uint64_t rx_counter;
|
||||
bool header_sent;
|
||||
};
|
||||
|
||||
// Verbatim copy from e2ee_aes_gcm_ossl.c — see plan, interop contract item 4.
|
||||
static void build_nonce(uint8_t out[AES_GCM_NONCE_LEN], const uint8_t *initial, uint64_t counter) {
|
||||
memcpy(out, initial, AES_GCM_NONCE_PREFIX_LEN);
|
||||
int shift = 0;
|
||||
for (int i = AES_GCM_NONCE_LEN; i > AES_GCM_NONCE_PREFIX_LEN; i--) {
|
||||
out[i - 1] = (counter >> shift) & 0xff;
|
||||
shift += 8;
|
||||
}
|
||||
}
|
||||
|
||||
static void reverse_bytes(uint8_t *buf, size_t len) {
|
||||
for (size_t i = 0, j = len - 1; i < j; i++, j--) {
|
||||
uint8_t t = buf[i];
|
||||
buf[i] = buf[j];
|
||||
buf[j] = t;
|
||||
}
|
||||
}
|
||||
|
||||
static int hkdf_sha256(const uint8_t *ikm, size_t ikm_len,
|
||||
const uint8_t *info, size_t info_len,
|
||||
uint8_t *out, size_t out_len) {
|
||||
BCRYPT_KEY_HANDLE hKey = NULL;
|
||||
int ret = -1;
|
||||
|
||||
// Generate KDF Key from Input Keying Material (IKM)
|
||||
NTSTATUS s = BCryptGenerateSymmetricKey(BCRYPT_HKDF_ALG_HANDLE, &hKey, NULL, 0, (PUCHAR)ikm, (ULONG)ikm_len, 0);
|
||||
if (!BCRYPT_SUCCESS(s)) {
|
||||
ZITI_LOG(ERROR, "BCryptGenerateSymmetricKey(HKDF IKM) failed: 0x%lx", s);
|
||||
goto cleanup;
|
||||
}
|
||||
s = BCryptSetProperty(hKey, BCRYPT_HKDF_HASH_ALGORITHM, (void*)BCRYPT_SHA256_ALGORITHM, (ULONG)(sizeof(BCRYPT_SHA256_ALGORITHM)), 0);
|
||||
if (!BCRYPT_SUCCESS(s)) {
|
||||
ZITI_LOG(ERROR, "BCryptSetProperty(SHA-256) failed: 0x%lx", s);
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
// 3. Extract Stage: finalize
|
||||
s = BCryptSetProperty(hKey, BCRYPT_HKDF_SALT_AND_FINALIZE, NULL, 0, 0);
|
||||
if (!BCRYPT_SUCCESS(s)) {
|
||||
ZITI_LOG(ERROR, "BCryptSetProperty(SALT_AND_FINALIZE) failed: 0x%lx", s);
|
||||
goto cleanup;
|
||||
}
|
||||
ULONG written = 0;
|
||||
|
||||
BCryptBuffer params[] = {
|
||||
{ (ULONG)info_len, KDF_HKDF_INFO, (PVOID)info },
|
||||
};
|
||||
BCryptBufferDesc desc = { BCRYPTBUFFER_VERSION, ARRAYSIZE(params), params };
|
||||
s = BCryptKeyDerivation(hKey, &desc, out, out_len, &written, 0);
|
||||
if (!BCRYPT_SUCCESS(s)) {
|
||||
ZITI_LOG(ERROR, "BCryptKeyDerivation failed: 0x%lx", s);
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
ret = 0;
|
||||
|
||||
cleanup:
|
||||
if (hKey) BCryptDestroyKey(hKey);
|
||||
return ret;
|
||||
}
|
||||
|
||||
static int derive_session_keys(struct aes_gcm_e2ee *e,
|
||||
const uint8_t *peer_key, size_t peer_key_len,
|
||||
bool server) {
|
||||
BCRYPT_KEY_HANDLE peer_pub = NULL;
|
||||
BCRYPT_SECRET_HANDLE secret = NULL;
|
||||
uint8_t shared_secret[32] = {0};
|
||||
uint8_t derived[HKDF_OUT_LEN] = {0};
|
||||
uint8_t pub_blob[ECDH_P256_BLOB_LEN] = {0};
|
||||
uint8_t info[HKDF_INFO_LEN];
|
||||
NTSTATUS s;
|
||||
int ret = -1;
|
||||
|
||||
if (peer_key_len != ECDH_P256_PUB_LEN || peer_key[0] != 0x04) {
|
||||
ZITI_LOG(ERROR, "invalid peer P-256 public key (len=%zu, first byte=0x%02x)",
|
||||
peer_key_len, peer_key[0]);
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Build BCRYPT_ECCPUBLIC_BLOB from the 65-byte uncompressed wire form.
|
||||
BCRYPT_ECCKEY_BLOB *hdr = (BCRYPT_ECCKEY_BLOB *)pub_blob;
|
||||
hdr->dwMagic = BCRYPT_ECDH_PUBLIC_P256_MAGIC;
|
||||
hdr->cbKey = ECDH_P256_COORD_LEN;
|
||||
memcpy(pub_blob + sizeof(BCRYPT_ECCKEY_BLOB), peer_key + 1, 2 * ECDH_P256_COORD_LEN);
|
||||
|
||||
s = BCryptImportKeyPair(BCRYPT_ECDH_P256_ALG_HANDLE, NULL, BCRYPT_ECCPUBLIC_BLOB, &peer_pub,
|
||||
pub_blob, sizeof(pub_blob), 0);
|
||||
if (!BCRYPT_SUCCESS(s)) {
|
||||
ZITI_LOG(ERROR, "BCryptImportKeyPair(peer pub) failed: 0x%lx", s);
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
// ECDH agreement
|
||||
s = BCryptSecretAgreement(e->ecdh_key, peer_pub, &secret, 0);
|
||||
if (!BCRYPT_SUCCESS(s)) {
|
||||
ZITI_LOG(ERROR, "BCryptSecretAgreement failed: 0x%lx", s);
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
ULONG written = 0;
|
||||
s = BCryptDeriveKey(secret, BCRYPT_KDF_RAW_SECRET, NULL,
|
||||
shared_secret, sizeof(shared_secret), &written, 0);
|
||||
if (!BCRYPT_SUCCESS(s) || written != sizeof(shared_secret)) {
|
||||
ZITI_LOG(ERROR, "BCryptDeriveKey(RAW_SECRET) failed: 0x%lx (written=%lu)", s, written);
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
// BCRYPT_KDF_RAW_SECRET returns the shared secret in little-endian byte order, while
|
||||
// OpenSSL's EVP_PKEY_derive returns big-endian. Reverse to match the OSSL backend.
|
||||
// (Interop contract item 2.)
|
||||
reverse_bytes(shared_secret, sizeof(shared_secret));
|
||||
|
||||
// rx HKDF: info = role || my_pub || peer_pub
|
||||
info[0] = server ? 1 : 0;
|
||||
memcpy(info + 1, e->pub_key, e->pub_key_len);
|
||||
memcpy(info + 1 + e->pub_key_len, peer_key, peer_key_len);
|
||||
if (hkdf_sha256(shared_secret, sizeof(shared_secret),
|
||||
info, sizeof(info), derived, sizeof(derived)) != 0) {
|
||||
goto cleanup;
|
||||
}
|
||||
memcpy(e->rx_key, derived, sizeof(e->rx_key));
|
||||
memcpy(e->rx_iv_prefix, derived + sizeof(e->rx_key), sizeof(e->rx_iv_prefix));
|
||||
|
||||
// tx HKDF: flip role, swap pub-key order
|
||||
info[0] = server ? 0 : 1;
|
||||
memcpy(info + 1, peer_key, peer_key_len);
|
||||
memcpy(info + 1 + peer_key_len, e->pub_key, e->pub_key_len);
|
||||
if (hkdf_sha256(shared_secret, sizeof(shared_secret),
|
||||
info, sizeof(info), derived, sizeof(derived)) != 0) {
|
||||
goto cleanup;
|
||||
}
|
||||
memcpy(e->tx_key, derived, sizeof(e->tx_key));
|
||||
memcpy(e->tx_iv_prefix, derived + sizeof(e->tx_key), sizeof(e->tx_iv_prefix));
|
||||
|
||||
ret = 0;
|
||||
|
||||
cleanup:
|
||||
SecureZeroMemory(shared_secret, sizeof(shared_secret));
|
||||
SecureZeroMemory(derived, sizeof(derived));
|
||||
SecureZeroMemory(pub_blob, sizeof(pub_blob));
|
||||
if (peer_pub) BCryptDestroyKey(peer_pub);
|
||||
if (secret) BCryptDestroySecret(secret);
|
||||
return ret;
|
||||
}
|
||||
|
||||
static e2ee_pub_t aes_gcm_pub(struct e2ee *e2ee) {
|
||||
struct aes_gcm_e2ee *e = (struct aes_gcm_e2ee *)e2ee;
|
||||
PRINT_BYTES("own pub key", e->pub_key, e->pub_key_len);
|
||||
return (e2ee_pub_t){.key = e->pub_key, .key_len = e->pub_key_len};
|
||||
}
|
||||
|
||||
static int aes_gcm_init(struct e2ee *e2ee, const uint8_t *peer_key, size_t peer_key_len, bool server) {
|
||||
struct aes_gcm_e2ee *e = (struct aes_gcm_e2ee *)e2ee;
|
||||
|
||||
if (peer_key_len != e->pub_key_len) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Already initialized
|
||||
if (!sodium_is_zero(e->rx_key, sizeof(e->rx_key)) ||
|
||||
!sodium_is_zero(e->tx_key, sizeof(e->tx_key))) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
int ret = derive_session_keys(e, peer_key, peer_key_len, server);
|
||||
|
||||
// Scrub ECDH private key material regardless of outcome
|
||||
if (e->ecdh_key && !e->clone) {
|
||||
BCryptDestroyKey(e->ecdh_key);
|
||||
e->ecdh_key = NULL;
|
||||
}
|
||||
|
||||
if (ret != 0) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
e->tx_counter = 1;
|
||||
e->rx_counter = 1;
|
||||
|
||||
NTSTATUS s = BCryptGenerateSymmetricKey(BCRYPT_AES_GCM_ALG_HANDLE, &e->tx_aes_key, NULL, 0,
|
||||
e->tx_key, AES_KEY_LEN, 0);
|
||||
if (!BCRYPT_SUCCESS(s)) {
|
||||
ZITI_LOG(ERROR, "BCryptGenerateSymmetricKey(tx) failed: 0x%lx", s);
|
||||
return -1;
|
||||
}
|
||||
s = BCryptGenerateSymmetricKey(BCRYPT_AES_GCM_ALG_HANDLE, &e->rx_aes_key, NULL, 0,
|
||||
e->rx_key, AES_KEY_LEN, 0);
|
||||
if (!BCRYPT_SUCCESS(s)) {
|
||||
ZITI_LOG(ERROR, "BCryptGenerateSymmetricKey(rx) failed: 0x%lx", s);
|
||||
return -1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
static ssize_t aes_gcm_get_header(struct e2ee *e2ee, uint8_t header[E2EE_MAX_HEADER_LEN]) {
|
||||
struct aes_gcm_e2ee *e = (struct aes_gcm_e2ee *)e2ee;
|
||||
if (header == NULL) {
|
||||
return -1;
|
||||
}
|
||||
if (e->header_sent) {
|
||||
return -1;
|
||||
}
|
||||
// IV prefix and counter origin are agreed during init via HKDF; nothing to send.
|
||||
e->header_sent = true;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static ssize_t aes_gcm_encrypt(e2ee_t *e2ee, const uint8_t *plaintext, size_t plaintext_len,
|
||||
uint8_t *ciphertext, size_t ciphertext_len) {
|
||||
struct aes_gcm_e2ee *e = (struct aes_gcm_e2ee *)e2ee;
|
||||
if (ciphertext_len < plaintext_len + AES_GCM_TAG_LEN) {
|
||||
return -1;
|
||||
}
|
||||
if (e->tx_counter == UINT64_MAX) {
|
||||
ZITI_LOG(ERROR, "AES-GCM encryption counter overflow");
|
||||
return -1;
|
||||
}
|
||||
|
||||
uint8_t iv[AES_GCM_NONCE_LEN];
|
||||
build_nonce(iv, e->tx_iv_prefix, e->tx_counter);
|
||||
|
||||
BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO info;
|
||||
BCRYPT_INIT_AUTH_MODE_INFO(info);
|
||||
info.pbNonce = iv;
|
||||
info.cbNonce = AES_GCM_NONCE_LEN;
|
||||
info.pbTag = ciphertext + plaintext_len; // tag appended after ciphertext
|
||||
info.cbTag = AES_GCM_TAG_LEN;
|
||||
|
||||
ULONG written = 0;
|
||||
NTSTATUS s = BCryptEncrypt(e->tx_aes_key, (PUCHAR)plaintext, (ULONG)plaintext_len,
|
||||
&info, NULL, 0, ciphertext, (ULONG)plaintext_len,
|
||||
&written, 0);
|
||||
if (!BCRYPT_SUCCESS(s) || written != plaintext_len) {
|
||||
ZITI_LOG(ERROR, "aes-gcm encryption failed: 0x%lx (written=%lu, expected=%zu)",
|
||||
s, written, plaintext_len);
|
||||
return -1;
|
||||
}
|
||||
|
||||
e->tx_counter++;
|
||||
return (ssize_t)(plaintext_len + AES_GCM_TAG_LEN);
|
||||
}
|
||||
|
||||
static ssize_t aes_gcm_decrypt(e2ee_t *e2ee, const uint8_t *ciphertext, size_t ciphertext_len,
|
||||
uint8_t *plaintext, size_t plaintext_len) {
|
||||
struct aes_gcm_e2ee *e = (struct aes_gcm_e2ee *)e2ee;
|
||||
if (ciphertext_len <= AES_GCM_TAG_LEN) {
|
||||
return -1;
|
||||
}
|
||||
size_t ct_data_len = ciphertext_len - AES_GCM_TAG_LEN;
|
||||
if (plaintext_len < ct_data_len) {
|
||||
return -1;
|
||||
}
|
||||
if (e->rx_counter == UINT64_MAX) {
|
||||
ZITI_LOG(ERROR, "AES-GCM decryption counter overflow");
|
||||
return -1;
|
||||
}
|
||||
|
||||
uint8_t iv[AES_GCM_NONCE_LEN];
|
||||
build_nonce(iv, e->rx_iv_prefix, e->rx_counter);
|
||||
|
||||
BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO info;
|
||||
BCRYPT_INIT_AUTH_MODE_INFO(info);
|
||||
info.pbNonce = iv;
|
||||
info.cbNonce = AES_GCM_NONCE_LEN;
|
||||
info.pbTag = (PUCHAR)(ciphertext + ct_data_len);
|
||||
info.cbTag = AES_GCM_TAG_LEN;
|
||||
|
||||
ULONG written = 0;
|
||||
NTSTATUS s = BCryptDecrypt(e->rx_aes_key, (PUCHAR)ciphertext, (ULONG)ct_data_len,
|
||||
&info, NULL, 0, plaintext, (ULONG)ct_data_len,
|
||||
&written, 0);
|
||||
if (!BCRYPT_SUCCESS(s) || written != ct_data_len) {
|
||||
ZITI_LOG(WARN, "aes-gcm decryption failed: 0x%lx (written=%lu, expected=%zu)",
|
||||
s, written, ct_data_len);
|
||||
return -1;
|
||||
}
|
||||
|
||||
e->rx_counter++;
|
||||
return (ssize_t)ct_data_len;
|
||||
}
|
||||
|
||||
static struct e2ee *aes_gcm_clone(struct e2ee *e2ee) {
|
||||
struct aes_gcm_e2ee *e = (struct aes_gcm_e2ee*)e2ee;
|
||||
struct aes_gcm_e2ee *clone = calloc(1, sizeof(struct aes_gcm_e2ee));
|
||||
if (clone == NULL) {
|
||||
ZITI_LOG(ERROR, "failed to allocate aes-gcm e2ee: out of memory");
|
||||
abort();
|
||||
}
|
||||
|
||||
|
||||
clone->e2ee = e->e2ee;
|
||||
clone->clone = true;
|
||||
clone->ecdh_key = e->ecdh_key;
|
||||
memcpy(clone->pub_key, e->pub_key, e->pub_key_len);
|
||||
clone->pub_key_len = e->pub_key_len;
|
||||
|
||||
return (struct e2ee *)clone;
|
||||
}
|
||||
|
||||
static void aes_gcm_free(e2ee_t *e2ee) {
|
||||
struct aes_gcm_e2ee *e = (struct aes_gcm_e2ee *)e2ee;
|
||||
if (e->tx_aes_key) BCryptDestroyKey(e->tx_aes_key);
|
||||
if (e->rx_aes_key) BCryptDestroyKey(e->rx_aes_key);
|
||||
if (!e->clone && e->ecdh_key) BCryptDestroyKey(e->ecdh_key);
|
||||
SecureZeroMemory(e, sizeof(struct aes_gcm_e2ee));
|
||||
free(e);
|
||||
}
|
||||
|
||||
static e2ee_t aes_gcm_e2ee_impl = {
|
||||
.method = ziti_crypto_aes_gcm,
|
||||
.clone = aes_gcm_clone,
|
||||
.pub = aes_gcm_pub,
|
||||
.init = aes_gcm_init,
|
||||
.get_header = aes_gcm_get_header,
|
||||
.encrypt = aes_gcm_encrypt,
|
||||
.decrypt = aes_gcm_decrypt,
|
||||
.free = aes_gcm_free,
|
||||
};
|
||||
|
||||
struct aes_gcm_e2ee *new_aes_gcm_e2ee(void) {
|
||||
struct aes_gcm_e2ee *e = calloc(1, sizeof(struct aes_gcm_e2ee));
|
||||
if (e == NULL) {
|
||||
ZITI_LOG(ERROR, "failed to allocate aes-gcm e2ee: out of memory");
|
||||
abort();
|
||||
}
|
||||
|
||||
e->e2ee = aes_gcm_e2ee_impl;
|
||||
|
||||
NTSTATUS s = BCryptGenerateKeyPair(BCRYPT_ECDH_P256_ALG_HANDLE, &e->ecdh_key, 256, 0);
|
||||
if (!BCRYPT_SUCCESS(s)) {
|
||||
ZITI_LOG(ERROR, "BCryptGenerateKeyPair(P-256) failed: 0x%lx", s);
|
||||
aes_gcm_free((e2ee_t *)e);
|
||||
abort();
|
||||
}
|
||||
s = BCryptFinalizeKeyPair(e->ecdh_key, 0);
|
||||
if (!BCRYPT_SUCCESS(s)) {
|
||||
ZITI_LOG(ERROR, "BCryptFinalizeKeyPair(P-256) failed: 0x%lx", s);
|
||||
aes_gcm_free((e2ee_t *)e);
|
||||
abort();
|
||||
}
|
||||
|
||||
// Export BCRYPT_ECCPUBLIC_BLOB (72 bytes) and convert to 65-byte uncompressed wire form.
|
||||
uint8_t blob[ECDH_P256_BLOB_LEN];
|
||||
ULONG blob_len = 0;
|
||||
s = BCryptExportKey(e->ecdh_key, NULL, BCRYPT_ECCPUBLIC_BLOB,
|
||||
blob, sizeof(blob), &blob_len, 0);
|
||||
if (!BCRYPT_SUCCESS(s) || blob_len != sizeof(blob)) {
|
||||
ZITI_LOG(ERROR, "BCryptExportKey(ECCPUBLIC_BLOB) failed: 0x%lx (blob_len=%lu)",
|
||||
s, blob_len);
|
||||
aes_gcm_free((e2ee_t *)e);
|
||||
abort();
|
||||
}
|
||||
|
||||
e->pub_key[0] = 0x04;
|
||||
memcpy(e->pub_key + 1, blob + sizeof(BCRYPT_ECCKEY_BLOB), 2 * ECDH_P256_COORD_LEN);
|
||||
e->pub_key_len = ECDH_P256_PUB_LEN;
|
||||
|
||||
return e;
|
||||
}
|
||||
@@ -119,7 +119,6 @@ enum connection_type {
|
||||
|
||||
enum crypto_method {
|
||||
CryptoMethodLibsodium = 0,
|
||||
CryptoMethodAES256GCM = 1,
|
||||
};
|
||||
|
||||
enum edge_flag {
|
||||
|
||||
@@ -44,7 +44,13 @@ public:
|
||||
->expected(0,1)
|
||||
->default_str("3128");
|
||||
|
||||
add_flag("--aes", aes_crypto, "e2ee: use AES-GCM (instead of libsodium)");
|
||||
add_option("--e2ee", e2ee_method, "e2ee method")
|
||||
->transform(CLI::CheckedTransformer(std::map<std::string, ziti_crypto_method>{
|
||||
{"none", ziti_crypto_none},
|
||||
{"libsodium", ziti_crypto_libsodium},
|
||||
{"tls", ziti_crypto_tls},
|
||||
}, CLI::ignore_case))
|
||||
->default_str("libsodium");
|
||||
final_callback([this] {
|
||||
this->execute();
|
||||
});
|
||||
@@ -52,7 +58,7 @@ public:
|
||||
|
||||
|
||||
private:
|
||||
bool aes_crypto{false};
|
||||
ziti_crypto_method e2ee_method{ziti_crypto_libsodium};
|
||||
int debug{3};
|
||||
std::string identity;
|
||||
std::vector<std::string> intercepts;
|
||||
@@ -63,7 +69,7 @@ private:
|
||||
|
||||
void execute() const {
|
||||
run_opts opts{};
|
||||
opts.e2ee_method = aes_crypto ? ziti_crypto_aes_gcm : ziti_crypto_libsodium;
|
||||
opts.e2ee_method = this->e2ee_method;
|
||||
opts.identity = this->identity.c_str();
|
||||
opts.debug = this->debug;
|
||||
opts.http_proxy_port = this->http_proxy_port;
|
||||
|
||||
@@ -26,11 +26,6 @@ add_executable(all_tests
|
||||
posture_tests.cpp)
|
||||
|
||||
set_property(TARGET all_tests PROPERTY CXX_STANDARD 20)
|
||||
if (WIN32)
|
||||
find_package(OpenSSL REQUIRED)
|
||||
target_link_libraries(all_tests PRIVATE OpenSSL::Crypto)
|
||||
endif ()
|
||||
|
||||
target_compile_definitions(all_tests
|
||||
PRIVATE ZITI_TEST_DIR=${CMAKE_CURRENT_SOURCE_DIR})
|
||||
target_include_directories(all_tests
|
||||
|
||||
+1
-79
@@ -83,7 +83,7 @@ static void test_e2ee(e2ee_t *alice, e2ee_t *bob) {
|
||||
|
||||
TEST_CASE("e2ee", "[crypto]") {
|
||||
ziti_log_init(nullptr, 5, nullptr);
|
||||
auto e2ee = GENERATE(ziti_crypto_none, ziti_crypto_libsodium, ziti_crypto_aes_gcm);
|
||||
auto e2ee = GENERATE(ziti_crypto_none, ziti_crypto_libsodium);
|
||||
WHEN("e2ee_impl_t: " << e2ee_method_id(e2ee)) {
|
||||
auto alice = std::unique_ptr<e2ee_t, e2ee_deleter>(create_e2ee(e2ee, false, nullptr));
|
||||
auto bob = std::unique_ptr<e2ee_t, e2ee_deleter>(create_e2ee(e2ee, false, nullptr));
|
||||
@@ -181,84 +181,6 @@ TEST_CASE("e2ee libsodium decrypt retries after partial header", "[crypto]") {
|
||||
}
|
||||
|
||||
|
||||
#if defined(__APPLE__)
|
||||
namespace ossl {
|
||||
#include "../library/e2ee/e2ee_aes_gcm_ossl.c"
|
||||
}
|
||||
// the Apple backend derives keys with Security.framework + CommonCrypto, so this is what
|
||||
// proves it stays wire-compatible with the OpenSSL/BCrypt peers. Both orderings, because
|
||||
// the two directions use different HKDF info.
|
||||
TEST_CASE("e2ee-ossl-apple-interop", "[crypto]") {
|
||||
ziti_log_init(nullptr, 5, nullptr);
|
||||
|
||||
WHEN("apple is the server") {
|
||||
auto alice = std::unique_ptr<e2ee_t, e2ee_deleter>(create_e2ee(ziti_crypto_aes_gcm, false, nullptr));
|
||||
auto bob = std::unique_ptr<e2ee_t, e2ee_deleter>((e2ee_t *)ossl::new_aes_gcm_e2ee());
|
||||
test_e2ee(alice.get(), bob.get());
|
||||
}
|
||||
|
||||
WHEN("openssl is the server") {
|
||||
auto alice = std::unique_ptr<e2ee_t, e2ee_deleter>((e2ee_t *)ossl::new_aes_gcm_e2ee());
|
||||
auto bob = std::unique_ptr<e2ee_t, e2ee_deleter>(create_e2ee(ziti_crypto_aes_gcm, false, nullptr));
|
||||
test_e2ee(alice.get(), bob.get());
|
||||
}
|
||||
}
|
||||
// the ossl backend above defines the same tuning macros with different values
|
||||
#undef AES_GCM_TAG_LEN
|
||||
#undef AES_GCM_NONCE_LEN
|
||||
#undef AES_GCM_NONCE_PREFIX_LEN
|
||||
#undef AES_GCM_KEY_LEN
|
||||
#undef P256_PUB_KEY_LEN
|
||||
namespace apple {
|
||||
#include "../library/e2ee/e2ee_aes_gcm_apple.c"
|
||||
}
|
||||
// An empty payload reaches the CryptoKit shim as (NULL, 0), a different path through the
|
||||
// Swift bridging than a non-empty buffer -- and one that traps inside CryptoKit if the null
|
||||
// base pointer is passed straight through, where the CommonCrypto one-shot accepted it.
|
||||
// Note the receiving side rejects a tag-only frame (ciphertext_len <= AES_GCM_TAG_LEN); that
|
||||
// guard is pre-existing and identical in the OpenSSL backend, so this only pins encrypt.
|
||||
TEST_CASE("e2ee-apple-aes-gcm-empty-payload", "[crypto]") {
|
||||
auto alice = std::unique_ptr<e2ee_t, e2ee_deleter>(create_e2ee(ziti_crypto_aes_gcm, false, nullptr));
|
||||
auto bob = std::unique_ptr<e2ee_t, e2ee_deleter>(create_e2ee(ziti_crypto_aes_gcm, false, nullptr));
|
||||
auto alice_pub = alice->pub(alice.get());
|
||||
auto bob_pub = bob->pub(bob.get());
|
||||
REQUIRE(alice->init(alice.get(), bob_pub.key, bob_pub.key_len, true) == 0);
|
||||
REQUIRE(bob->init(bob.get(), alice_pub.key, alice_pub.key_len, false) == 0);
|
||||
|
||||
// must not trap: produces a tag and nothing else
|
||||
uint8_t ciphertext[E2EE_MAX_MSG_OVERHEAD];
|
||||
auto ct_len = alice->encrypt(alice.get(), nullptr, 0, ciphertext, sizeof(ciphertext));
|
||||
REQUIRE(ct_len == 16);
|
||||
|
||||
// and the receive side must not trap on the resulting tag-only frame either
|
||||
uint8_t out[16];
|
||||
REQUIRE(bob->decrypt(bob.get(), ciphertext, ct_len, out, sizeof(out)) == -1);
|
||||
}
|
||||
|
||||
// RFC 5869 test case 3: SHA-256, zero-length salt and info. The zero-length salt is exactly
|
||||
// what derive_session_keys() uses, so this pins the CCHmac-based HKDF independently of OpenSSL.
|
||||
TEST_CASE("e2ee-apple-hkdf-rfc5869", "[crypto]") {
|
||||
const uint8_t ikm[22] = {
|
||||
0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,
|
||||
0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,
|
||||
};
|
||||
const uint8_t expected[42] = {
|
||||
0x8d, 0xa4, 0xe7, 0x75, 0xa5, 0x63, 0xc1, 0x8f, 0x71, 0x5f, 0x80, 0x2a, 0x06, 0x3c,
|
||||
0x5a, 0x31, 0xb8, 0xa1, 0x1f, 0x5c, 0x5e, 0xe1, 0x87, 0x9e, 0xc3, 0x45, 0x4e, 0x5f,
|
||||
0x3c, 0x73, 0x8d, 0x2d, 0x9d, 0x20, 0x13, 0x95, 0xfa, 0xa4, 0xb6, 0x1a, 0x96, 0xc8,
|
||||
};
|
||||
const uint8_t info[1] = {0};
|
||||
|
||||
uint8_t out[sizeof(expected)];
|
||||
REQUIRE(apple::hkdf_sha256(ikm, sizeof(ikm), info, 0, out, sizeof(out)) == 0);
|
||||
REQUIRE(memcmp(out, expected, sizeof(expected)) == 0);
|
||||
|
||||
// more than 255 blocks of output is out of range for HKDF
|
||||
REQUIRE(apple::hkdf_sha256(ikm, sizeof(ikm), info, 0, out, 255 * 32 + 1) == -1);
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
TEST_CASE("e2ee-tls", "[crypto]") {
|
||||
ziti_log_init(nullptr, 6, nullptr);
|
||||
auto ca = R"(-----BEGIN CERTIFICATE-----
|
||||
|
||||
@@ -36,11 +36,6 @@
|
||||
"name": "catch2",
|
||||
"$comment": "main testing framework"
|
||||
},
|
||||
{
|
||||
"name": "openssl",
|
||||
"platform": "windows | mingw",
|
||||
"$comment": "for testing e2ee compat"
|
||||
},
|
||||
{
|
||||
"name": "botan",
|
||||
"$comment": "needed for TOTP testing"
|
||||
|
||||
Reference in New Issue
Block a user