Skip to content

Port keyutils tests add #33

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jul 7, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ edition = "2018"
[workspace]
members = ["keyutils-raw"]

[dev-dependencies]
lazy_static = "1"
regex = "1"

[dependencies]
bitflags = "1.0.4"
errno = "0.2"
Expand Down
7 changes: 7 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@

#![warn(missing_docs)]

#[cfg(test)]
#[macro_use]
extern crate lazy_static;

mod api;
mod constants;
mod keytype;
Expand All @@ -41,3 +45,6 @@ pub use self::constants::*;
pub use self::keytype::*;

pub use keyutils_raw::{DefaultKeyring, KeyPermissions, KeyringSerial, TimeoutSeconds};

#[cfg(test)]
mod tests;
131 changes: 131 additions & 0 deletions src/tests/add.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
// Copyright (c) 2019, Ben Boeckel
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of this project nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

use std::iter;

use crate::keytypes::User;
use crate::{Keyring, KeyringSerial, SpecialKeyring};

use super::utils::kernel::*;
use super::utils::keys::*;

#[test]
fn empty_key_type() {
let mut keyring = Keyring::attach_or_create(SpecialKeyring::Process).unwrap();
let err = keyring.add_key::<EmptyKey, _, _>("", ()).unwrap_err();
assert_eq!(err, errno::Errno(libc::EINVAL));
}

#[test]
fn unsupported_key_type() {
let mut keyring = Keyring::attach_or_create(SpecialKeyring::Process).unwrap();
let err = keyring.add_key::<UnsupportedKey, _, _>("", ()).unwrap_err();
assert_eq!(err, errno::Errno(libc::ENODEV));
}

#[test]
fn invalid_key_type() {
let mut keyring = Keyring::attach_or_create(SpecialKeyring::Process).unwrap();
let err = keyring.add_key::<InvalidKey, _, _>("", ()).unwrap_err();
assert_eq!(err, errno::Errno(libc::EPERM));
}

#[test]
fn maxlen_key_type() {
let mut keyring = Keyring::attach_or_create(SpecialKeyring::Process).unwrap();
let err = keyring.add_key::<MaxLenKey, _, _>("", ()).unwrap_err();
assert_eq!(err, errno::Errno(libc::ENODEV));
}

#[test]
fn overlong_key_type() {
let mut keyring = Keyring::attach_or_create(SpecialKeyring::Process).unwrap();
let err = keyring.add_key::<OverlongKey, _, _>("", ()).unwrap_err();
assert_eq!(err, errno::Errno(libc::EINVAL));
}

#[test]
fn keyring_with_payload() {
let mut keyring = Keyring::attach_or_create(SpecialKeyring::Process).unwrap();
let err = keyring
.add_key::<KeyringShadow, _, _>("", "payload")
.unwrap_err();
assert_eq!(err, errno::Errno(libc::EINVAL));
}

#[test]
fn max_user_description() {
let mut keyring = Keyring::attach_or_create(SpecialKeyring::Process).unwrap();
// Subtract one because the NUL is added in the kernel API.
let maxdesc: String = iter::repeat('a').take(*PAGE_SIZE - 1).collect();
let res = keyring.add_key::<User, _, _>(maxdesc.as_ref(), "payload".as_bytes());
// If the user's quota is smaller than this, it's an error.
if KEY_INFO.maxbytes < *PAGE_SIZE {
assert_eq!(res.unwrap_err(), errno::Errno(libc::EDQUOT));
} else {
let key = res.unwrap();
assert_eq!(key.description().unwrap().description, maxdesc);
key.invalidate().unwrap();
}
}

#[test]
fn overlong_user_description() {
let mut keyring = Keyring::attach_or_create(SpecialKeyring::Process).unwrap();
// On MIPS with < 3.19, there is a bug where this is allowed. 3.19 was released in Feb 2015,
// so this is being ignored here.
let toolarge: String = iter::repeat('a').take(*PAGE_SIZE).collect();
let err = keyring
.add_key::<User, _, _>(toolarge.as_ref(), "payload".as_bytes())
.unwrap_err();
assert_eq!(err, errno::Errno(libc::EINVAL));
}

#[test]
fn invalid_keyring() {
// Yes, we're explicitly breaking the NonZeroI32 rules here. However, it is not passing
// through any bits which care (e.g., `Option`), so this is purely to test that using an
// invalid keyring ID gives back `EINVAL` as expected.
let mut keyring = unsafe { Keyring::new(KeyringSerial::new_unchecked(0)) };
let err = keyring
.add_key::<User, _, _>("desc", "payload".as_bytes())
.unwrap_err();
assert_eq!(err, errno::Errno(libc::EINVAL));
}

#[test]
fn add_key_to_session() {
let mut keyring = Keyring::attach_or_create(SpecialKeyring::Session).unwrap();
let expected = "stuff".as_bytes();
let mut key = keyring.add_key::<User, _, _>("wibble", expected).unwrap();
let payload = key.read().unwrap();
assert_eq!(payload, expected);
let new_expected = "lizard".as_bytes();
key.update(new_expected).unwrap();
let new_payload = key.read().unwrap();
assert_eq!(new_payload, new_expected);
keyring.unlink_key(&key).unwrap();
}
31 changes: 31 additions & 0 deletions src/tests/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Copyright (c) 2019, Ben Boeckel
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of this project nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

//! The test structure here comes from the structure in libkeyutils.

mod utils;

mod add;
122 changes: 122 additions & 0 deletions src/tests/utils/kernel.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
// Copyright (c) 2019, Ben Boeckel
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of this project nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

use std::collections::HashMap;
use std::fs;
use std::str::FromStr;

use regex::{Captures, Regex};

lazy_static! {
pub static ref PAGE_SIZE: usize = page_size();
pub static ref KEY_INFO: KeyQuota = key_user_info();
}

fn page_size() -> usize {
errno::set_errno(errno::Errno(0));
let ret = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
if ret < 0 {
let err = errno::errno();
if err.0 == 0 {
panic!("page size is indeterminite?");
} else {
panic!("failed to query the page size: {}", errno::errno());
}
}
ret as usize
}

const KEY_USERS_FILE: &str = "/proc/key-users";

lazy_static! {
static ref KEY_USERS: Regex = Regex::new(
" *(?P<uid>\\d+): +\
(?P<usage>\\d+) \
(?P<nkeys>\\d+)/(?P<nikeys>\\d+) \
(?P<qnkeys>\\d+)/(?P<maxkeys>\\d+) \
(?P<qnbytes>\\d+)/(?P<maxbytes>\\d+)"
)
.unwrap();
}

fn by_name<T: FromStr>(capture: &Captures, name: &str) -> T {
let cap = capture
.name(name)
.expect("name should be captured")
.as_str();
match cap.parse() {
Ok(v) => v,
Err(_) => panic!("failed to parse {} as an integer", name),
}
}

#[derive(Debug, Clone, Copy)]
pub struct KeyQuota {
pub usage: usize,
pub nkeys: usize,
pub nikeys: usize,
pub qnkeys: usize,
pub maxkeys: usize,
pub qnbytes: usize,
pub maxbytes: usize,
}

fn all_key_user_info() -> HashMap<libc::uid_t, KeyQuota> {
let data = String::from_utf8(fs::read(KEY_USERS_FILE).unwrap()).unwrap();
(*KEY_USERS)
.captures_iter(&data)
.map(|capture| {
let uid = by_name(&capture, "uid");
let usage = by_name(&capture, "usage");
let nkeys = by_name(&capture, "nkeys");
let nikeys = by_name(&capture, "nikeys");
let qnkeys = by_name(&capture, "qnkeys");
let maxkeys = by_name(&capture, "maxkeys");
let qnbytes = by_name(&capture, "qnbytes");
let maxbytes = by_name(&capture, "maxbytes");

(
uid,
KeyQuota {
usage,
nkeys,
nikeys,
qnkeys,
maxkeys,
qnbytes,
maxbytes,
},
)
})
.collect()
}

fn key_user_info() -> KeyQuota {
let uid = unsafe { libc::getuid() };
*all_key_user_info()
.get(&uid)
.expect("the current user has no keys?")
}
Loading