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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
extern crate errno;
extern crate libc;
use super::constants::*;
use super::ffi::*;
use std::ffi::CString;
use std::mem;
use std::os::unix::raw::{gid_t, uid_t};
use std::ptr;
use std::result;
use std::str;
pub type Error = errno::Errno;
pub type Result<T> = result::Result<T, Error>;
fn check_call<T>(res: libc::c_long, value: T) -> Result<T> {
if res == -1 {
Err(errno::errno())
} else {
Ok(value)
}
}
fn check_call_ret(res: libc::c_long) -> Result<libc::c_long> {
if res == -1 {
Err(errno::errno())
} else {
Ok(res)
}
}
fn check_call_ret_serial(res: KeyringSerial) -> Result<KeyringSerial> {
if res == -1 {
Err(errno::errno())
} else {
Ok(res)
}
}
pub struct Keyring {
id: KeyringSerial,
}
impl Keyring {
pub fn set_default(keyring: DefaultKeyring) -> Result<DefaultKeyring> {
let ret = try!(check_call_ret(unsafe { keyctl_set_reqkey_keyring(keyring.serial()) }));
Ok(DefaultKeyring::from(ret as i32))
}
pub fn request(description: &str) -> Result<Self> {
Keyring { id: 0, }.request_keyring(description)
}
pub fn request_with_fallback(description: &str, info: &str) -> Result<Self> {
Keyring { id: 0, }.request_keyring_with_fallback(description, info)
}
fn get_keyring(id: SpecialKeyring, create: bool) -> Result<Keyring> {
let res = unsafe { keyctl_get_keyring_ID(id.serial(), create as libc::c_int) };
check_call(res as libc::c_long, Keyring { id: res, })
}
pub fn attach(id: SpecialKeyring) -> Result<Self> {
Self::get_keyring(id, false)
}
pub fn attach_or_create(id: SpecialKeyring) -> Result<Self> {
Self::get_keyring(id, true)
}
pub fn join_anonymous_session() -> Result<Self> {
let res = unsafe { keyctl_join_session_keyring(ptr::null()) };
check_call(res as libc::c_long, Keyring { id: res })
}
pub fn join_session(name: &str) -> Result<Self> {
let name_cstr = CString::new(name).unwrap();
let res = unsafe { keyctl_join_session_keyring(name_cstr.as_ptr()) };
check_call(res as libc::c_long, Keyring { id: res })
}
pub fn clear(&mut self) -> Result<()> {
check_call(unsafe { keyctl_clear(self.id) }, ())
}
pub fn link_key(&mut self, key: &Key) -> Result<()> {
check_call(unsafe { keyctl_link(key.id, self.id) }, ())
}
pub fn unlink_key(&mut self, key: &Key) -> Result<()> {
check_call(unsafe { keyctl_unlink(key.id, self.id) }, ())
}
pub fn link_keyring(&mut self, keyring: &Keyring) -> Result<()> {
check_call(unsafe { keyctl_link(keyring.id, self.id) }, ())
}
pub fn unlink_keyring(&mut self, keyring: &Keyring) -> Result<()> {
check_call(unsafe { keyctl_unlink(keyring.id, self.id) }, ())
}
fn _search(&self, type_: &str, description: &str) -> Result<libc::c_long> {
let type_cstr = CString::new(type_).unwrap();
let desc_cstr = CString::new(description).unwrap();
check_call_ret(unsafe { keyctl_search(self.id, type_cstr.as_ptr(), desc_cstr.as_ptr(), self.id) })
}
pub fn search_for_key(&self, description: &str) -> Result<Key> {
let res = try!(self._search("user", description));
check_call(res, Key { id: res as key_serial_t, })
}
pub fn search_for_keyring(&self, description: &str) -> Result<Self> {
let res = try!(self._search("keyring", description));
check_call(res, Keyring { id: res as key_serial_t, })
}
pub fn read(&self) -> Result<(Vec<Key>, Vec<Keyring>)> {
let sz = try!(check_call_ret(unsafe { keyctl_read(self.id, ptr::null_mut(), 0) }));
let mut buffer = Vec::<key_serial_t>::with_capacity((sz as usize) / mem::size_of::<KeyringSerial>());
let actual_sz = try!(check_call_ret(unsafe { keyctl_read(self.id, buffer.as_mut_ptr() as *mut libc::c_char, sz as usize) }));
unsafe { buffer.set_len((actual_sz as usize) / mem::size_of::<KeyringSerial>()) };
let keys = buffer.iter().map(|&id| { Key { id: id, } }).partition(|key| {
key.description().unwrap().type_ == "keyring"
});
Ok((keys.1, keys.0.iter().map(|key| {
Keyring {
id: key.id,
}
}).collect::<Vec<Keyring>>()))
}
pub fn attach_persistent(&mut self) -> Result<Self> {
let res = unsafe { keyctl_get_persistent(!0, self.id) };
check_call(res, Keyring { id: res as key_serial_t, })
}
pub fn add_key(&mut self, description: &str, payload: &[u8]) -> Result<Key> {
let type_cstr = CString::new("user").unwrap();
let desc_cstr = CString::new(description).unwrap();
let res = unsafe { add_key(type_cstr.as_ptr(), desc_cstr.as_ptr(), payload.as_ptr() as *const libc::c_void, payload.len(), self.id) };
check_call(res as libc::c_long, Key { id: res, })
}
pub fn add_keyring(&mut self, description: &str) -> Result<Self> {
let type_cstr = CString::new("keyring").unwrap();
let desc_cstr = CString::new(description).unwrap();
let res = unsafe { add_key(type_cstr.as_ptr(), desc_cstr.as_ptr(), ptr::null(), 0, self.id) };
check_call(res as libc::c_long, Keyring { id: res, })
}
fn _request(&self, type_: &str, description: &str) -> Result<KeyringSerial> {
let type_cstr = CString::new(type_).unwrap();
let desc_cstr = CString::new(description).unwrap();
check_call_ret_serial(unsafe { request_key(type_cstr.as_ptr(), desc_cstr.as_ptr(), ptr::null(), self.id) })
}
pub fn request_key(&self, description: &str) -> Result<Key> {
let res = try!(self._request("user", description));
check_call(res as libc::c_long, Key { id: res, })
}
pub fn request_keyring(&self, description: &str) -> Result<Self> {
let res = try!(self._request("keyring", description));
check_call(res as libc::c_long, Keyring { id: res, })
}
fn _request_fallback(&self, type_: &str, description: &str, info: &str) -> Result<KeyringSerial> {
let type_cstr = CString::new(type_).unwrap();
let desc_cstr = CString::new(description).unwrap();
let info_cstr = CString::new(info).unwrap();
check_call_ret_serial(unsafe { request_key(type_cstr.as_ptr(), desc_cstr.as_ptr(), info_cstr.as_ptr(), self.id) })
}
pub fn request_key_with_fallback(&self, description: &str, info: &str) -> Result<Key> {
let res = try!(self._request_fallback("user", description, info));
check_call(res as libc::c_long, Key { id: res, })
}
pub fn request_keyring_with_fallback(&self, description: &str, info: &str) -> Result<Self> {
let res = try!(self._request_fallback("keyring", description, info));
check_call(res as libc::c_long, Keyring { id: res, })
}
pub fn revoke(self) -> Result<()> {
check_call(unsafe { keyctl_revoke(self.id) }, ())
}
pub fn chown(&mut self, uid: uid_t) -> Result<()> {
check_call(unsafe { keyctl_chown(self.id, uid, !0) }, ())
}
pub fn chgrp(&mut self, gid: gid_t) -> Result<()> {
check_call(unsafe { keyctl_chown(self.id, !0, gid) }, ())
}
pub fn set_permissions(&mut self, perms: KeyPermissions) -> Result<()> {
check_call(unsafe { keyctl_setperm(self.id, perms) }, ())
}
fn description_raw(&self) -> Result<String> {
let sz = try!(check_call_ret(unsafe { keyctl_describe(self.id, ptr::null_mut(), 0) }));
let mut buffer = Vec::with_capacity(sz as usize);
let actual_sz = try!(check_call_ret(unsafe { keyctl_describe(self.id, buffer.as_mut_ptr() as *mut libc::c_char, sz as usize) }));
unsafe { buffer.set_len((actual_sz - 1) as usize) };
let str_slice = str::from_utf8(&buffer[..]).unwrap();
Ok(str_slice.to_owned())
}
pub fn description(&self) -> Result<KeyDescription> {
self.description_raw().and_then(|desc| {
KeyDescription::parse(desc)
.ok_or(errno::Errno(libc::EINVAL))
})
}
pub fn set_timeout(&mut self, timeout: u32) -> Result<()> {
check_call(unsafe { keyctl_set_timeout(self.id, timeout) }, ())
}
pub fn security(&self) -> Result<String> {
let sz = try!(check_call_ret(unsafe { keyctl_get_security(self.id, ptr::null_mut(), 0) }));
let mut buffer = Vec::with_capacity(sz as usize);
let actual_sz = try!(check_call_ret(unsafe { keyctl_get_security(self.id, buffer.as_mut_ptr() as *mut libc::c_char, sz as usize) }));
unsafe { buffer.set_len(actual_sz as usize) };
let str_slice = str::from_utf8(&buffer[..]).unwrap();
Ok(str_slice.to_owned())
}
pub fn invalidate(self) -> Result<()> {
check_call(unsafe { keyctl_invalidate(self.id) }, ())
}
}
pub struct Key {
id: KeyringSerial,
}
impl Key {
pub fn request_key_auth_key(create: bool) -> Result<Self> {
let res = unsafe { keyctl_get_keyring_ID(KEY_SPEC_REQKEY_AUTH_KEY, create as libc::c_int) };
check_call(res as libc::c_long, Key { id: res, })
}
pub fn request(description: &str) -> Result<Self> {
Keyring { id: 0, }.request_key(description)
}
pub fn request_with_fallback(description: &str, info: &str) -> Result<Self> {
Keyring { id: 0, }.request_key_with_fallback(description, info)
}
pub fn update(&mut self, data: &[u8]) -> Result<()> {
check_call(unsafe { keyctl_update(self.id, data.as_ptr() as *const libc::c_void, data.len()) }, ())
}
pub fn revoke(self) -> Result<()> {
Keyring { id: self.id }.revoke()
}
pub fn chown(&mut self, uid: uid_t) -> Result<()> {
Keyring { id: self.id }.chown(uid)
}
pub fn chgrp(&mut self, gid: gid_t) -> Result<()> {
Keyring { id: self.id }.chgrp(gid)
}
pub fn set_permissions(&mut self, perms: KeyPermissions) -> Result<()> {
Keyring { id: self.id }.set_permissions(perms)
}
pub fn description(&self) -> Result<KeyDescription> {
Keyring { id: self.id }.description()
}
pub fn read(&self) -> Result<Vec<u8>> {
let sz = try!(check_call_ret(unsafe { keyctl_read(self.id, ptr::null_mut(), 0) }));
let mut buffer = Vec::with_capacity(sz as usize);
let actual_sz = try!(check_call_ret(unsafe { keyctl_read(self.id, buffer.as_mut_ptr() as *mut libc::c_char, sz as usize) }));
unsafe { buffer.set_len(actual_sz as usize) };
Ok(buffer)
}
pub fn set_timeout(&mut self, timeout: u32) -> Result<()> {
Keyring { id: self.id }.set_timeout(timeout)
}
pub fn security(&self) -> Result<String> {
Keyring { id: self.id }.security()
}
pub fn invalidate(self) -> Result<()> {
Keyring { id: self.id }.invalidate()
}
pub fn manage(&mut self) -> Result<KeyManager> {
check_call(unsafe { keyctl_assume_authority(self.id) }, KeyManager {
key: Key {
id: self.id,
},
})
}
}
pub struct KeyDescription {
pub type_: String,
pub uid: uid_t,
pub gid: gid_t,
pub perms: KeyPermissions,
pub description: String,
}
impl KeyDescription {
fn parse(desc: String) -> Option<KeyDescription> {
let mut pieces = desc.split(';').collect::<Vec<&str>>();
pieces.reverse();
let len = pieces.len();
if len < 5 {
None
} else {
if len > 5 {
println!("New fields detected! Please report this upstream to https://github.com/mathstuf/rust-keyutils: {}", desc);
}
Some(KeyDescription {
type_: pieces[4].to_owned(),
uid: pieces[3].parse::<uid_t>().unwrap(),
gid: pieces[2].parse::<gid_t>().unwrap(),
perms: KeyPermissions::from_str_radix(pieces[1], 16).unwrap(),
description: pieces[0].to_owned(),
})
}
}
}
pub struct KeyManager {
key: Key,
}
impl KeyManager {
pub fn instantiate(self, keyring: &Keyring, payload: &[u8]) -> Result<()> {
check_call(unsafe { keyctl_instantiate(self.key.id, payload.as_ptr() as *const libc::c_void, payload.len(), keyring.id) }, ())
}
pub fn reject(self, keyring: &Keyring, timeout: u32, error: errno::Errno) -> Result<()> {
let errno::Errno(errval) = error;
check_call(unsafe { keyctl_reject(self.key.id, timeout, errval as u32, keyring.id) }, ())
}
pub fn negate(self, keyring: &Keyring, timeout: u32) -> Result<()> {
check_call(unsafe { keyctl_negate(self.key.id, timeout, keyring.id) }, ())
}
}
#[test]
fn test_add_key() {
let mut keyring = Keyring::attach_or_create(SpecialKeyring::ThreadKeyring).unwrap();
let description = "test:ruskey:add_key";
let payload = "payload";
let key = keyring.add_key(description, payload.as_bytes()).unwrap();
assert_eq!(key.read().unwrap(), payload.as_bytes().iter().cloned().collect::<Vec<u8>>());
let new_payload = "new_payload";
let updated_key = keyring.add_key(description, new_payload.as_bytes()).unwrap();
assert_eq!(key.read().unwrap(), new_payload.as_bytes().iter().cloned().collect::<Vec<u8>>());
assert_eq!(updated_key.read().unwrap(), new_payload.as_bytes().iter().cloned().collect::<Vec<u8>>());
keyring.unlink_key(&key).unwrap();
keyring.invalidate().unwrap();
}
#[test]
fn test_clear_keyring() {
let mut keyring = Keyring::attach_or_create(SpecialKeyring::ThreadKeyring).unwrap();
{
let (keys, keyrings) = keyring.read().unwrap();
assert_eq!(keys.len(), 0);
assert_eq!(keyrings.len(), 0);
}
keyring.add_key("test:ruskey:clear_keyring", "payload".as_bytes()).unwrap();
keyring.add_keyring("description").unwrap();
{
let (keys, keyrings) = keyring.read().unwrap();
assert_eq!(keys.len(), 1);
assert_eq!(keyrings.len(), 1);
}
keyring.clear().unwrap();
{
let (keys, keyrings) = keyring.read().unwrap();
assert_eq!(keys.len(), 0);
assert_eq!(keyrings.len(), 0);
}
keyring.invalidate().unwrap();
}
#[test]
fn test_describe_key() {
let mut keyring = Keyring::attach_or_create(SpecialKeyring::ThreadKeyring).unwrap();
let desc = "test:ruskey:describe_key";
let payload = "payload";
let key = keyring.add_key(desc, payload.as_bytes()).unwrap();
assert_eq!(key.description().unwrap().description, desc);
keyring.unlink_key(&key).unwrap();
keyring.invalidate().unwrap();
}
#[test]
fn test_invalidate_key() {
unimplemented!()
}
#[test]
fn test_link_keyring() {
unimplemented!()
}
#[test]
fn test_read_keyring() {
unimplemented!()
}
#[test]
fn test_read_key() {
unimplemented!()
}
#[test]
fn test_create_keyring() {
unimplemented!()
}
#[test]
fn test_chmod_keyring() {
unimplemented!()
}
#[test]
fn test_request_key() {
unimplemented!()
}
#[test]
fn test_revoke_key() {
unimplemented!()
}
#[test]
fn test_search_key() {
unimplemented!()
}
#[test]
fn test_key_timeout() {
unimplemented!()
}
#[test]
fn test_unlink_key() {
unimplemented!()
}
#[test]
fn test_update_key() {
unimplemented!()
}