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
//! Support for password entries in the keychain.  Works on both iOS and macOS.
//!
//! If you want the extended keychain facilities only available on macOS, use the
//! version of these functions in the macOS extensions module.

use crate::base::Result;
use crate::{cvt, Error};
use core_foundation::base::{CFType, TCFType};
use core_foundation::boolean::CFBoolean;
use core_foundation::data::CFData;
use core_foundation::dictionary::CFDictionary;
use core_foundation::number::CFNumber;
use core_foundation::string::CFString;
use core_foundation_sys::base::{CFGetTypeID, CFRelease, CFTypeRef};
use core_foundation_sys::data::CFDataRef;
use security_framework_sys::base::{errSecDuplicateItem, errSecParam};
use security_framework_sys::item::{
    kSecAttrAccount, kSecAttrAuthenticationType, kSecAttrPath, kSecAttrPort, kSecAttrProtocol,
    kSecAttrSecurityDomain, kSecAttrServer, kSecAttrService, kSecClass, kSecClassGenericPassword,
    kSecClassInternetPassword, kSecReturnData, kSecValueData,
};
use security_framework_sys::keychain::{SecAuthenticationType, SecProtocolType};
use security_framework_sys::keychain_item::{
    SecItemAdd, SecItemCopyMatching, SecItemDelete, SecItemUpdate,
};

/// Set a generic password for the given service and account.
/// Creates or updates a keychain entry.
pub fn set_generic_password(service: &str, account: &str, password: &[u8]) -> Result<()> {
    let mut query = generic_password_query(service, account);
    set_password_internal(&mut query, password)
}

/// Get the generic password for the given service and account.  If no matching
/// keychain entry exists, fails with error code `errSecItemNotFound`.
pub fn get_generic_password(service: &str, account: &str) -> Result<Vec<u8>> {
    let mut query = generic_password_query(service, account);
    query.push((
        unsafe { CFString::wrap_under_get_rule(kSecReturnData) },
        CFBoolean::from(true).as_CFType(),
    ));
    let params = CFDictionary::from_CFType_pairs(&query);
    let mut ret: CFTypeRef = std::ptr::null();
    cvt(unsafe { SecItemCopyMatching(params.as_concrete_TypeRef(), &mut ret) })?;
    get_password_and_release(ret)
}

/// Delete the generic password keychain entry for the given service and account.
/// If none exists, fails with error code `errSecItemNotFound`.
pub fn delete_generic_password(service: &str, account: &str) -> Result<()> {
    let query = generic_password_query(service, account);
    let params = CFDictionary::from_CFType_pairs(&query);
    cvt(unsafe { SecItemDelete(params.as_concrete_TypeRef()) })
}

/// Set an internet password for the given endpoint parameters.
/// Creates or updates a keychain entry.
#[allow(clippy::too_many_arguments)]
pub fn set_internet_password(
    server: &str,
    security_domain: Option<&str>,
    account: &str,
    path: &str,
    port: Option<u16>,
    protocol: SecProtocolType,
    authentication_type: SecAuthenticationType,
    password: &[u8],
) -> Result<()> {
    let mut query = internet_password_query(
        server,
        security_domain,
        account,
        path,
        port,
        protocol,
        authentication_type,
    );
    set_password_internal(&mut query, password)
}

/// Get the internet password for the given endpoint parameters.  If no matching
/// keychain entry exists, fails with error code `errSecItemNotFound`.
pub fn get_internet_password(
    server: &str,
    security_domain: Option<&str>,
    account: &str,
    path: &str,
    port: Option<u16>,
    protocol: SecProtocolType,
    authentication_type: SecAuthenticationType,
) -> Result<Vec<u8>> {
    let mut query = internet_password_query(
        server,
        security_domain,
        account,
        path,
        port,
        protocol,
        authentication_type,
    );
    query.push((
        unsafe { CFString::wrap_under_get_rule(kSecReturnData) },
        CFBoolean::from(true).as_CFType(),
    ));
    let params = CFDictionary::from_CFType_pairs(&query);
    let mut ret: CFTypeRef = std::ptr::null();
    cvt(unsafe { SecItemCopyMatching(params.as_concrete_TypeRef(), &mut ret) })?;
    get_password_and_release(ret)
}

/// Delete the internet password for the given endpoint parameters.
/// If none exists, fails with error code `errSecItemNotFound`.
pub fn delete_internet_password(
    server: &str,
    security_domain: Option<&str>,
    account: &str,
    path: &str,
    port: Option<u16>,
    protocol: SecProtocolType,
    authentication_type: SecAuthenticationType,
) -> Result<()> {
    let query = internet_password_query(
        server,
        security_domain,
        account,
        path,
        port,
        protocol,
        authentication_type,
    );
    let params = CFDictionary::from_CFType_pairs(&query);
    cvt(unsafe { SecItemDelete(params.as_concrete_TypeRef()) })
}

// Generic passwords are identified by service and account.  They have other
// attributes, but this interface doesn't allow specifying them.
fn generic_password_query(service: &str, account: &str) -> Vec<(CFString, CFType)> {
    let query = vec![
        (
            unsafe { CFString::wrap_under_get_rule(kSecClass) },
            unsafe { CFString::wrap_under_get_rule(kSecClassGenericPassword).as_CFType() },
        ),
        (
            unsafe { CFString::wrap_under_get_rule(kSecAttrService) },
            CFString::from(service).as_CFType(),
        ),
        (
            unsafe { CFString::wrap_under_get_rule(kSecAttrAccount) },
            CFString::from(account).as_CFType(),
        ),
        (
            unsafe { CFString::wrap_under_get_rule(kSecReturnData) },
            CFBoolean::from(true).as_CFType(),
        ),
    ];
    query
}

// Internet passwords are identified by a number of attributes.
// They can have others, but this interface doesn't allow specifying them.
fn internet_password_query(
    server: &str,
    security_domain: Option<&str>,
    account: &str,
    path: &str,
    port: Option<u16>,
    protocol: SecProtocolType,
    authentication_type: SecAuthenticationType,
) -> Vec<(CFString, CFType)> {
    let mut query = vec![
        (
            unsafe { CFString::wrap_under_get_rule(kSecClass) },
            unsafe { CFString::wrap_under_get_rule(kSecClassInternetPassword) }.as_CFType(),
        ),
        (
            unsafe { CFString::wrap_under_get_rule(kSecAttrServer) },
            CFString::from(server).as_CFType(),
        ),
        (
            unsafe { CFString::wrap_under_get_rule(kSecAttrPath) },
            CFString::from(path).as_CFType(),
        ),
        (
            unsafe { CFString::wrap_under_get_rule(kSecAttrAccount) },
            CFString::from(account).as_CFType(),
        ),
        (
            unsafe { CFString::wrap_under_get_rule(kSecAttrProtocol) },
            CFNumber::from(protocol as i32).as_CFType(),
        ),
        (
            unsafe { CFString::wrap_under_get_rule(kSecAttrAuthenticationType) },
            CFNumber::from(authentication_type as i32).as_CFType(),
        ),
    ];
    if let Some(domain) = security_domain {
        query.push((
            unsafe { CFString::wrap_under_get_rule(kSecAttrSecurityDomain) },
            CFString::from(domain).as_CFType(),
        ))
    }
    if let Some(port) = port {
        query.push((
            unsafe { CFString::wrap_under_get_rule(kSecAttrPort) },
            CFNumber::from(port as i32).as_CFType(),
        ))
    }
    query
}

// This starts by trying to create the password with the given query params.
// If the creation attempt reveals that one exists, its password is updated.
fn set_password_internal(query: &mut Vec<(CFString, CFType)>, password: &[u8]) -> Result<()> {
    let query_len = query.len();
    query.push((
        unsafe { CFString::wrap_under_get_rule(kSecValueData) },
        CFData::from_buffer(password).as_CFType(),
    ));
    let params = CFDictionary::from_CFType_pairs(query);
    let mut ret = std::ptr::null();
    let status = unsafe { SecItemAdd(params.as_concrete_TypeRef(), &mut ret) };
    if status == errSecDuplicateItem {
        let params = CFDictionary::from_CFType_pairs(&query[0..query_len]);
        let update = CFDictionary::from_CFType_pairs(&query[query_len..]);
        cvt(unsafe { SecItemUpdate(params.as_concrete_TypeRef(), update.as_concrete_TypeRef()) })
    } else {
        cvt(status)
    }
}

// Having retrieved a password entry, this copies and returns the password.
//
// # Safety
// The data element passed in is assumed to have been returned from a Copy
// call, so it's released after we are done with it.
fn get_password_and_release(data: CFTypeRef) -> Result<Vec<u8>> {
    if !data.is_null() {
        let type_id = unsafe { CFGetTypeID(data) };
        if type_id == CFData::type_id() {
            let val = unsafe { CFData::wrap_under_create_rule(data as CFDataRef) };
            let mut vec = Vec::new();
            vec.extend_from_slice(val.bytes());
            return Ok(vec);
        } else {
            // unexpected: we got a reference to some other type.
            // Release it to make sure there's no leak, but
            // we can't return the password in this case.
            unsafe { CFRelease(data) };
        }
    }
    Err(Error::from_code(errSecParam))
}

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

    #[test]
    fn missing_generic() {
        let name = "a string not likely to already be in the keychain as service or account";
        let password = get_generic_password(name, name);
        assert!(password.is_err());
    }

    #[test]
    fn roundtrip_generic() {
        let name = "roundtrip_generic";
        set_generic_password(name, name, name.as_bytes()).expect("set_generic_password");
        let pass = get_generic_password(name, name).expect("get_generic_password");
        assert_eq!(name.as_bytes(), pass);
        delete_generic_password(name, name).expect("delete_generic_password")
    }

    #[test]
    fn update_generic() {
        let name = "update_generic";
        set_generic_password(name, name, name.as_bytes()).expect("set_generic_password");
        let alternate = "update_generic_alternate";
        set_generic_password(name, name, alternate.as_bytes()).expect("set_generic_password");
        let pass = get_generic_password(name, name).expect("get_generic_password");
        assert_eq!(pass, alternate.as_bytes());
        delete_generic_password(name, name).expect("delete_generic_password")
    }

    #[test]
    fn missing_internet() {
        let name = "a string not likely to already be in the keychain as service or account";
        let (server, domain, account, path, port, protocol, auth) = (
            name,
            None,
            name,
            "/",
            Some(8080u16),
            SecProtocolType::HTTP,
            SecAuthenticationType::Any,
        );
        let password = get_internet_password(server, domain, account, path, port, protocol, auth);
        assert!(password.is_err());
    }

    #[test]
    fn roundtrip_internet() {
        let name = "roundtrip_internet";
        let (server, domain, account, path, port, protocol, auth) = (
            name,
            None,
            name,
            "/",
            Some(8080u16),
            SecProtocolType::HTTP,
            SecAuthenticationType::Any,
        );
        set_internet_password(
            server,
            domain,
            account,
            path,
            port,
            protocol,
            auth,
            name.as_bytes(),
        )
        .expect("set_internet_password");
        let pass = get_internet_password(server, domain, account, path, port, protocol, auth)
            .expect("get_internet_password");
        assert_eq!(name.as_bytes(), pass);
        delete_internet_password(server, domain, account, path, port, protocol, auth)
            .expect("delete_internet_password");
    }

    #[test]
    fn update_internet() {
        let name = "update_internet";
        let (server, domain, account, path, port, protocol, auth) = (
            name,
            None,
            name,
            "/",
            Some(8080u16),
            SecProtocolType::HTTP,
            SecAuthenticationType::Any,
        );
        set_internet_password(
            server,
            domain,
            account,
            path,
            port,
            protocol,
            auth,
            name.as_bytes(),
        )
        .expect("set_internet_password");
        let alternate = "alternate_internet_password";
        set_internet_password(
            server,
            domain,
            account,
            path,
            port,
            protocol,
            auth,
            alternate.as_bytes(),
        )
        .expect("set_internet_password");
        let pass = get_internet_password(server, domain, account, path, port, protocol, auth)
            .expect("get_internet_password");
        assert_eq!(pass, alternate.as_bytes());
        delete_internet_password(server, domain, account, path, port, protocol, auth)
            .expect("delete_internet_password");
    }
}