keyring-manager 0.10.0

Cross-platform library for managing passwords
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
// iOS keychain backend. Items are generic passwords with an empty kSecAttrService and the whole
// (application, service, key) triple tab-joined into kSecAttrAccount.
//
// Accessibility is an invariant, not a write-time option: every item this backend stores is
// kSecAttrAccessibleAfterFirstUnlock, and an item found with any other class is updated in place.
// A read or a write is the only moment the backend can prove the class key is available, so that is
// where the update is issued.
//
// Not the ThisDeviceOnly variant of that class. An app's files come back from an encrypted device
// backup and a ThisDeviceOnly item does not, which leaves the restored device holding ciphertext
// whose key exists nowhere. What guards the item inside a backup is the backup's own encryption,
// which is also all that guards the data the item decrypts.
//
// Absence is a claim this backend only makes when it can prove it. A device that cannot decrypt an
// item can answer a lookup for it with errSecItemNotFound, so NoPasswordFound is reported only
// after a probe write shows the strictest protection class is available; otherwise the answer is
// Locked. A caller that reprovisions on absence would otherwise overwrite a secret it merely could
// not read.
//
// Queries do not pin kSecAttrAccessGroup, so they match every group the app can reach. Two items
// with one account name in different groups are a conflict a read refuses rather than resolves.
//
// Nothing here deletes or re-adds an item, and the update dictionaries are disjoint: a data update
// never carries kSecAttrAccessible and an accessibility update never carries kSecValueData. No
// interrupted or concurrent update can alter, stale, or lose the secret.

use crate::error::{KeyringError, Result};
use crate::*;
use core_foundation::array::CFArray;
use core_foundation::base::{CFGetTypeID, CFRelease, CFType, CFTypeRef, TCFType};
use core_foundation::boolean::CFBoolean;
use core_foundation::data::CFData;
use core_foundation::dictionary::CFDictionary;
use core_foundation::string::{CFString, CFStringRef};
use security_framework::base::Error as SfError;
use security_framework::item::{ItemClass, ItemSearchOptions, Limit};
use security_framework::passwords::delete_generic_password;
use security_framework_sys::access_control::{
    kSecAttrAccessibleAfterFirstUnlock, kSecAttrAccessibleWhenUnlocked,
};
use security_framework_sys::base::{errSecDuplicateItem, errSecItemNotFound};
use security_framework_sys::item::{
    kSecAttrAccount, kSecAttrService, kSecClass, kSecClassGenericPassword, kSecMatchLimit,
    kSecMatchLimitAll, kSecReturnAttributes, kSecReturnData, kSecValueData,
};
use security_framework_sys::keychain_item::{SecItemAdd, SecItemCopyMatching, SecItemUpdate};
use std::sync::atomic::{AtomicU64, Ordering};

pub type OSStatus = i32;

// security-framework-sys exports the accessibility values but not this key
#[allow(non_upper_case_globals)]
#[link(name = "Security", kind = "framework")]
extern "C" {
    static kSecAttrAccessible: CFStringRef;
}

#[allow(non_upper_case_globals)]
const errSecInteractionNotAllowed: OSStatus = -25308;

static PROMOTIONS: AtomicU64 = AtomicU64::new(0);

/// Accessibility updates issued since the process started. A promoted item must stop being
/// promoted, so the tests watch this rather than the log.
#[cfg(feature = "keyring_manager_ios_tests")]
pub(crate) fn promotion_count() -> u64 {
    PROMOTIONS.load(Ordering::Relaxed)
}

#[allow(non_upper_case_globals)]
fn map_status(status: OSStatus) -> KeyringError {
    match status {
        errSecItemNotFound => KeyringError::NoPasswordFound,
        errSecInteractionNotAllowed => KeyringError::Locked,
        status => KeyringError::from(status),
    }
}

#[inline(always)]
fn map_keyring_error(err: SfError) -> KeyringError {
    map_status(err.code())
}

fn cf_static(key: CFStringRef) -> CFString {
    unsafe { CFString::wrap_under_get_rule(key) }
}

// must stay byte-identical to what PasswordOptions::new_generic_password("", account) builds, since
// delete_value and list_keys still match items through security-framework's own query
fn item_query(account_name: &str) -> Vec<(CFString, CFType)> {
    vec![
        (
            cf_static(unsafe { kSecClass }),
            cf_static(unsafe { kSecClassGenericPassword }).into_CFType(),
        ),
        (
            cf_static(unsafe { kSecAttrService }),
            CFString::from("").into_CFType(),
        ),
        (
            cf_static(unsafe { kSecAttrAccount }),
            CFString::from(account_name).into_CFType(),
        ),
    ]
}

fn target_accessibility() -> CFString {
    cf_static(unsafe { kSecAttrAccessibleAfterFirstUnlock })
}

fn accessible_pair(class: CFString) -> (CFString, CFType) {
    (
        cf_static(unsafe { kSecAttrAccessible }),
        class.into_CFType(),
    )
}

fn data_pair(value: &[u8]) -> (CFString, CFType) {
    (
        cf_static(unsafe { kSecValueData }),
        CFData::from_buffer(value).into_CFType(),
    )
}

fn flag_pair(key: CFStringRef) -> (CFString, CFType) {
    (cf_static(key), CFBoolean::from(true).into_CFType())
}

/// `None` when securityd did not return the attribute, which is evidence neither way.
fn accessibility_is_current(item: &CFDictionary<CFType, CFType>) -> Option<bool> {
    item.find(cf_static(unsafe { kSecAttrAccessible }).into_CFType())
        .and_then(|v| v.downcast::<CFString>())
        .map(|v| v == target_accessibility())
}

fn all_current(items: &[CFDictionary<CFType, CFType>]) -> Option<bool> {
    let mut result = Some(true);
    for item in items {
        match accessibility_is_current(item) {
            Some(false) => return Some(false),
            Some(true) => {}
            None => result = None,
        }
    }
    result
}

fn item_data(item: &CFDictionary<CFType, CFType>) -> Result<Vec<u8>> {
    item.find(cf_static(unsafe { kSecValueData }).into_CFType())
        .and_then(|v| v.downcast::<CFData>())
        .map(|v| v.bytes().to_vec())
        .ok_or_else(|| map_to_generic("keychain item has no data"))
}

/// Every match for the query, with whatever `kSecReturn*` flags the caller asked for.
fn copy_all(mut query: Vec<(CFString, CFType)>) -> Result<Vec<CFDictionary<CFType, CFType>>> {
    query.push((
        cf_static(unsafe { kSecMatchLimit }),
        cf_static(unsafe { kSecMatchLimitAll }).into_CFType(),
    ));
    let params = CFDictionary::from_CFType_pairs(&query);
    let mut ret: CFTypeRef = std::ptr::null();
    let status = unsafe { SecItemCopyMatching(params.as_concrete_TypeRef(), &mut ret) };
    if status != 0 {
        return Err(map_status(status));
    }
    if ret.is_null() {
        return Ok(Vec::new());
    }
    // a limit of all answers with an array; the cast below is only sound for one
    if unsafe { CFGetTypeID(ret) } != CFArray::<CFType>::type_id() {
        unsafe { CFRelease(ret) };
        return Err(map_to_generic(
            "keychain returned an unexpected result type",
        ));
    }
    let array: CFArray<CFType> = unsafe { CFArray::wrap_under_create_rule(ret as _) };

    let mut items = Vec::with_capacity(array.len() as usize);
    for entry in array.iter() {
        if !entry.instance_of::<CFDictionary<CFType, CFType>>() {
            return Err(map_to_generic("keychain returned an unexpected item type"));
        }
        items.push(unsafe { CFDictionary::wrap_under_get_rule(entry.as_CFTypeRef() as _) });
    }
    Ok(items)
}

fn copy_attributes(account_name: &str) -> Result<Vec<CFDictionary<CFType, CFType>>> {
    let mut query = item_query(account_name);
    query.push(flag_pair(unsafe { kSecReturnAttributes }));
    copy_all(query)
}

/// A probe write, the only way to tell "no such item" from "cannot decrypt the item". Probing uses
/// the strictest class: an item this backend has not promoted yet is still
/// kSecAttrAccessibleWhenUnlocked, whose key exists only while the device is unlocked.
fn keychain_unlocked() -> bool {
    let account = format!("\u{1}keyring-manager-probe\t{}", probe_nonce());
    let mut attrs = item_query(&account);
    attrs.push(accessible_pair(cf_static(unsafe {
        kSecAttrAccessibleWhenUnlocked
    })));
    attrs.push(data_pair(&[0u8]));
    let params = CFDictionary::from_CFType_pairs(&attrs);
    let status = unsafe { SecItemAdd(params.as_concrete_TypeRef(), std::ptr::null_mut()) };
    if status == 0 {
        let _ = delete_generic_password("", &account);
        return true;
    }
    if status == errSecDuplicateItem {
        // a probe stranded by an earlier crash; clear it so the next one can decide
        let _ = delete_generic_password("", &account);
    }
    warn!("keychain probe failed, absence is unproven: {}", status);
    false
}

fn probe_nonce() -> u64 {
    static COUNTER: AtomicU64 = AtomicU64::new(0);
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_nanos() as u64)
        .unwrap_or(0);
    nanos ^ (COUNTER.fetch_add(1, Ordering::Relaxed) << 40) ^ ((std::process::id() as u64) << 20)
}

fn absence_or_locked() -> KeyringError {
    if keychain_unlocked() {
        KeyringError::NoPasswordFound
    } else {
        KeyringError::Locked
    }
}

/// Bring existing items to the target accessibility. Best effort: the caller has already completed
/// its own operation, and a failure leaves the item exactly as it was.
pub(crate) fn promote_accessibility(account_name: &str) -> bool {
    PROMOTIONS.fetch_add(1, Ordering::Relaxed);
    let query = CFDictionary::from_CFType_pairs(&item_query(account_name));
    let update = CFDictionary::from_CFType_pairs(&[accessible_pair(target_accessibility())]);
    let status =
        unsafe { SecItemUpdate(query.as_concrete_TypeRef(), update.as_concrete_TypeRef()) };
    if status != 0 {
        warn!("keychain accessibility update failed: {}", status);
        return false;
    }
    match copy_attributes(account_name).map(|items| all_current(&items)) {
        Ok(Some(true)) => {
            info!("keychain accessibility updated");
            true
        }
        Ok(Some(false)) => {
            error!("keychain accepted an accessibility update that did not take; the item stays unreadable while locked");
            false
        }
        Ok(None) | Err(_) => {
            warn!("keychain accessibility update could not be verified");
            false
        }
    }
}

pub struct IosKeyringManager {
    application: String,
}

impl IosKeyringManager {
    pub fn new(application: &str) -> Result<Self> {
        Ok(IosKeyringManager {
            application: application.to_owned(),
        })
    }

    pub fn with_keyring<F, T>(&self, service: &str, key: &str, func: F) -> Result<T>
    where
        F: FnOnce(&mut dyn Keyring) -> Result<T>,
    {
        let mut kr = IosKeyring::new(&self.application, service, key)?;
        func(&mut kr)
    }

    pub fn list_keys(&self, service: &str) -> Result<Vec<String>> {
        // Matching on an empty service attribute is unreliable, and an iOS app only sees its own
        // keychain access group, so enumerate generic passwords and filter by the account prefix.
        let prefix = format!(
            "{}\t{}\t",
            crate::escape(&self.application),
            crate::escape(service)
        );

        let results = match ItemSearchOptions::new()
            .class(ItemClass::generic_password())
            .limit(Limit::All)
            .load_attributes(true)
            .search()
        {
            Ok(r) => r,
            // No matching items is an empty list, not an error.
            Err(e) if e.code() == errSecItemNotFound => Vec::new(),
            Err(e) => return Err(map_keyring_error(e)),
        };

        // No promotion here: this enumerates every generic password in the app's access group, not
        // only the items this backend wrote.
        results
            .iter()
            .filter_map(|r| r.simplify_dict()?.get("acct").cloned())
            .filter_map(|acct| acct.strip_prefix(&prefix).map(str::to_owned))
            .map(|key| crate::unescape(&key).map_err(map_to_generic))
            .collect()
    }
}

pub struct IosKeyring<'a> {
    application: &'a str,
    service: &'a str,
    key: &'a str,
}

impl<'a> IosKeyring<'a> {
    fn new(application: &'a str, service: &'a str, key: &'a str) -> Result<IosKeyring<'a>> {
        Ok(IosKeyring {
            application,
            service,
            key,
        })
    }

    fn make_key_string(&self) -> String {
        [
            crate::escape(self.application),
            crate::escape(self.service),
            crate::escape(self.key),
        ]
        .join("\t")
    }
}
impl<'a> Keyring for IosKeyring<'a> {
    fn set_value(&mut self, value: &str) -> Result<()> {
        let account_name = self.make_key_string();

        // add and update can each lose to a concurrent delete or add, so retry the pair; a write
        // never reports absence, whatever it loses to
        for _ in 0..3 {
            let mut attrs = item_query(&account_name);
            attrs.push(accessible_pair(target_accessibility()));
            attrs.push(data_pair(value.as_bytes()));
            let params = CFDictionary::from_CFType_pairs(&attrs);
            let status = unsafe { SecItemAdd(params.as_concrete_TypeRef(), std::ptr::null_mut()) };
            if status == 0 {
                return Ok(());
            }
            // accessibility is not part of a generic password's primary key, so an existing item of
            // any class in this access group collides here rather than being added alongside
            if status != errSecDuplicateItem {
                return Err(map_status(status));
            }

            // data alone: an accessibility pair here would let a rejected attribute change fail the
            // write
            let query = CFDictionary::from_CFType_pairs(&item_query(&account_name));
            let update = CFDictionary::from_CFType_pairs(&[data_pair(value.as_bytes())]);
            let status =
                unsafe { SecItemUpdate(query.as_concrete_TypeRef(), update.as_concrete_TypeRef()) };
            if status == errSecItemNotFound {
                continue;
            }
            if status != 0 {
                return Err(map_status(status));
            }
            // data first, attribute second: the reverse could report success for bytes that never
            // landed
            promote_accessibility(&account_name);
            return Ok(());
        }
        Err(map_to_generic("keychain item changed under the write"))
    }

    fn get_value(&self) -> Result<String> {
        let account_name = self.make_key_string();

        let mut query = item_query(&account_name);
        query.push(flag_pair(unsafe { kSecReturnData }));
        query.push(flag_pair(unsafe { kSecReturnAttributes }));

        let items = match copy_all(query) {
            Ok(items) => items,
            Err(KeyringError::NoPasswordFound) => return Err(absence_or_locked()),
            Err(e) => return Err(e),
        };
        if items.is_empty() {
            return Err(absence_or_locked());
        }

        let mut values = Vec::with_capacity(items.len());
        for item in &items {
            values.push(item_data(item)?);
        }
        if values.iter().any(|v| v != &values[0]) {
            return Err(map_to_generic(
                "keychain holds conflicting items for this key",
            ));
        }
        let value = String::from_utf8(values.swap_remove(0)).map_err(|e| {
            KeyringError::from(format!("couldn't convert keychain data to string: {}", e))
        })?;

        // a successful read is proof the class key is available, which is what the update needs
        let current = match all_current(&items) {
            // a query that asked for data is not guaranteed to carry the attribute
            None => copy_attributes(&account_name)
                .ok()
                .and_then(|attrs| all_current(&attrs)),
            known => known,
        };
        if current != Some(true) {
            promote_accessibility(&account_name);
        }
        Ok(value)
    }

    fn delete_value(&mut self) -> Result<()> {
        let account_name = self.make_key_string();
        delete_generic_password("", &account_name).map_err(|e| match map_keyring_error(e) {
            KeyringError::NoPasswordFound => absence_or_locked(),
            e => e,
        })?;
        Ok(())
    }
}