We are going to design a privacy-preserving cohort analytics system that combines differential privacy (DP) and secure enclaves (like Intel SGX or similar). The system must handle:
- Budget accounting for differential privacy (to ensure the total privacy budget is not exceeded)
- Attestation (to verify the integrity of the secure enclave and that it runs the correct code)
- Results delivery (to return the differentially private aggregated results to the analyst)
We assume a scenario where multiple data owners (cohorts) contribute data. The data is processed in a secure enclave to protect the raw data, and then DP is applied to the aggregated results to protect against information leakage from the output.
Steps:
-
System Setup:
- Trusted Setup: Generate keys for the secure enclave and for attestation (if using a remote attestation service).
- Differential Privacy: Choose a DP mechanism (e.g., Laplace, Gaussian) and define the sensitivity of the queries.
-
Data Ingestion:
- Each data owner sends their data to the secure enclave (or the enclave fetches from a secure location). The data must be encrypted in transit and at rest (but the enclave will decrypt it inside).
-
Query Processing:
- The analyst submits a query (or a set of queries) to the enclave.
- The enclave checks the current DP budget. If the query's privacy cost (epsilon) would exceed the budget, it rejects.
- The enclave executes the query on the aggregated data (or on individual data and then aggregates) to compute the true result.
- The enclave then adds noise according to the DP mechanism, using the remaining budget and the query's sensitivity.
-
Budget Accounting:
- We need to track the total epsilon spent. For multiple queries, we can use composition theorems (e.g., advanced composition) to compute the total privacy loss.
- Alternatively, we can allocate a fixed epsilon per query and ensure the sum does not exceed the total budget.
-
Attestation:
- Before the data is sent, the data owner (or the system) must verify the enclave's integrity and that it is running the correct code (via remote attestation).
- The analyst might also want to attest the enclave before submitting the query to ensure the code is correct and the budget accounting is trusted.
-
Results Delivery:
- The noisy result is sent to the analyst. The enclave must sign the result so the analyst can verify it came from the attested enclave and that the DP noise was applied correctly (by verifying the signature and the enclave's identity).
-
Audit:
- The system should have an audit log (inside the enclave) that records queries, budget usage, and noise added. This log can be attested and provided to an auditor if needed.
Implementation Outline:
Let's break down the components:
-
Enclave Application:
- Written in a language supported by the enclave (e.g., C++ for Intel SGX).
- Contains:
- Data structures for the cohort data (which may be large, so we might need to store it in encrypted form outside and decrypt on the fly).
- DP mechanism implementation (with fixed sensitivity and noise distribution).
- Budget manager (tracking epsilon and delta for each query, and the total).
- Query executor (for a set of pre-defined queries or a limited query language).
- Attestation key and procedures (for generating quotes and verifying them).
-
Data Owner Client:
- A tool for data owners to send data to the enclave after attesting it.
- Might also be used to set the DP budget (or the budget is set by the system administrator).
-
Analyst Client:
- Submits queries to the enclave (after attesting the enclave).
- Receives and verifies the signed result.
-
Attestation Service (optional):
- Could be a service that provides the enclave's quote (from the hardware) and verifies it.
-
Audit Service:
- Can request the enclave's audit log (after attestation) to check the budget usage and queries.
Steps in Detail:
A. Initialization:
- Generate a key pair for the enclave (for signing results and audit logs). The private key is sealed (or stored) in the enclave and never leaves.
- The public key can be used by analysts and auditors to verify signatures.
B. Data Ingestion:
- Data owner:
1. Obtains the enclave's public key and quote (via attestation) to verify the enclave.
2. Encrypts the data with a symmetric key (which is then encrypted with the enclave's public key, or uses a key exchange).
3. Sends the encrypted data to the enclave.
- Enclave:
1. Verifies the data owner's identity (if needed, but we assume the data owner is trusted and the data is sent over a secure channel).
2. Decrypts the data and stores it in an encrypted form in the enclave's memory (or in a persistent encrypted storage outside, but decrypted only in the enclave).
C. Query Submission:
- Analyst:
1. Attests the enclave (gets a quote) and verifies the enclave's identity and that it is running the expected code.
2. Submits a query (with a specified epsilon for that query) to the enclave.
- Enclave:
1. Checks if the query's epsilon (and delta, if using Gaussian) plus the already used budget (with composition) exceeds the total budget.
2. If not, it executes the query on the data (which is decrypted in the enclave) to get the true result.
3. Applies the DP noise (with the specified epsilon and delta) to the true result.
4. Updates the budget (logging the query and the epsilon used).
5. Signs the noisy result with the enclave's private key and sends it to the analyst.
D. Audit:
- Auditor can request the audit log (signed by the enclave) to verify the budget usage and that all queries were processed correctly.
Implementation Challenges:
-
Composition: We must track the total epsilon and delta spent. For a sequence of queries, we can use the advanced composition theorem. However, note that the composition theorem depends on the type of queries (e.g., non-adaptive vs. adaptive). We assume we are allowing non-adaptive queries (queries are fixed in advance) or we use a conservative composition (like the ones for adaptive queries). Alternatively, we can use the method of grouping queries and using a fixed total budget for a group.
-
Sensitivity: The sensitivity of each query must be known. We assume we have a fixed set of queries with known sensitivity (e.g., count, sum, average with known bounds). For more complex queries, we need to compute the sensitivity.
-
Enclave Memory: The data might not fit in the enclave's memory. We need to design a way to process data in chunks (e.g., using an external database that the enclave can query in a trusted manner, or by encrypting the data and decrypting chunks at a time). However, the enclave must see the entire dataset to compute the global sensitivity? Not necessarily: for some queries we can compute the global sensitivity from the data (with clipping) but that might require two passes. Alternatively, we can use local differential privacy (but that's different). We assume we have bounds on the data (e.g., each record is in [0,1]) so the sensitivity is fixed.
-
Attestation: We need to ensure that the enclave is running the correct code. This is done by the hardware (e.g., Intel SGX) and we can get a quote that includes a hash of the code. The analyst must have a way to verify the quote (e.g., using Intel's attestation service or a predefined public key).
-
Network Security: All communications must be encrypted (TLS) and the enclave must authenticate the data owner and analyst (or we assume they are on a secure network and the enclave is the only one that matters).
-
Enclave Code Update: If we update the code, we need to re-attest and update the trusted hash.
Given the complexity, we will outline a simplified version:
Let's assume:
-
We have a fixed set of queries (e.g., count, sum, average) and each query has a known sensitivity (e.g., for count, sensitivity=1; for sum with data in [0,1], sensitivity=1; for average, we can compute from count and sum or set sensitivity to 1/|dataset|? Actually, average sensitivity depends on the count and the range. We can set a fixed bound on the average by clippinndividual values).
-
We use the Laplace mechanism for its simplicity (epsilon-DP, delta=0). Then we don't have to track delta.
-
We have a total budget E (epsilon). We allow the analyst to specify the epsilon for each query, but the enclave will check that the sum of epsilons does not exceed E.
-
We assume non-adaptive queries (the analyst decides the sequence of queries in advance) so we can just sum the epsilons.
-
Alternatively, we can use the advanced composition for adaptive queries, but that is more complex. We'll stick to non-adaptive for simplicity.
Steps for the enclave:
-
State:
total_epsilon_used = 0
total_epsilon_budget = E (set by administrator at initialization)
data: the dataset (in memory, decrypted, but we assume the data is not too large so it fits in the enclave memory; if not, we need to encrypt it on disk and decrypt in chunks, but then the enclave must see the entire dataset for global sensitivity? We assume we have bounds and can clip without seeing the entire dataset? Actually, for sum and count, we don't need to clip. For average, we might compute the count and sum and then divide. But the sensitivity of average is 2/|dataset| if we clip each value to [0,1]. So we need to know the dataset size? Yes, but that's okay.
-
We'll implement:
query_count(epsilon)
query_sum(epsilon) [assuming each value in [0,1]]
query_average(epsilon) [using count and sum, then adding noise appropriately? Actually, we can compute average as sum/count. But note: the sensitivity of average is not the same as sum and count. We can do:
true_count = count()
true_sum = sum()
true_average = true_sum / true_count
Then we add noise to the numerator and denominator? That's not standard. Alternatively, we can release the count and sum with appropriate noise and then the analyst computes the average. But then the average does not satisfy DP because the division is not DP. We need to use a mechanism that directly releases the average with sensitivity? Or use the subset mechanism? Actually, we can clip each value to [0,1] and then the average has sensitivity 2/n? But note: if we change one record, the average changes by at most 1/n (if the record was 0 and becomes 1, or vice versa) but if we have bounds [a,b] then sensitivity is (b-a)/n. However, if we clip each value to [0,1] then the worst-case change is 1/n? Actually, if we clip, then changing one record might change the average by at most 1/n? Wait: if we have two datasets that differ in one record, the maximum change in the average is the maximum difference between two values (which is 1) divided by n? Actually, no: if we clip each value to [0,1], then the maximum change in one record is 1 (from 0 to 1). So the average changes by at most 1/n. But wait, the sensitivity of the average function (with domain [0,1]^n) is 1/n. However, if we use the Laplace mechanism for average, we scale the noise by sensitivity/epsilon. So we can compute the true average (with clipped values) and then add noise from Laplace(1/(n*epsilon)).
But note: if we clip, we are changing the data. We must do the same clipping for both datasets. Alternatively, we can have a function that returns the average of the clipped values.
Alternatively, we can avoid releasing average and instead release count and sum and let the analyst compute the average. But then the analyst can compute the average of the noisy count and noisy sum? That would not be the same as releasing the average with noise added directly. And it might not satisfy DP. So we must release the average with the correct mechanism.
We can do:
Let f(D) = (1/n) * sum_{i=1 to n} clip(x_i, 0, 1)
The sensitivity of f is 1/n (because changing one x_i can change the sum by at most 1, so the average by 1/n).
-
Results Delivery:
- The enclave signs the noisy result (and the query id, and maybe the query type) and sends it to the analyst.
- The analyst verifies the signature and the enclave's identity (via the attestation quote).
-
Attestation Flow:
- Data owner and analyst both perform remote attestation of the enclave before sending data or query.
- They get a quote (which includes the hash of the enclave code and the public key of the enclave? The quote is signed by the hardware).
- They verify the quote with the hardware manufacturer's root of trust (or a proxy).
- Then they extract the enclave's public key from the quote (or we have a separate key exchange).
-
Budget Management:
- We set a total budget E at initialization.
- For each query, we require the analyst to specify the epsilon they want to use (or the enclave assigns one? We let the analyst specify, but the enclave checks that the sum of epsilons (with composition) does not exceed E.
Since we are using Laplace (pure DP) and non-adaptive queries, we can just sum the epsilons.
However, if we allow adaptive queries, we must use composition. But note: the analyst can send queries sequentially and the enclave's data changes? Actually, the data is fixed. The analyst can send multiple queries on the same data. Then the composition is the sum of epsilons for pure DP.
But if we use Gaussian (approximate DP) then we have to track delta as well.
We'll stick to Laplace for simplicity (epsilon-DP, delta=0).
-
Code Structure:
Enclave (in C++ for SGX):
class Enclave {
private:
double total_budget;
double used_budget;
Dataset data; // we assume the data is loaded and stored in plaintext in the enclave's memory.
public:
// Called by the data owner to load data (after attestation and secure channel)
void load_data(encrypted_data) {
// decrypt and store in data
}
// Called by the analyst to run a query
QueryResult run_query(Query query) {
// Check budget: if query.epsilon + used_budget > total_budget, reject.
// Execute the query on the data to get true_result.
// Compute noise: scale = sensitivity / query.epsilon
// For count: sensitivity = 1
// For sum (clipped to [0,1]): sensitivity = 1
// For average: sensitivity = 1/n (where n is the number of records)
// Add noise to true_result.
// Update used_budget += query.epsilon.
// Log: query type, epsilon, noisy_result, remaining_budget.
// Sign the noisy_result (and query id, etc.) and return.
}
// For audit: return the audit log (signed by the enclave)
AuditLog get_audit_log() {
// return the log (signed by the enclave's private key)
}
};
System Architecture Overview
┌─────────────────┐ ┌─────────────────────────────────────────────┐
│ Data Owners │ │ Trusted Execution │
│ (Cohort Members)│ │ Environment │
└────────┬────────┘ ├──────────────┬──────────────┬───────────┤
│ │ Enclave │ Attestation │ DP │
│ (1) Raw │ (Secure │ Service │ Engine │
├─────────────▶│ Storage) │ (Quote │ (Laplace│
│ │ │ Gen/Verify) │ /Gaussian)│
│ └──────┬───────┴───────┬───────┴──────────┘
│ │ │
┌────────▼────────┐ ┌──────▼──────┐ ┌────▼─────┐
│ Data │ │ Query │ │ Budget │
│ Ingestion │ │ Processor │ │ Manager│
│ (Encrypted) │ │ │ │ │
└─────────────────┘ └─────────────┘ └──────────┘
│ │
│ ┌──────▼──────┐
│ │ Result │
└──────────────▶│ Formatter │
│ & Signer │
└──────┬──────┘
│
┌──────▼──────┐
│ Analyst │
│ (Client) │
└─────────────┘
Core Components
1. Secure Enclave (Trusted Execution Environment)
# Pseudocode for enclave entry points
class SecureAnalyticsEnclave:
def __init__(self):
self.dp_budget = DPBudgetManager(total_epsilon=1.0, total_delta=1e-5)
self.encrypted_data_store = EncryptedDataStore()
self.attestation_key = generate_enclave_keypair()
self.audit_log = SecureAuditLog()
# ECALL (Enclave Call)
def ingest_data(self, encrypted_shards: List[bytes],
data_owner_attestation: Quote) -> IngestResult:
"""Securely ingest encrypted data from verified data owners"""
verify_attestation(data_owner_attestation, required_quote_type="DATA_OWNER")
decrypt_and_store(encrypted_shards) # Never decrypt outside enclave
self.audit_log.log("DATA_INGESTED",
metadata={"owners": count_owners()})
return IngestResult(success=True)
# ECALL
def execute_query(self, query: Query,
requested_epsilon: float) -> QueryResult:
"""Execute DP query with budget checking"""
# 1. Check budget
remaining = self.dp_budget.consume(requested_epsilon)
if not remaining.allowed:
raise BudgetExceededError(f"Budget exceeded. Remaining: {remaining.epsilon}")
# 2. Verify query validity (sensitivity analysis)
sensitivity = self.compute_sensitivity(query)
# 3. Execute query on decrypted data (in enclave)
true_result = self.process_query(query)
# 4. Apply DP noise
noisy_result = self.dp_engine.add_noise(
true_result,
sensitivity,
requested_epsilon,
self.dp_budget.remaining_delta
)
# 5. Update usage & audit
self.dp_budget.commit(requested_epsilon)
self.audit_log.log("QUERY_EXECUTED", {
"query_hash": hash(query),
"epsilon": requested_epsilon,
"sensitivity": sensitivity,
"timestamp": current_time()
})
return QueryResult(
result=noisy_result,
privacy_used=requested_epsilon,
query_signature=self.sign_result(noisy_result, query)
)
2. Differential Privacy Engine (Hybrid Approach)
class HybridDPEngine:
"""Combines local and central DP for optimized privacy/utility"""
def __init__(self):
self.local_dp = LocalDPMechanism() # For pre-processing
self.central_dp = CentralDPMechanism() # For final aggregation
def add_noise(self, true_value: float, sensitivity: float,
epsilon: float, delta: float) -> float:
"""Hybrid noise addition based on query type"""
if self.is_high_sensitivity_query(true_value):
# Use Gaussian for better utility with small delta
noise = self.central_dp.gaussian_mechanism(
sensitivity, epsilon, delta
)
else:
# Use Laplace for pure ε-DP (δ=0)
noise = self.central_dp.laplace_mechanism(
sensitivity, epsilon
)
# Apply local DP pre-processing if needed
if self.requires_local_dp(true_value):
preprocessed = self.local_dp.preprocess(true_value)
return preprocessed + noise
return true_value + noise
3. Budget Accounting System
class DPTaggedBudget:
"""Advanced budget tracking with composition theorems"""
def __init__(self, total_epsilon: float, total_delta: float):
self.epsilon_ledger = EpsilonLedger(total_epsilon)
self.delta_ledger = DeltaLedger(total_delta)
self.composition = AdvancedComposition() # zCDP or RDP accounting
def consume(self, query_epsilon: float,
query_type: QueryType = QueryType.STANDARD) -> BudgetStatus:
"""Check if query can proceed with remaining budget"""
# Apply composition based on query adaptivity
if query_type == QueryType.ADAPTIVE:
composed_epsilon = self.composition.adaptive_compose(
self.epsilon_ledger.used,
query_epsilon
)
else:
composed_epsilon = self.epsilon_ledger.used + query_epsilon
if composed_epsilon > self.epsilon_ledger.total:
return BudgetStatus(allowed=False,
remaining_epsilon=0,
message="ε budget exceeded")
# Check delta budget for approximate DP queries
if query_type == QueryType.APPROXIMATE:
if self.delta_ledger.used + self.estimated_delta(query_epsilon) > \
self.delta_ledger.total:
return BudgetStatus(allowed=False,
remaining_epsilon=0,
message="δ budget exceeded")
return BudgetStatus(
allowed=True,
remaining_epsilon=self.epsilon_ledger.total - composed_epsilon,
remaining_delta=self.delta_ledger.total - self.delta_ledger.used
)
def commit(self, epsilon: float, delta: float = 0.0):
"""Commit budget after successful query execution"""
self.epsilon_ledger.commit(epsilon)
if delta > 0:
self.delta_ledger.commit(delta)
4. Attestation Service
class AttestationService:
"""Hardware-rooted attestation for enclave verification"""
def generate_quote(self, enclave_id: str,
user_type: UserType) -> bytes:
"""Generate SGX/AMD-SEV quote with custom report data"""
report_data = {
"enclave_id": enclave_id,
"user_type": user_type.value,
"timestamp": current_time(),
"code_hash": self.get_enclave_hash(),
"public_key": self.attestation_key.public_bytes()
}
quote = sgx_attestation.generate_quote(
report_data=serialize(report_data),
sign=False # Hardware signs
)
return quote
def verify_quote(self, quote: bytes,
expected_user_type: UserType) -> VerificationResult:
"""Verify enclave integrity and user permissions"""
# 1. Verify hardware signature
if not sgx_attestation.verify_quote(quote):
return VerificationResult(valid=False, reason="Invalid hardware signature")
# 2. Parse and verify report data
report_data = sgx_attestation.parse_quote(quote)
if report_data["user_type"] != expected_user_type:
return VerificationResult(valid=False, reason="User type mismatch")
# 3. Check code hash against approved baselines
if report_data["code_hash"] not in self.approved_hashes:
return VerificationResult(valid=False, reason="Unapproved code version")
return VerificationResult(valid=True, public_key=report_data["public_key"])
5. Results Delivery with Cryptographic Proofs
class ResultDeliveryService:
"""Deliver results with verifiable DP guarantees"""
def package_result(self, result: DPResult, query: Query,
proof: DPProof) -> SignedResult:
"""Create verifiable result package"""
package = {
"result": result.value,
"query_hash": hash(query),
"epsilon_used": result.epsilon,
"delta_used": result.delta,
"mechanism": result.mechanism,
"timestamp": current_time(),
"enclave_id": self.enclave_id,
"proof": proof.to_json() # Zero-knowledge proof of DP
}
# Sign with enclave's attestation key
signature = self.enclave_key.sign(serialize(package))
return SignedResult(
package=package,
signature=signature,
verification_key=self.attestation_key.public_key
)
def verify_result(self, signed_result: SignedResult) -> VerificationResult:
"""Client-side verification of result authenticity and DP"""
# 1. Verify enclave signature
if not verify_signature(
signed_result.package,
signed_result.signature,
signed_result.verification_key
):
return VerificationResult(valid=False, reason="Invalid signature")
# 2. Check proof of DP application
if not self.dp_proof_verifier.verify(
signed_result.package["proof"],
signed_result.package["query_hash"],
signed_result.package["epsilon_used"]
):
return VerificationResult(valid=False, reason="DP proof invalid")
return VerificationResult(valid=True)
Data Flow & Protocols
Phase 1: Setup & Attestation
1. System Initialization:
- Deploy enclave with approved code hash
- Generate attestation key pair (stored in enclave)
- Configure DP budget pool (ε_total, δ_total)
2. Data Owner Onboarding:
- Verify enclave quote (hardware + code)
- Establish secure channel (TLS + enclave public key)
- Register public key for data contribution
Phase 2: Secure Data Ingestion
For each data owner:
1. Generate local data encryption key (DEK)
2. Encrypt data with DEK
3. Encrypt DEK with enclave's public key (from attestation)
4. Send encrypted shards + enclave attestation quote
5. Enclave verifies quote, decrypts DEK, stores encrypted data
Phase 3: Query Execution
# Analyst workflow
def analyst_query_workflow(query: Query, epsilon: float):
# 1. Get fresh enclave attestation
quote = get_enclave_quote()
assert verify_quote(quote, expected_user_type="ANALYST")
# 2. Open secure channel to enclave
session_key = key_exchange(quote.public_key)
# 3. Submit query with epsilon request
encrypted_query = encrypt(query, session_key)
result = send_to_enclave(encrypted_query, epsilon)
# 4. Verify result package
assert verify_result(result) # Checks signature + DP proof
return decrypt_result(result.result, session_key)
Phase 4: Audit & Monitoring
Continuous:
- Real-time budget monitoring dashboard
- Audit log (sealed storage in enclave):
* All data ingestions (owners, timestamps, sizes)
* All queries (hash, ε, δ, sensitivity, timestamp)
* Attestation events
* Budget consumption
Periodic:
- Auditor requests signed audit log from enclave
- Verify enclave signature and quote validity
- Check budget compliance
- Validate DP proofs on sampled results
Security & Privacy Guarantees
Differential Privacy
- ε-DP / (ε,δ)-DP via hybrid mechanisms
- Composition: Advanced composition theorems for adaptive queries
- Privacy Budget: Hard limit enforced by enclave (cannot be bypassed)
Secure Enclave Guarantees
- Confidentiality: Data never decrypted outside enclave
- Integrity: Code execution verified via attestation
- Freshness: Quote includes timestamp/nonce
- Isolation: Enclave memory encrypted, CPU registers protected
Cryptographic Guarantees
- Authenticity: All results signed by enclave key
- Verifiability: Zero-knowledge proofs of DP application
- Non-repudiation: Audit log sealed with monotonic counters
Implementation Considerations
Technology Stack
- TEE: Intel SGX / AMD SEV-SNP / AWS Nitro Enclaves
- Language: C++/Rust for enclave, Python/Go for outer services
- Crypto: libsodium, OpenSSL, Microsoft QFE (for ZKP)
- Attestation: RA-TLS, DCAP (for SGX)
- Storage: Encrypted databases (SQLite/PostgreSQL with TDE)
Performance Optimizations
- Batch Processing: Group queries to amortize attestation overhead
- Caching: Cache frequent query results (with DP timestamping)
- Parallelism: Multiple enclave threads for query processing
- Compression: Compress encrypted data before ingestion
Deployment Topology
Option A (Single Enclave):
- Simpler, suitable for <10M records
- Limited by enclave memory (128MB-2GB)
Option B (Enclave Cluster):
- Sharded data across multiple enclaves