Skip to content

fix: address remaining 34 security and bug audit findings (#69) - #70

Merged
arkavo-com merged 3 commits into
mainfrom
fix/69-security-audit
Nov 23, 2026
Merged

arkavo-com merged 3 commits into
mainfrom
fix/69-security-audit

Conversation

@arkavo-com

Copy link
Copy Markdown
Contributor

Summary

Resolves all 34 remaining open and partially-fixed findings from the v5.1.0 security and bug audit in #69 (4 of the original 38 findings — #3, #18, #28, #36 — were already fully fixed on main in PR #65).

Findings Addressed

NanoTDF Cryptography & Parsing

  • Serializer #1 (CryptoHelper.swift, NanoTDF.swift): .embeddedEncrypted now derives a domain-separated policy key via HKDF-SHA256(ikm: tdfSymmetricKey, salt: hkdfSaltV12, info: "nanotdf-embedded-policy") and appends the 16-byte AES-GCM authentication tag, eliminating (tdfSymmetricKey, [0; 12]) nonce reuse with createGMACBinding. .embeddedEncryptedWithPolicyKeyAccess also appends its 16-byte GCM tag.
  • Signature and Policy Key #2 (NanoTDFCollectionBuilder.swift): Actually encrypts .embeddedEncrypted and .embeddedEncryptedWithKeyAccess policy bodies instead of storing plaintext, validates policy size via serializedData(), and computes the GMAC policy binding over serialized EmbeddedPolicyBody bytes.
  • Update Swift package version and platform versions #4 (BinaryParser.swift, NanoTDFCollectionParser.swift): Made read(length:) and NanoTDFCollectionFile.parse(from:) startIndex-safe and overflow-safe against Data slices and huge header lengths.
  • Rewrap #5 (CryptoHelper.swift, NanoTDF.swift): Added generateNonZeroNonce(length:) so createNanoTDF never generates an all-zero payload IV.
  • KASWebSocket kasUrl #6 (NanoTDF.swift): addSignatureToNanoTDF rejects non-P256 signatureCurve requests (CryptoHelperError.unsupportedCurve) and sets .secp256r1 when nil.
  • Refactor KASWebSocket.swift for managing connection state #7 (NanoTDF.swift, NanoTDFCollectionDecryptor.swift, KASService.swift): Added Header.verifyPolicyBinding(symmetricKey:) (constant-time GMAC and ECDSA verification) and enforced it in NanoTDF.getPayloadPlaintext(symmetricKey:), NanoTDF.getPlaintext(using:), NanoTDFCollectionDecryptor, and KASService rewrap/key-access paths.
  • NanoTDF concurrent #12 (KeyStore.swift, NanoTDF.swift, NanoTDFCollectionDecryptor.swift): Added v12 parsed-header key resolution in KeyStore.derivePayloadSymmetricKey(header:) (via unique ResourceLocator.identifier match or single-key store) plus explicit kasPublicKey: overloads.
  • NanoTDF KAS rewrap support #20 (CryptoHelper.swift): Replaced CryptoSwift.GCM for truncated tag sizes (64/96/104/112/120-bit) with constant-time CoreCrypto CommonCrypto kCCModeCTR + CryptoKit.AES.GCM.seal + constant-time tag prefix verification (zeroing plaintext on mismatch) and removed import CryptoSwift.
  • TDF support #21 (NanoTDF.swift): Added throwing Payload.serializedData() and EmbeddedPolicyBody.serializedData(); prevented non-throwing toData() from trapping on oversized inputs.
  • Adopt Post-Quantum Cryptography with Hybrid Approach #22 (BinaryParser.swift): Rejected unknown identifierType values (4...15) and missing/truncated PolicyKeyAccess on .embeddedEncryptedWithPolicyKeyAccess.
  • feat: AES-128 support for FairPlay Streaming compatibility #33 (BinaryParser.swift): Restored wire nibble 0x0F mapping to ProtocolEnum.sharedResourceDirectory.

KAS Discovery, Transport, Rewrap & KeyStore

  • WebSocketConnectionState #8 & Reduce code duplication across codebase #34 (KASRewrapClient.swift): rewrapNanoTDF signs the request JWT with clientKeyPair.privateKey (ES256/ES384/ES512), sets algorithm from clientKeyPair.curve, supports P-256/P-384/P-521 in PEM encoding/decoding and unwrapKey, and encodes remote.toData() instead of "{}" for .remote policies.
  • Swift 6 #9 & Developer Experience Improvements for StandardTDF Encryption/Decryption #24 (KASDiscovery.swift, KASService.swift, KASRewrapClient.swift): Added internal BoundedHTTPClient (disables redirects and caps buffered response bytes) for fetchWellKnown (1 MiB), KASService.rewrapKey (1 MiB, 30 s timeout), and URLSessionKASTransport (16 MiB default); fetchWellKnown and KASService.rewrapKey now validate URLs via validateKasURL, and fetchWellKnown no longer leaks raw server error bodies.
  • Make toData methods public #10 (KASDiscovery.swift): Hardened validateKasURL against case/trailing-dot localhost, URL userinfo, IPv6 % zone IDs, non-canonical IPv4 literals (octal/hex/integer/shorthand — checked both before inet_pton and on the raw unnormalized authority host), and full reserved CIDR coverage (0.0.0.0/8, 100.64.0.0/10, 224.0.0.0/4, 240.0.0.0/4, ::ffff:0:0/96, ::ffff:0:0:0/96, 64:ff9b::/96, 64:ff9b:1::/48, fec0::/10, ff00::/8).
  • Fix endianness issue in BinaryParser content length read #11 (KeyStore.swift, KASService.swift): Added atomic KeyStore.popPrivateKey(forPublicKey:) used by KASService.processKeyAccessWithKeyIdentifier alongside deterministic RFC 4122 v5-style UUID generation from SHA256(kasPublicKey).
  • Developer ergonomics #23 (PublicKeyStore.swift): deserialize(from:) now parses and bounds-checks all keys locally before atomically replacing store contents.
  • Improve NanoTDF Developer Experience #25 (KASRewrapClient.swift): rewrapTDF rejects unknown or duplicate KAO IDs; rewrapAndUnwrapTDFShares enforces "kao-" bounds and sorts numerically rather than lexicographically.
  • DX #26 (KASDiscovery.swift): needsKasEndpointSynthesis returns false whenever any endpoint URL is present (even if kas.uri is empty), preventing silent override of explicit/hostile kas blocks.
  • Feature Request: AES-128 Support for FairPlay Streaming Compatibility #32 (KeyStore.swift): Maintained accurate totalBytesStored across all mutations and added overflow checks in deserialize(from:).
  • fix Standard TDF rewrap request format #35 (KeyStore.swift, KASBulkRewrap.swift, KASService.swift): Backed StoredKeyPair with SecureKeyPairStorage (memset_s on deinit), zeroed local private-key/DEK copies, and validated non-empty wrapped DEKs (> 28 bytes) in KASBulkRewrap.

Standard TDF, JSON/CBOR & Streaming

Wire-Format & Compatibility Notes

  • Backwards source compatibility (ArkavoKit): Preserved all existing public API signatures via default parameter values and additive overloads.
  • Coordinated wire-format note (Serializer #1 & Signature and Policy Key #2 — .embeddedEncrypted): .embeddedEncrypted now encrypts with a domain-separated HKDF key (info = "nanotdf-embedded-policy") and appends a 16-byte GCM authentication tag to EmbeddedPolicyBody.body. .remote and .embeddedPlaintext wire formats are unchanged. Any Rust KAS or receiver decrypting .embeddedEncrypted policies must adopt the derived policy key + 16-byte GCM tag.
  • Standard TDF policy binding (Header and Payload from OpenTDFKit aren't Codable #13): TDFCrypto.verifyPolicyBinding accepts both spec-form Base64(raw HMAC-SHA256) (32 bytes) and legacy Go SDK Base64(hex(HMAC-SHA256)) (64 bytes) for backwards wire compatibility.
  • v12 NanoTDF KeyStore (NanoTDF concurrent #12): Keeps the v12 wire format intact (no KAS public key in header) and resolves parsed v12 headers via ResourceLocator.identifier / single-key store or explicit kasPublicKey: overload.
  • TDF-CBOR (Implement FIPS 203 (ML-KEM) Support for Quantum-Resistant Key Encapsulation in OpenTDFKit #29): Encodes sid under CBOR key 10 and preserves PEM ephemeralPublicKey as a UTF-8 string (decoding both byteString and utf8String).

Verification

  • swiftformat --swiftversion 6.2 . && swiftformat --lint . — 0/80 files require formatting
  • swift test --skip BenchmarkTests — 448 tests executed, 12 skipped, 0 failures (including 25 new regression tests in OpenTDFKitTests/SecurityAuditRegressionTests.swift)
  • swift build -c release & swift build -c release --product OpenTDFKitCLI — clean builds, 0 new warnings
  • Go ec-wrapped interop (scripts/interop/ec-wrapped): go vet ./..., go test ./..., and go run . verify against TDFKASEncryptorTests/testWriteSwiftFixtureForGo — OK

Ready for multi-model PR review.

Closes #69

Resolves all 34 open and partially-fixed findings from the v5.1.0 security
and bug audit in #69 (4 of the 38 findings — #3, #18, #28, #36 — were
already resolved in PR #65):

- NanoTDF crypto & parsing (#1, #2, #4, #5, #6, #7, #12, #20, #21, #22, #33):
  - Domain-separated HKDF policy key + appended 16-byte GCM tag for
    .embeddedEncrypted and .embeddedEncryptedWithPolicyKeyAccess (fixes
    nonce reuse and plaintext fallback in NanoTDFCollectionBuilder).
  - Non-zero IV generation; reject non-P256 curves in addSignatureToNanoTDF;
    enforce policy binding verification on decrypt; v12 KeyStore resolution
    for parsed headers; constant-time CoreCrypto CTR+GCM for truncated tags
    (removing CryptoSwift.GCM); startIndex/overflow-safe BinaryParser &
    collection parser; strict identifierType/PolicyKeyAccess checks; restore
    ProtocolEnum.sharedResourceDirectory wire mapping (0x0F).
- KAS discovery, transport, rewrap & KeyStore (#8, #9, #10, #11, #23, #24,
  #25, #26, #32, #34, #35):
  - Harden validateKasURL against non-canonical IPv4 (octal/hex/int/short),
    userinfo, IPv6 zone IDs, and reserved CIDRs (0/8, 100.64/10, 224/4,
    240/4, ::ffff:0:0/96, NAT64, fec0::/10, ff00::/8).
  - BoundedHTTPClient (no redirects, response byte cap) for well-known,
    KASService, and URLSessionKASTransport; no raw server bodies in errors;
    preserve explicit kas endpoints when kas.uri is empty.
  - Atomic popPrivateKey + deterministic key IDs in KASService; multi-curve
    P-256/P-384/P-521 NanoTDF rewrap with client-key JWT signing & remote
    policy encoding; strict KAO ID validation and numeric share sorting.
  - Secure zeroing of key material in KeyStore & bulk rewrap, accurate
    totalBytesStored tracking, and atomic PublicKeyStore.deserialize.
- Standard TDF, JSON/CBOR & streaming (#13, #14, #15, #16, #17, #19, #27,
  #29, #30, #31, #37, #38):
  - Policy binding verification (spec raw + legacy hex) and symmetric key
    bit-count validation across Archive, JSON, and CBOR decryptors; explicit
    rejection of multi-split JSON/CBOR manifests.
  - Per-segment hash & optional rootSignature verification with buffered
    output in StreamingTDFCrypto; overflow-safe chunking & bounded archive
    payload reads; multi-curve EC unwrap; zeroing of intermediate key copies.
  - Iterative depth/size-bounded CBOR pre-validator; startIndex-safe magic
    check; PEM ephemeralPublicKey, encryptedMetadata & sid round-tripping;
    accurate CBOR format detection and bounded JSON file probing.

Adds SecurityAuditRegressionTests covering all 34 findings.

Closes #69
- TDFArchive & TDFLoader: stop rejecting Go ZIP64/data-descriptor
  placeholder entry.uncompressedSize before extraction (fixes swift <-> go
  X-Test failure); enforce cap on running extracted bytes; make TDFLoader's
  default parameter defaultPayloadMaxSize so explicit nil remains uncapped.
- TDFCBORFormat: track explicit per-frame nesting depth in
  validateCBORStructure, charge indefinite-string chunks against maxItems,
  and pass CBOROptions(maximumDepth: 32) to SwiftCBOR.
- TDFProcessor & OpenTDFKitCLI: fail closed in bare-DEK decryptEncryptionInfo
  when keyAccess is empty or multi-split; add TDFDecryptor.decrypt(container:
  keyShares:) verifying every split share's policy binding; switch CLI to
  decrypt(container:keyShares:) and withUnwrappedKey(header:symmetricKey:).
- KeyStore & KASService: resolve v12 key pairs once in
  processKeyAccess(header:encryptedKey:kasPublicKey:), restore popped
  one-time keys on validation/rewrap failure, add mandatory-binding
  overloads (deprecating unverified overloads), and use RFC 9562 v8 marker.
- KASDiscovery: synchronize BoundedHTTPClient start/finish/cancel in a
  single state machine to prevent pre-registration cancellation hangs;
  reject trailing-dot numeric IPv4 literals and block ::/96 (except ::1).
- StreamingTDFCrypto: compute rootSignature on encrypt, enforce
  rootSignature on multi-segment decrypt, support HS256 & GMAC
  segmentHashAlg, and replace temp-file buffering with two-pass
  verify-then-decrypt.
- TDFFormatDetector, NanoTDF & cleanup: bound JSON probe reads directly
  (no readToEnd TOCTOU), validate Payload.serializedData() actual length,
  remove redundant checks and stale CryptoSwift comments, and strengthen
  SecurityAuditRegressionTests.
@arkavo-com

Copy link
Copy Markdown
Contributor Author

Gitar review

- StreamingTDFCrypto: require rootSignature for every payload (including
  1-segment, blocking truncation-to-1-segment bypasses), re-verify each
  Pass-2 segment signature against Pass 1 with length guards before writing,
  and ensure decryptPayloadMultiSegmentFromMemory zeroes plaintext on all
  error exits.
- TDFProcessor: skip invalid replica shares in decrypt(container:keyShares:)
  so another valid replica for the same split can succeed; document
  single-split vs keyShares usage across TDFProcessor, KASRewrapClient, and
  TDFKAS.
- KASService: peek-validate-then-pop in processKeyAccessWithKeyIdentifier
  so malformed requests neither burn one-time keys nor create transient
  keyNotFound windows for concurrent valid callers.
- KASDiscovery: guard BoundedHTTPClient chunk-size check against
  data.count > maxBytes underflow and block 6to4 (2002::/16) and Teredo
  (2001:0000::/32) IPv6 prefixes.
- NanoTDF & Tests: add NanoTDFError.payloadLengthMismatch for
  Payload.serializedData() and expand regression tests for 1-segment nil
  root, bad replica share, 6to4/Teredo, deterministic cancellation, and
  payload length mismatch.
@arkavo-com
arkavo-com merged commit 2c0adad into main Nov 23, 2026
8 checks passed
@arkavo-com
arkavo-com deleted the fix/69-security-audit branch November 23, 2026 01:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Security and bug audit of OpenTDFKit v5.1.0 (38 findings)

1 participant