Skip to main content

cryptoki/
types.rs

1// Copyright 2021 Contributors to the Parsec project.
2// SPDX-License-Identifier: Apache-2.0
3//! PKCS11 General Data Types
4
5use crate::error::{Error, Result};
6use cryptoki_sys::*;
7use secrecy::{SecretBox, SecretString};
8use std::convert::TryFrom;
9use std::convert::TryInto;
10use std::fmt::Formatter;
11use std::ops::Deref;
12
13#[derive(Debug, Copy, Clone, Default)]
14#[repr(transparent)]
15/// Value that represents a date
16pub struct Date {
17    date: CK_DATE,
18}
19
20impl Date {
21    /// Creates a new `Date` structure
22    ///
23    /// # Arguments
24    ///
25    /// * `year` - A 4 character length year, e.g. "2021"
26    /// * `month` - A 2 character length mont, e.g. "02"
27    /// * `day` - A 2 character length day, e.g. "15"
28    ///
29    /// # Errors
30    ///
31    /// If the lengths are invalid, an `Error::InvalidValue` will be returned
32    pub fn new_from_str_slice(year: &str, month: &str, day: &str) -> Result<Self> {
33        if year.len() != 4 || month.len() != 2 || day.len() != 2 {
34            Err(Error::InvalidValue)
35        } else {
36            let mut year_slice: [u8; 4] = Default::default();
37            let mut month_slice: [u8; 2] = Default::default();
38            let mut day_slice: [u8; 2] = Default::default();
39            year_slice.copy_from_slice(year.as_bytes());
40            month_slice.copy_from_slice(month.as_bytes());
41            day_slice.copy_from_slice(day.as_bytes());
42            Ok(Date::new(year_slice, month_slice, day_slice))
43        }
44    }
45
46    /// Creates a new `Date` structure from byte slices
47    ///
48    /// # Arguments
49    ///
50    /// * `year` - A 4 character length year, e.g. "2021"
51    /// * `month` - A 2 character length mont, e.g. "02"
52    /// * `day` - A 2 character length day, e.g. "15"
53    pub fn new(year: [u8; 4], month: [u8; 2], day: [u8; 2]) -> Self {
54        let date = CK_DATE { year, month, day };
55        Self { date }
56    }
57
58    /// Creates a new, empty `Date` structure
59    ///
60    /// This represents the default value of the attribute (on
61    /// newer implementations of `Cryptoki`).
62    pub fn new_empty() -> Self {
63        Self::default()
64    }
65
66    /// Check if `Date` is empty
67    ///
68    /// *NOTE*: This function is only representative of newer implementations
69    /// of `Cryptoki`, for which dates are represented as empty object attributes.
70    pub fn is_empty(&self) -> bool {
71        self.date.year == <[u8; 4]>::default()
72            && self.date.month == <[u8; 2]>::default()
73            && self.date.day == <[u8; 2]>::default()
74    }
75}
76
77impl Deref for Date {
78    type Target = CK_DATE;
79
80    fn deref(&self) -> &Self::Target {
81        &self.date
82    }
83}
84
85impl From<Date> for CK_DATE {
86    fn from(date: Date) -> Self {
87        *date
88    }
89}
90
91impl From<CK_DATE> for Date {
92    fn from(date: CK_DATE) -> Self {
93        Self { date }
94    }
95}
96
97impl std::fmt::Display for Date {
98    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
99        let year = String::from_utf8_lossy(Vec::from(self.year).as_slice())
100            .trim_end()
101            .to_string();
102        let month = String::from_utf8_lossy(Vec::from(self.month).as_slice())
103            .trim_end()
104            .to_string();
105        let day = String::from_utf8_lossy(Vec::from(self.day).as_slice())
106            .trim_end()
107            .to_string();
108
109        write!(f, "Month: {month}\nDay: {day}\nYear: {year}")
110    }
111}
112
113impl PartialEq for Date {
114    fn eq(&self, other: &Self) -> bool {
115        self.date.year == other.date.year
116            && self.date.month == other.date.month
117            && self.date.day == other.date.day
118    }
119}
120
121impl Eq for Date {}
122
123#[derive(Debug, Copy, Clone, PartialEq, Eq)]
124#[repr(transparent)]
125/// Unsigned value, at least 32 bits long
126pub struct Ulong {
127    val: CK_ULONG,
128}
129
130impl Ulong {
131    /// Create a new variable
132    #[must_use]
133    pub const fn new(ulong: CK_ULONG) -> Self {
134        Ulong { val: ulong }
135    }
136}
137
138impl Deref for Ulong {
139    type Target = CK_ULONG;
140
141    fn deref(&self) -> &Self::Target {
142        &self.val
143    }
144}
145
146impl From<Ulong> for CK_ULONG {
147    fn from(ulong: Ulong) -> Self {
148        *ulong
149    }
150}
151
152impl From<CK_ULONG> for Ulong {
153    fn from(ulong: CK_ULONG) -> Self {
154        Ulong { val: ulong }
155    }
156}
157
158impl TryFrom<usize> for Ulong {
159    type Error = Error;
160
161    fn try_from(ulong: usize) -> Result<Self> {
162        Ok(Ulong {
163            val: ulong.try_into()?,
164        })
165    }
166}
167
168impl From<Ulong> for usize {
169    fn from(ulong: Ulong) -> Self {
170        ulong.val as usize
171    }
172}
173
174impl std::fmt::Display for Ulong {
175    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
176        write!(f, "{}", self.val)
177    }
178}
179
180#[derive(Debug, Copy, Clone, PartialEq, Eq)]
181/// Represents a version
182pub struct Version {
183    major: CK_BYTE,
184    minor: CK_BYTE,
185}
186
187impl std::fmt::Display for Version {
188    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
189        write!(f, "{}.{}", self.major, self.minor)
190    }
191}
192
193impl Version {
194    /// Construct a new version
195    pub(crate) fn new(major: u8, minor: u8) -> Self {
196        Self { major, minor }
197    }
198
199    /// Returns the major version
200    pub fn major(&self) -> CK_BYTE {
201        self.major
202    }
203
204    /// Returns the minor version
205    pub fn minor(&self) -> CK_BYTE {
206        self.minor
207    }
208}
209
210impl From<Version> for CK_VERSION {
211    fn from(version: Version) -> Self {
212        CK_VERSION {
213            major: version.major,
214            minor: version.minor,
215        }
216    }
217}
218
219impl From<CK_VERSION> for Version {
220    fn from(version: CK_VERSION) -> Self {
221        Version {
222            major: version.major,
223            minor: version.minor,
224        }
225    }
226}
227
228/// A UTC datetime returned by a token's clock if present.
229#[derive(Copy, Clone, Debug)]
230pub struct UtcTime {
231    /// **[Conformance](crate#conformance-notes): **
232    /// Guaranteed to be in range 0..=9999
233    pub year: u16,
234    /// **[Conformance](crate#conformance-notes): **
235    /// Guaranteed to be in range 0..=99
236    pub month: u8,
237    /// **[Conformance](crate#conformance-notes): **
238    /// Guaranteed to be in range 0..=99
239    pub day: u8,
240    /// **[Conformance](crate#conformance-notes): **
241    /// Guaranteed to be in range 0..=99
242    pub hour: u8,
243    /// **[Conformance](crate#conformance-notes): **
244    /// Guaranteed to be in range 0..=99
245    pub minute: u8,
246    /// **[Conformance](crate#conformance-notes): **
247    /// Guaranteed to be in range 0..=99
248    pub second: u8,
249}
250
251impl UtcTime {
252    /// Stringify the structure in ISO 8601 format.
253    ///
254    /// PKCS#11 and ISO are unrelated standards, and this function is provided
255    /// only for convenience. ISO format is more widely recognized and parsable
256    /// by various date/time utilities, while PKCS#11's internal representation
257    /// of this type is not used elsewhere.
258    /// Other than formatting, this crate does not guarantee or enforce any part
259    /// of the ISO standard.
260    pub fn as_iso8601_string(&self) -> String {
261        format!(
262            "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z",
263            self.year, self.month, self.day, self.hour, self.minute, self.second
264        )
265    }
266}
267
268// UTC time has the format YYYYMMDDhhmmss00 as ASCII digits
269pub(crate) fn convert_utc_time(orig: [u8; 16]) -> Result<UtcTime> {
270    // Note: No validation of these values beyond being ASCII digits
271    // because PKCS#11 doesn't impose any such restrictions.
272    Ok(UtcTime {
273        year: std::str::from_utf8(&orig[0..4])?.parse()?,
274        month: std::str::from_utf8(&orig[4..6])?.parse()?,
275        day: std::str::from_utf8(&orig[6..8])?.parse()?,
276        hour: std::str::from_utf8(&orig[8..10])?.parse()?,
277        minute: std::str::from_utf8(&orig[10..12])?.parse()?,
278        second: std::str::from_utf8(&orig[12..14])?.parse()?,
279    })
280}
281
282/// Secret wrapper for a Pin
283///
284/// Enable the `serde` feature to add support for Deserialize
285pub type AuthPin = SecretString;
286
287/// Secret wrapper for a raw non UTF-8 Pin
288///
289/// Enable the `serde` feature to add support for Deserialize
290pub type RawAuthPin = SecretBox<Vec<u8>>;
291
292#[cfg(test)]
293mod test {
294    use super::*;
295    const UTC_TIME: UtcTime = UtcTime {
296        year: 1970,
297        month: 1,
298        day: 1,
299        hour: 0,
300        minute: 0,
301        second: 0,
302    };
303
304    #[test]
305    fn utc_time_convert_good() {
306        let valid: [u8; 16] = [
307            0x31, 0x39, 0x37, 0x30, 0x30, 0x31, 0x30, 0x31, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30,
308            0x30, 0x30,
309        ];
310        let valid = convert_utc_time(valid).unwrap();
311        assert_eq!(valid.year, UTC_TIME.year);
312        assert_eq!(valid.month, UTC_TIME.month);
313        assert_eq!(valid.day, UTC_TIME.day);
314        assert_eq!(valid.hour, UTC_TIME.hour);
315        assert_eq!(valid.minute, UTC_TIME.minute);
316        assert_eq!(valid.second, UTC_TIME.second);
317    }
318
319    #[test]
320    fn utc_time_convert_bad() {
321        // Year starts with a non-numeric value ('A')
322        let invalid: [u8; 16] = [
323            0x41, 0x39, 0x37, 0x30, 0x30, 0x31, 0x30, 0x31, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30,
324            0x30, 0x30,
325        ];
326        let invalid = convert_utc_time(invalid);
327        assert!(invalid.is_err());
328    }
329
330    #[test]
331    fn utc_time_debug_fmt() {
332        let expected = r#"UtcTime {
333    year: 1970,
334    month: 1,
335    day: 1,
336    hour: 0,
337    minute: 0,
338    second: 0,
339}"#;
340        let observed = format!("{UTC_TIME:#?}");
341        assert_eq!(observed, expected);
342    }
343    #[test]
344    fn utc_time_display_fmt() {
345        let iso_format = UTC_TIME.as_iso8601_string();
346        assert_eq!(&iso_format, "1970-01-01T00:00:00Z");
347    }
348}