Repository navigation
fix: address remaining 34 security and bug audit findings (#69) - #70
Merged
Merged
Conversation
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.
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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
mainin PR #65).Findings Addressed
NanoTDF Cryptography & Parsing
CryptoHelper.swift,NanoTDF.swift):.embeddedEncryptednow derives a domain-separated policy key viaHKDF-SHA256(ikm: tdfSymmetricKey, salt: hkdfSaltV12, info: "nanotdf-embedded-policy")and appends the 16-byte AES-GCM authentication tag, eliminating(tdfSymmetricKey, [0; 12])nonce reuse withcreateGMACBinding..embeddedEncryptedWithPolicyKeyAccessalso appends its 16-byte GCM tag.NanoTDFCollectionBuilder.swift): Actually encrypts.embeddedEncryptedand.embeddedEncryptedWithKeyAccesspolicy bodies instead of storing plaintext, validates policy size viaserializedData(), and computes the GMAC policy binding over serializedEmbeddedPolicyBodybytes.BinaryParser.swift,NanoTDFCollectionParser.swift): Maderead(length:)andNanoTDFCollectionFile.parse(from:)startIndex-safe and overflow-safe againstDataslices and huge header lengths.CryptoHelper.swift,NanoTDF.swift): AddedgenerateNonZeroNonce(length:)socreateNanoTDFnever generates an all-zero payload IV.NanoTDF.swift):addSignatureToNanoTDFrejects non-P256signatureCurverequests (CryptoHelperError.unsupportedCurve) and sets.secp256r1whennil.NanoTDF.swift,NanoTDFCollectionDecryptor.swift,KASService.swift): AddedHeader.verifyPolicyBinding(symmetricKey:)(constant-time GMAC and ECDSA verification) and enforced it inNanoTDF.getPayloadPlaintext(symmetricKey:),NanoTDF.getPlaintext(using:),NanoTDFCollectionDecryptor, andKASServicerewrap/key-access paths.KeyStore.swift,NanoTDF.swift,NanoTDFCollectionDecryptor.swift): Added v12 parsed-header key resolution inKeyStore.derivePayloadSymmetricKey(header:)(via uniqueResourceLocator.identifiermatch or single-key store) plus explicitkasPublicKey:overloads.CryptoHelper.swift): ReplacedCryptoSwift.GCMfor truncated tag sizes (64/96/104/112/120-bit) with constant-time CoreCryptoCommonCryptokCCModeCTR+CryptoKit.AES.GCM.seal+ constant-time tag prefix verification (zeroing plaintext on mismatch) and removedimport CryptoSwift.NanoTDF.swift): Added throwingPayload.serializedData()andEmbeddedPolicyBody.serializedData(); prevented non-throwingtoData()from trapping on oversized inputs.BinaryParser.swift): Rejected unknownidentifierTypevalues (4...15) and missing/truncatedPolicyKeyAccesson.embeddedEncryptedWithPolicyKeyAccess.BinaryParser.swift): Restored wire nibble0x0Fmapping toProtocolEnum.sharedResourceDirectory.KAS Discovery, Transport, Rewrap & KeyStore
KASRewrapClient.swift):rewrapNanoTDFsigns the request JWT withclientKeyPair.privateKey(ES256/ES384/ES512), setsalgorithmfromclientKeyPair.curve, supports P-256/P-384/P-521 in PEM encoding/decoding andunwrapKey, and encodesremote.toData()instead of"{}"for.remotepolicies.KASDiscovery.swift,KASService.swift,KASRewrapClient.swift): Added internalBoundedHTTPClient(disables redirects and caps buffered response bytes) forfetchWellKnown(1 MiB),KASService.rewrapKey(1 MiB, 30 s timeout), andURLSessionKASTransport(16 MiB default);fetchWellKnownandKASService.rewrapKeynow validate URLs viavalidateKasURL, andfetchWellKnownno longer leaks raw server error bodies.toDatamethods public #10 (KASDiscovery.swift): HardenedvalidateKasURLagainst case/trailing-dotlocalhost, URL userinfo, IPv6%zone IDs, non-canonical IPv4 literals (octal/hex/integer/shorthand — checked both beforeinet_ptonand 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).KeyStore.swift,KASService.swift): Added atomicKeyStore.popPrivateKey(forPublicKey:)used byKASService.processKeyAccessWithKeyIdentifieralongside deterministic RFC 4122 v5-style UUID generation fromSHA256(kasPublicKey).PublicKeyStore.swift):deserialize(from:)now parses and bounds-checks all keys locally before atomically replacing store contents.KASRewrapClient.swift):rewrapTDFrejects unknown or duplicate KAO IDs;rewrapAndUnwrapTDFSharesenforces"kao-"bounds and sorts numerically rather than lexicographically.KASDiscovery.swift):needsKasEndpointSynthesisreturnsfalsewhenever any endpoint URL is present (even ifkas.uriis empty), preventing silent override of explicit/hostilekasblocks.KeyStore.swift): Maintained accuratetotalBytesStoredacross all mutations and added overflow checks indeserialize(from:).KeyStore.swift,KASBulkRewrap.swift,KASService.swift): BackedStoredKeyPairwithSecureKeyPairStorage(memset_sondeinit), zeroed local private-key/DEK copies, and validated non-empty wrapped DEKs (> 28bytes) inKASBulkRewrap.Standard TDF, JSON/CBOR & Streaming
TDFCrypto.swift,TDFProcessor.swift,TDFJSONFormat.swift,TDFJSONContainer.swift,TDFCBORContainer.swift): AddedTDFCrypto.verifyPolicyBindingand sharedTDFDecryptor.decryptEncryptionInfoenforcing algorithm,symmetricKey.bitCount, integrity, and policy binding across Archive, JSON, and CBOR decryptors;TDFJSONEnvelope.parsevalidatestype/protocol/isEncrypted/length; JSON & CBOR decryptors explicitly reject multi-split manifests and non-.ecWrappedKAOs instead of silently readingkeyAccess[0].StreamingTDFCrypto.swift):decryptPayloadStreamingMultiSegmentanddecryptPayloadMultiSegmentFromMemorynow verify everysegment.hashand optionalrootSignature; streaming decryptor buffers into a temp file and copies tooutputHandleonly after all integrity checks pass.TDFArchive.swift,TDFBuilder.swift): Overflow-safepayloadSize(), capped initialData(capacity:), default512 MiBpayload limit inpayloadData/writePayload/TDFLoader, and overflow-checked chunk accumulation.TDFCBORFormat.swift): Added iterative stack-basedvalidateCBORStructure(_:maxDepth:maxItems:)prior toCBOR.decodeto block recursion stack-overflows and oversized-headerreadNOOM allocations.TDFCBORFormat.swift): MadehasMagicBytesstartIndex-safe.TDFFormatDetector.swift): FixeddetectWithDetails(from:)CBOR header check and boundeddetect(from url:)to a 4-byte header peek +10 MiBcap for speculative JSON detection.TDFCBORFormat.swift): Preserved PEMephemeralPublicKey,encryptedMetadata(key 6), andsid(key 10); enforced strict decoding of required fields/enums and kept absentencryptedSegmentSizeDefaultasnil.TDFProcessor.swift): Overflow-safechunkSize/segmentSizebounds and ceiling division.TDFCrypto.swift,TDFProcessor.swift): Multi-curve P-256/P-384/P-521unwrapSymmetricKeyWithECand secure zeroing of intermediate key copies and XOR key shares.Wire-Format & Compatibility Notes
ArkavoKit): Preserved all existing public API signatures via default parameter values and additive overloads..embeddedEncrypted):.embeddedEncryptednow encrypts with a domain-separated HKDF key (info = "nanotdf-embedded-policy") and appends a 16-byte GCM authentication tag toEmbeddedPolicyBody.body..remoteand.embeddedPlaintextwire formats are unchanged. Any Rust KAS or receiver decrypting.embeddedEncryptedpolicies must adopt the derived policy key + 16-byte GCM tag.TDFCrypto.verifyPolicyBindingaccepts both spec-formBase64(raw HMAC-SHA256)(32 bytes) and legacy Go SDKBase64(hex(HMAC-SHA256))(64 bytes) for backwards wire compatibility.KeyStore(NanoTDF concurrent #12): Keeps the v12 wire format intact (no KAS public key in header) and resolves parsed v12 headers viaResourceLocator.identifier/ single-key store or explicitkasPublicKey:overload.sidunder CBOR key10and preserves PEMephemeralPublicKeyas a UTF-8 string (decoding both byteString and utf8String).Verification
swiftformat --swiftversion 6.2 . && swiftformat --lint .— 0/80 files require formattingswift test --skip BenchmarkTests— 448 tests executed, 12 skipped, 0 failures (including 25 new regression tests inOpenTDFKitTests/SecurityAuditRegressionTests.swift)swift build -c release&swift build -c release --product OpenTDFKitCLI— clean builds, 0 new warningsec-wrappedinterop (scripts/interop/ec-wrapped):go vet ./...,go test ./..., andgo run . verifyagainstTDFKASEncryptorTests/testWriteSwiftFixtureForGo— OKReady for multi-model PR review.
Closes #69