envseal 0.3.11

Write-only secret vault with process-level access control — post-agent secret management
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
//! macOS Secure Enclave backend.
//!
//! On first use we generate a P-256 ECC keypair where the private key
//! is materialized **inside the Secure Enclave** (`kSecAttrTokenID =
//! kSecAttrTokenIDSecureEnclave`). The private key never enters the
//! application processor's address space — even kernel root cannot
//! extract it. The keypair is persisted in the keychain with a fixed
//! application tag so subsequent `envseal` runs find it again.
//!
//! Sealing:  ECIES (cofactor variable-IV X9.63 SHA-256 AES-GCM) with
//! the public key. Output is opaque DER-shaped blob produced by
//! `SecKeyCreateEncryptedData`.
//!
//! Unsealing: `SecKeyCreateDecryptedData` with the SEP-resident
//! private key. Returns `Err` if the keypair has been removed from
//! the keychain or if the blob was sealed by a different keypair.
//!
//! # Why direct FFI
//!
//! The wrapper crates do not currently expose the combination of
//! (SEP token + permanent + application-tag + ECIES) that we need.
//! Direct FFI to Security.framework / CoreFoundation keeps the
//! surface explicit and small.

#![cfg(target_os = "macos")]
#![allow(non_upper_case_globals)]

use std::os::raw::{c_int, c_long, c_void};
use std::ptr;

use crate::error::Error;

// `CString` is intentionally not used — we pass byte-string literals
// (already nul-terminated) directly via `as_ptr().cast()`.

/// Stable application tag in the keychain. Bumping the trailing
/// version string forces re-keying — old vault files become
/// undecryptable, which is what we want if the algorithm or
/// parameters change.
const APP_TAG: &[u8] = b"dev.santh.envseal.master.v1";

// --- CoreFoundation FFI -----------------------------------------------------

#[repr(C)]
struct __CFType(c_void);
type CFTypeRef = *const __CFType;
type CFAllocatorRef = CFTypeRef;
type CFDictionaryRef = CFTypeRef;
type CFMutableDictionaryRef = CFTypeRef;
type CFDataRef = CFTypeRef;
type CFStringRef = CFTypeRef;
type CFNumberRef = CFTypeRef;
type CFErrorRef = CFTypeRef;
type CFBooleanRef = CFTypeRef;
type CFIndex = c_long;
type Boolean = u8;
type OSStatus = i32;
type SecKeyRef = CFTypeRef;
type SecKeyAlgorithm = CFStringRef;

#[repr(C)]
struct CFDictionaryKeyCallBacks {
    _opaque: [u8; 0],
}
#[repr(C)]
struct CFDictionaryValueCallBacks {
    _opaque: [u8; 0],
}

#[link(name = "CoreFoundation", kind = "framework")]
extern "C" {
    static kCFAllocatorDefault: CFAllocatorRef;
    static kCFTypeDictionaryKeyCallBacks: CFDictionaryKeyCallBacks;
    static kCFTypeDictionaryValueCallBacks: CFDictionaryValueCallBacks;
    static kCFBooleanTrue: CFBooleanRef;

    fn CFRelease(cf: CFTypeRef);
    fn CFDictionaryCreateMutable(
        allocator: CFAllocatorRef,
        capacity: CFIndex,
        keyCallBacks: *const CFDictionaryKeyCallBacks,
        valueCallBacks: *const CFDictionaryValueCallBacks,
    ) -> CFMutableDictionaryRef;
    fn CFDictionaryAddValue(theDict: CFMutableDictionaryRef, key: CFTypeRef, value: CFTypeRef);
    fn CFDataCreate(allocator: CFAllocatorRef, bytes: *const u8, length: CFIndex) -> CFDataRef;
    fn CFDataGetLength(data: CFDataRef) -> CFIndex;
    fn CFDataGetBytePtr(data: CFDataRef) -> *const u8;
    fn CFNumberCreate(
        allocator: CFAllocatorRef,
        the_type: c_int,
        value_ptr: *const c_void,
    ) -> CFNumberRef;
    fn CFErrorCopyDescription(err: CFErrorRef) -> CFStringRef;
    fn CFStringGetCString(s: CFStringRef, buf: *mut u8, size: CFIndex, encoding: u32) -> Boolean;
}

const kCFNumberSInt32Type: c_int = 3;
const kCFStringEncodingUTF8: u32 = 0x0800_0100;

// --- Security.framework FFI -------------------------------------------------

#[link(name = "Security", kind = "framework")]
extern "C" {
    static kSecAttrKeyType: CFStringRef;
    static kSecAttrKeyTypeECSECPrimeRandom: CFStringRef;
    static kSecAttrKeySizeInBits: CFStringRef;
    static kSecAttrTokenID: CFStringRef;
    static kSecAttrTokenIDSecureEnclave: CFStringRef;
    static kSecAttrIsPermanent: CFStringRef;
    static kSecAttrApplicationTag: CFStringRef;
    static kSecPrivateKeyAttrs: CFStringRef;
    static kSecClass: CFStringRef;
    static kSecClassKey: CFStringRef;
    static kSecAttrKeyClass: CFStringRef;
    static kSecAttrKeyClassPrivate: CFStringRef;
    static kSecReturnRef: CFStringRef;
    static kSecMatchLimit: CFStringRef;
    static kSecMatchLimitOne: CFStringRef;
    static kSecKeyAlgorithmECIESEncryptionCofactorVariableIVX963SHA256AESGCM: SecKeyAlgorithm;

    fn SecKeyCreateRandomKey(parameters: CFDictionaryRef, error: *mut CFErrorRef) -> SecKeyRef;
    fn SecKeyCopyPublicKey(key: SecKeyRef) -> SecKeyRef;
    fn SecKeyCreateEncryptedData(
        key: SecKeyRef,
        algorithm: SecKeyAlgorithm,
        plaintext: CFDataRef,
        error: *mut CFErrorRef,
    ) -> CFDataRef;
    fn SecKeyCreateDecryptedData(
        key: SecKeyRef,
        algorithm: SecKeyAlgorithm,
        ciphertext: CFDataRef,
        error: *mut CFErrorRef,
    ) -> CFDataRef;
    fn SecItemCopyMatching(query: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
}

const errSecItemNotFound: OSStatus = -25300;

// --- RAII helpers -----------------------------------------------------------

struct CFOwned(CFTypeRef);
impl CFOwned {
    fn new(p: CFTypeRef) -> Option<Self> {
        if p.is_null() {
            None
        } else {
            Some(Self(p))
        }
    }
    fn as_ref(&self) -> CFTypeRef {
        self.0
    }
}
impl Drop for CFOwned {
    fn drop(&mut self) {
        if !self.0.is_null() {
            unsafe {
                CFRelease(self.0);
            }
        }
    }
}

fn cf_data(bytes: &[u8]) -> Option<CFOwned> {
    let len = CFIndex::try_from(bytes.len()).ok()?;
    let p = unsafe { CFDataCreate(kCFAllocatorDefault, bytes.as_ptr(), len) };
    CFOwned::new(p)
}

fn cf_number_i32(v: i32) -> Option<CFOwned> {
    let p = unsafe {
        CFNumberCreate(
            kCFAllocatorDefault,
            kCFNumberSInt32Type,
            std::ptr::from_ref(&v).cast::<c_void>(),
        )
    };
    CFOwned::new(p)
}

fn cf_dict_mutable() -> Option<CFOwned> {
    let p = unsafe {
        CFDictionaryCreateMutable(
            kCFAllocatorDefault,
            0,
            &kCFTypeDictionaryKeyCallBacks,
            &kCFTypeDictionaryValueCallBacks,
        )
    };
    CFOwned::new(p)
}

fn cf_error_string(err: CFErrorRef) -> String {
    if err.is_null() {
        return "<no error info>".to_string();
    }
    let desc = unsafe { CFErrorCopyDescription(err) };
    if desc.is_null() {
        return "<no description>".to_string();
    }
    let mut buf = [0u8; 1024];
    let buflen = CFIndex::try_from(buf.len()).unwrap_or(CFIndex::MAX);
    let ok = unsafe { CFStringGetCString(desc, buf.as_mut_ptr(), buflen, kCFStringEncodingUTF8) };
    unsafe {
        CFRelease(desc);
    }
    if ok == 0 {
        return "<encoding failed>".to_string();
    }
    let nul = buf.iter().position(|&b| b == 0).unwrap_or(buf.len());
    String::from_utf8_lossy(&buf[..nul]).into_owned()
}

// --- Keystore implementation ------------------------------------------------

/// Handle for the macOS Secure Enclave backend. Stateless — every
/// `seal` / `unseal` call looks up our application-tagged keypair
/// fresh, so the handle is just a phantom marker that proves
/// [`SecureEnclaveKeystore::try_new`] succeeded at process start.
pub struct SecureEnclaveKeystore;

impl SecureEnclaveKeystore {
    /// Probe for SEP availability by attempting to find or create our
    /// keypair. Returns `None` on hardware without an SEP (e.g. older
    /// Intel Macs without T2) or when keychain access is denied.
    pub fn try_new() -> Option<Self> {
        // Find-or-create: if creation succeeds even once, the SEP is
        // present. Subsequent runs find the existing key.
        match find_private_key() {
            Ok(Some(_)) => Some(Self),
            Ok(None) => match create_keypair() {
                Ok(()) => Some(Self),
                Err(_) => None,
            },
            Err(_) => None,
        }
    }

    /// Wrap `plaintext` under the SEP-resident public key using ECIES
    /// (cofactor variable-IV X9.63 SHA-256 AES-GCM). The result is an
    /// opaque blob that only the SEP private key on this device can
    /// decrypt.
    pub fn seal(&self, plaintext: &[u8]) -> Result<Vec<u8>, Error> {
        let priv_key = require_private_key()?;
        let pub_key = unsafe { SecKeyCopyPublicKey(priv_key.as_ref()) };
        let pub_key = CFOwned::new(pub_key)
            .ok_or_else(|| Error::CryptoFailure("SecKeyCopyPublicKey returned null".to_string()))?;

        let plaintext_cf = cf_data(plaintext)
            .ok_or_else(|| Error::CryptoFailure("CFDataCreate failed for plaintext".to_string()))?;

        let mut err: CFErrorRef = ptr::null();
        let cipher = unsafe {
            SecKeyCreateEncryptedData(
                pub_key.as_ref(),
                kSecKeyAlgorithmECIESEncryptionCofactorVariableIVX963SHA256AESGCM,
                plaintext_cf.as_ref(),
                &mut err,
            )
        };
        if cipher.is_null() {
            let msg = cf_error_string(err);
            if !err.is_null() {
                unsafe {
                    CFRelease(err);
                }
            }
            return Err(Error::CryptoFailure(format!(
                "SecKeyCreateEncryptedData failed: {msg}"
            )));
        }
        if !err.is_null() {
            unsafe {
                CFRelease(err);
            }
        }
        let cipher = CFOwned::new(cipher).ok_or_else(|| {
            Error::CryptoFailure("CFOwned::new returned null for non-null cipher".to_string())
        })?;

        Ok(copy_cfdata(cipher.as_ref()))
    }

    /// Recover plaintext from a blob previously produced by
    /// [`Self::seal`]. Fails if the SEP keypair has been removed,
    /// the blob was sealed by a different keypair, or the user
    /// declined the keychain-access prompt.
    pub fn unseal(&self, sealed: &[u8]) -> Result<Vec<u8>, Error> {
        let priv_key = require_private_key()?;
        let cipher_cf = cf_data(sealed).ok_or_else(|| {
            Error::CryptoFailure("CFDataCreate failed for ciphertext".to_string())
        })?;

        let mut err: CFErrorRef = ptr::null();
        let plain = unsafe {
            SecKeyCreateDecryptedData(
                priv_key.as_ref(),
                kSecKeyAlgorithmECIESEncryptionCofactorVariableIVX963SHA256AESGCM,
                cipher_cf.as_ref(),
                &mut err,
            )
        };
        if plain.is_null() {
            let msg = cf_error_string(err);
            if !err.is_null() {
                unsafe {
                    CFRelease(err);
                }
            }
            return Err(Error::CryptoFailure(format!(
                "SecKeyCreateDecryptedData failed (different SEP key, revoked, or corrupted blob): {msg}"
            )));
        }
        if !err.is_null() {
            unsafe {
                CFRelease(err);
            }
        }
        let plain = CFOwned::new(plain).ok_or_else(|| {
            Error::CryptoFailure("CFOwned::new returned null for non-null plain".to_string())
        })?;

        Ok(copy_cfdata(plain.as_ref()))
    }
}

fn copy_cfdata(data: CFDataRef) -> Vec<u8> {
    let len_signed = unsafe { CFDataGetLength(data) };
    let Ok(len) = usize::try_from(len_signed) else {
        // Negative length is an API contract violation by Security.framework
        // — return empty rather than wrapping or panicking.
        return Vec::new();
    };
    let ptr = unsafe { CFDataGetBytePtr(data) };
    if ptr.is_null() || len == 0 {
        return Vec::new();
    }
    let mut out = Vec::with_capacity(len);
    unsafe {
        std::ptr::copy_nonoverlapping(ptr, out.as_mut_ptr(), len);
        out.set_len(len);
    }
    out
}

fn require_private_key() -> Result<CFOwned, Error> {
    if let Some(k) = find_private_key()? {
        return Ok(k);
    }
    create_keypair()?;
    find_private_key()?.ok_or_else(|| {
        Error::CryptoFailure(
            "SEP keypair created but lookup failed immediately after — keychain inconsistency"
                .to_string(),
        )
    })
}

fn find_private_key() -> Result<Option<CFOwned>, Error> {
    let tag = cf_data(APP_TAG).ok_or_else(|| {
        Error::CryptoFailure("CFDataCreate failed for application tag".to_string())
    })?;
    let query = cf_dict_mutable()
        .ok_or_else(|| Error::CryptoFailure("CFDictionaryCreateMutable failed".to_string()))?;
    unsafe {
        CFDictionaryAddValue(query.as_ref(), kSecClass, kSecClassKey);
        CFDictionaryAddValue(query.as_ref(), kSecAttrKeyClass, kSecAttrKeyClassPrivate);
        CFDictionaryAddValue(query.as_ref(), kSecAttrApplicationTag, tag.as_ref());
        CFDictionaryAddValue(query.as_ref(), kSecMatchLimit, kSecMatchLimitOne);
        CFDictionaryAddValue(query.as_ref(), kSecReturnRef, kCFBooleanTrue);
    }
    let mut result: CFTypeRef = ptr::null();
    let status = unsafe { SecItemCopyMatching(query.as_ref(), &mut result) };
    match status {
        0 => Ok(CFOwned::new(result)),
        s if s == errSecItemNotFound => Ok(None),
        s => Err(Error::CryptoFailure(format!(
            "SecItemCopyMatching failed: OSStatus={s}"
        ))),
    }
}

fn create_keypair() -> Result<(), Error> {
    // Build the inner private-key attrs dict: { isPermanent: true,
    // applicationTag: APP_TAG }
    let priv_attrs = cf_dict_mutable().ok_or_else(|| {
        Error::CryptoFailure("CFDictionaryCreateMutable failed (priv_attrs)".to_string())
    })?;
    let tag = cf_data(APP_TAG).ok_or_else(|| {
        Error::CryptoFailure("CFDataCreate failed for application tag".to_string())
    })?;
    unsafe {
        CFDictionaryAddValue(priv_attrs.as_ref(), kSecAttrIsPermanent, kCFBooleanTrue);
        CFDictionaryAddValue(priv_attrs.as_ref(), kSecAttrApplicationTag, tag.as_ref());
    }

    // Outer params dict: { keyType: EC, keySize: 256, tokenID: SEP,
    // privateKeyAttrs: priv_attrs }
    let params = cf_dict_mutable().ok_or_else(|| {
        Error::CryptoFailure("CFDictionaryCreateMutable failed (params)".to_string())
    })?;
    let size = cf_number_i32(256)
        .ok_or_else(|| Error::CryptoFailure("CFNumberCreate failed".to_string()))?;
    unsafe {
        CFDictionaryAddValue(
            params.as_ref(),
            kSecAttrKeyType,
            kSecAttrKeyTypeECSECPrimeRandom,
        );
        CFDictionaryAddValue(params.as_ref(), kSecAttrKeySizeInBits, size.as_ref());
        CFDictionaryAddValue(
            params.as_ref(),
            kSecAttrTokenID,
            kSecAttrTokenIDSecureEnclave,
        );
        CFDictionaryAddValue(params.as_ref(), kSecPrivateKeyAttrs, priv_attrs.as_ref());
    }

    let mut err: CFErrorRef = ptr::null();
    let key = unsafe { SecKeyCreateRandomKey(params.as_ref(), &mut err) };
    if key.is_null() {
        let msg = cf_error_string(err);
        if !err.is_null() {
            unsafe {
                CFRelease(err);
            }
        }
        return Err(Error::CryptoFailure(format!(
            "SecKeyCreateRandomKey (Secure Enclave) failed: {msg}"
        )));
    }
    // The created key is now resident in the keychain. We don't need
    // to retain it here — `find_private_key` will return a fresh
    // reference on demand.
    unsafe {
        CFRelease(key);
    }
    if !err.is_null() {
        unsafe {
            CFRelease(err);
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Roundtrip on an actual macOS host with an SEP. CI's macos-latest
    /// runner has a virtualized SEP that supports this — falls through
    /// to a skipped test on hardware without one.
    #[test]
    fn seal_then_unseal_roundtrips_when_sep_present() {
        let Some(ks) = SecureEnclaveKeystore::try_new() else {
            eprintln!("SEP not available on this host — skipping");
            return;
        };
        let plaintext = b"the master key wrapped envelope";
        let sealed = ks.seal(plaintext).expect("SEP seal must succeed");
        assert_ne!(sealed.as_slice(), plaintext);
        let recovered = ks.unseal(&sealed).expect("SEP unseal must succeed");
        assert_eq!(recovered, plaintext);
    }

    #[test]
    fn unseal_rejects_corrupted_blob_when_sep_present() {
        let Some(ks) = SecureEnclaveKeystore::try_new() else {
            return;
        };
        let mut sealed = ks.seal(b"some payload").unwrap();
        let last = sealed.len() - 1;
        sealed[last] ^= 0x01;
        assert!(ks.unseal(&sealed).is_err());
    }
}