libcryptsetup_rs/luks2/
token.rs

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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

use std::ptr;

use crate::{consts::flags::CryptActivate, device::CryptDevice, err::LibcryptErr};

use libc::{c_char, c_int, c_uint, c_void};

/// Type representing the token status. This type wraps the `CRYPT_TOKEN_*` values and the optional corresponding token type as a string.
pub enum CryptTokenInfo {
    /// Token invalid
    Invalid,
    /// Token is free (empty)
    Inactive,
    /// Active internal token with driver
    Internal(String),
    /// Active internal token (reserved name) with missing token driver
    InternalUnknown(String),
    /// Active external (user defined) token with driver
    External(String),
    /// Active external (user defined) token with missing token driver
    ExternalUnknown(String),
}

impl CryptTokenInfo {
    /// Convert a token status code into `CryptTokenInfo`
    pub fn from_status(code: c_uint, type_: Option<String>) -> Result<Self, LibcryptErr> {
        Ok(match code {
            libcryptsetup_rs_sys::crypt_token_info_CRYPT_TOKEN_INVALID => CryptTokenInfo::Invalid,
            libcryptsetup_rs_sys::crypt_token_info_CRYPT_TOKEN_INACTIVE => CryptTokenInfo::Inactive,
            libcryptsetup_rs_sys::crypt_token_info_CRYPT_TOKEN_INTERNAL => {
                CryptTokenInfo::Internal(type_.ok_or(LibcryptErr::InvalidConversion)?)
            }
            libcryptsetup_rs_sys::crypt_token_info_CRYPT_TOKEN_INTERNAL_UNKNOWN => {
                CryptTokenInfo::InternalUnknown(type_.ok_or(LibcryptErr::InvalidConversion)?)
            }
            libcryptsetup_rs_sys::crypt_token_info_CRYPT_TOKEN_EXTERNAL => {
                CryptTokenInfo::External(type_.ok_or(LibcryptErr::InvalidConversion)?)
            }
            libcryptsetup_rs_sys::crypt_token_info_CRYPT_TOKEN_EXTERNAL_UNKNOWN => {
                CryptTokenInfo::ExternalUnknown(type_.ok_or(LibcryptErr::InvalidConversion)?)
            }
            _ => return Err(LibcryptErr::InvalidConversion),
        })
    }
}

#[allow(clippy::from_over_into)]
impl Into<u32> for CryptTokenInfo {
    fn into(self) -> u32 {
        match self {
            CryptTokenInfo::Invalid => libcryptsetup_rs_sys::crypt_token_info_CRYPT_TOKEN_INVALID,
            CryptTokenInfo::Inactive => libcryptsetup_rs_sys::crypt_token_info_CRYPT_TOKEN_INACTIVE,
            CryptTokenInfo::Internal(_) => {
                libcryptsetup_rs_sys::crypt_token_info_CRYPT_TOKEN_INTERNAL
            }
            CryptTokenInfo::InternalUnknown(_) => {
                libcryptsetup_rs_sys::crypt_token_info_CRYPT_TOKEN_INTERNAL_UNKNOWN
            }
            CryptTokenInfo::External(_) => {
                libcryptsetup_rs_sys::crypt_token_info_CRYPT_TOKEN_EXTERNAL
            }
            CryptTokenInfo::ExternalUnknown(_) => {
                libcryptsetup_rs_sys::crypt_token_info_CRYPT_TOKEN_EXTERNAL_UNKNOWN
            }
        }
    }
}

/// Token input for `CryptLuks2Token::json_set`
pub enum TokenInput<'a> {
    /// Add a new token to any free slot
    AddToken(&'a serde_json::Value),
    /// Replace the specified token
    ReplaceToken(c_uint, &'a serde_json::Value),
    /// Remove the specified token
    RemoveToken(c_uint),
}

/// Handle for LUKS2 token operations
pub struct CryptLuks2TokenHandle<'a> {
    reference: &'a mut CryptDevice,
}

impl<'a> CryptLuks2TokenHandle<'a> {
    pub(crate) fn new(reference: &'a mut CryptDevice) -> Self {
        CryptLuks2TokenHandle { reference }
    }

    /// Get contents of a token in JSON format
    pub fn json_get(&mut self, token: c_uint) -> Result<serde_json::Value, LibcryptErr> {
        let mut ptr: *const c_char = std::ptr::null();
        errno_int_success!(mutex!(libcryptsetup_rs_sys::crypt_token_json_get(
            self.reference.as_ptr(),
            token as c_int,
            &mut ptr as *mut _,
        )))
        .and_then(|_| from_str_ptr!(ptr))
        .and_then(|s| serde_json::from_str(s).map_err(LibcryptErr::JsonError))
    }

    /// Set contents of a token in JSON format
    pub fn json_set(&mut self, input: TokenInput<'_>) -> Result<c_uint, LibcryptErr> {
        let (token, json) = match input {
            TokenInput::AddToken(json) => (libcryptsetup_rs_sys::CRYPT_ANY_TOKEN, Some(json)),
            TokenInput::ReplaceToken(token, json) => (token as i32, Some(json)),
            TokenInput::RemoveToken(token) => (token as i32, None),
        };
        let json_cstring = match json {
            Some(j) => Some(
                serde_json::to_string(j)
                    .map_err(LibcryptErr::JsonError)
                    .and_then(|s| to_cstring!(s))?,
            ),
            None => None,
        };
        errno_int_success!(mutex!(libcryptsetup_rs_sys::crypt_token_json_set(
            self.reference.as_ptr(),
            token,
            json_cstring
                .as_ref()
                .map(|cs| cs.as_ptr())
                .unwrap_or(ptr::null()),
        )))
        .map(|rc| rc as c_uint)
    }

    /// Get the token info for a specific token
    pub fn status(&mut self, token: c_uint) -> Result<CryptTokenInfo, LibcryptErr> {
        let mut ptr: *const c_char = std::ptr::null();
        let code = mutex!(libcryptsetup_rs_sys::crypt_token_status(
            self.reference.as_ptr(),
            token as c_int,
            &mut ptr as *mut _,
        ));
        CryptTokenInfo::from_status(
            code,
            match ptr_to_option!(ptr) {
                Some(p) => Some(from_str_ptr_to_owned!(p)?),
                None => None,
            },
        )
    }

    /// Create new LUKS2 keyring token
    pub fn luks2_keyring_set(
        &mut self,
        token: Option<c_uint>,
        key_description: &str,
    ) -> Result<c_uint, LibcryptErr> {
        let description_cstring = to_cstring!(key_description)?;
        errno_int_success!(mutex!(libcryptsetup_rs_sys::crypt_token_luks2_keyring_set(
            self.reference.as_ptr(),
            token
                .map(|t| t as c_int)
                .unwrap_or(libcryptsetup_rs_sys::CRYPT_ANY_TOKEN),
            &libcryptsetup_rs_sys::crypt_token_params_luks2_keyring {
                key_description: description_cstring.as_ptr(),
            } as *const _,
        )))
        .map(|rc| rc as c_uint)
    }

    /// Get LUKS2 keyring token description
    pub fn luks2_keyring_get(&mut self, token: c_uint) -> Result<String, LibcryptErr> {
        let mut params = libcryptsetup_rs_sys::crypt_token_params_luks2_keyring {
            key_description: std::ptr::null(),
        };
        errno_int_success!(mutex!(libcryptsetup_rs_sys::crypt_token_luks2_keyring_get(
            self.reference.as_ptr(),
            token as c_int,
            &mut params as *mut _,
        )))
        .and_then(|_| from_str_ptr!(params.key_description).map(|s| s.to_string()))
    }

    /// Assign token to keyslot
    ///
    /// `None` for keyslot assigns all keyslots to the token
    pub fn assign_keyslot(
        &mut self,
        token: c_uint,
        keyslot: Option<c_uint>,
    ) -> Result<(), LibcryptErr> {
        errno_int_success!(mutex!(libcryptsetup_rs_sys::crypt_token_assign_keyslot(
            self.reference.as_ptr(),
            token as c_int,
            keyslot
                .map(|k| k as c_int)
                .unwrap_or(libcryptsetup_rs_sys::CRYPT_ANY_SLOT),
        )))
        .map(|_| ())
    }

    /// Unassign token from keyslot
    ///
    /// `None` for keyslot unassigns the token from all active keyslots
    pub fn unassign_keyslot(
        &mut self,
        token: c_uint,
        keyslot: Option<c_uint>,
    ) -> Result<(), LibcryptErr> {
        errno_int_success!(mutex!(libcryptsetup_rs_sys::crypt_token_unassign_keyslot(
            self.reference.as_ptr(),
            token as c_int,
            keyslot
                .map(|k| k as c_int)
                .unwrap_or(libcryptsetup_rs_sys::CRYPT_ANY_SLOT),
        )))
        .map(|_| ())
    }

    /// Check if token is assigned
    #[allow(clippy::wrong_self_convention)]
    pub fn is_assigned(&mut self, token: c_uint, keyslot: c_uint) -> Result<bool, LibcryptErr> {
        let rc = mutex!(libcryptsetup_rs_sys::crypt_token_is_assigned(
            self.reference.as_ptr(),
            token as c_int,
            keyslot as c_int,
        ));
        if rc == 0 {
            Ok(true)
        } else if rc == libc::ENOENT {
            Ok(false)
        } else {
            Err(LibcryptErr::IOError(std::io::Error::from_raw_os_error(-rc)))
        }
    }

    /// Activate device or check key using a token
    pub fn activate_by_token<T>(
        &mut self,
        name: Option<&str>,
        token: Option<c_uint>,
        usrdata: Option<&mut T>,
        flags: CryptActivate,
    ) -> Result<c_uint, LibcryptErr> {
        let name_cstring_option = match name {
            Some(n) => Some(to_cstring!(n)?),
            None => None,
        };
        let usrdata_ptr = match usrdata {
            Some(reference) => (reference as *mut T).cast::<c_void>(),
            None => ptr::null_mut(),
        };
        errno_int_success!(mutex!(libcryptsetup_rs_sys::crypt_activate_by_token(
            self.reference.as_ptr(),
            match name_cstring_option {
                Some(ref s) => s.as_ptr(),
                None => std::ptr::null(),
            },
            token
                .map(|t| t as c_int)
                .unwrap_or(libcryptsetup_rs_sys::CRYPT_ANY_TOKEN),
            usrdata_ptr,
            flags.bits(),
        )))
        .map(|rc| rc as c_uint)
    }
}

/// Register token handler
pub fn register(
    name: &'static str,
    open: libcryptsetup_rs_sys::crypt_token_open_func,
    buffer_free: libcryptsetup_rs_sys::crypt_token_buffer_free_func,
    validate: libcryptsetup_rs_sys::crypt_token_validate_func,
    dump: libcryptsetup_rs_sys::crypt_token_dump_func,
) -> Result<(), LibcryptErr> {
    if name.get(name.len() - 1..) != Some("\0") {
        return Err(LibcryptErr::NoNull(name));
    }
    let handler = libcryptsetup_rs_sys::crypt_token_handler {
        name: name.as_ptr().cast::<c_char>(),
        open,
        buffer_free,
        validate,
        dump,
    };
    errno!(mutex!(libcryptsetup_rs_sys::crypt_token_register(
        &handler as *const libcryptsetup_rs_sys::crypt_token_handler,
    )))
}