Skip to main content

pkcs11_abi/
layout.rs

1//! Allocation-free PKCS#11 function-table layout facts for Linux LP64 and ILP32.
2//!
3//! These operations describe target memory. They do not depend on the observer's
4//! pointer width and do not select or dereference a provider interface.
5
6/// The single ordered catalog of standard function-list fields.
7macro_rules! function_catalog {
8    ($consumer:ident) => {
9        $consumer! {
10            base [
11            C_Initialize,
12            C_Finalize,
13            C_GetInfo,
14            C_GetFunctionList,
15            C_GetSlotList,
16            C_GetSlotInfo,
17            C_GetTokenInfo,
18            C_GetMechanismList,
19            C_GetMechanismInfo,
20            C_InitToken,
21            C_InitPIN,
22            C_SetPIN,
23            C_OpenSession,
24            C_CloseSession,
25            C_CloseAllSessions,
26            C_GetSessionInfo,
27            C_GetOperationState,
28            C_SetOperationState,
29            C_Login,
30            C_Logout,
31            C_CreateObject,
32            C_CopyObject,
33            C_DestroyObject,
34            C_GetObjectSize,
35            C_GetAttributeValue,
36            C_SetAttributeValue,
37            C_FindObjectsInit,
38            C_FindObjects,
39            C_FindObjectsFinal,
40            C_EncryptInit,
41            C_Encrypt,
42            C_EncryptUpdate,
43            C_EncryptFinal,
44            C_DecryptInit,
45            C_Decrypt,
46            C_DecryptUpdate,
47            C_DecryptFinal,
48            C_DigestInit,
49            C_Digest,
50            C_DigestUpdate,
51            C_DigestKey,
52            C_DigestFinal,
53            C_SignInit,
54            C_Sign,
55            C_SignUpdate,
56            C_SignFinal,
57            C_SignRecoverInit,
58            C_SignRecover,
59            C_VerifyInit,
60            C_Verify,
61            C_VerifyUpdate,
62            C_VerifyFinal,
63            C_VerifyRecoverInit,
64            C_VerifyRecover,
65            C_DigestEncryptUpdate,
66            C_DecryptDigestUpdate,
67            C_SignEncryptUpdate,
68            C_DecryptVerifyUpdate,
69            C_GenerateKey,
70            C_GenerateKeyPair,
71            C_WrapKey,
72            C_UnwrapKey,
73            C_DeriveKey,
74            C_SeedRandom,
75            C_GenerateRandom,
76            C_GetFunctionStatus,
77            C_CancelFunction,
78            C_WaitForSlotEvent,
79            ]
80            v3_0 [
81            C_GetInterfaceList,
82            C_GetInterface,
83            C_LoginUser,
84            C_SessionCancel,
85            C_MessageEncryptInit,
86            C_EncryptMessage,
87            C_EncryptMessageBegin,
88            C_EncryptMessageNext,
89            C_MessageEncryptFinal,
90            C_MessageDecryptInit,
91            C_DecryptMessage,
92            C_DecryptMessageBegin,
93            C_DecryptMessageNext,
94            C_MessageDecryptFinal,
95            C_MessageSignInit,
96            C_SignMessage,
97            C_SignMessageBegin,
98            C_SignMessageNext,
99            C_MessageSignFinal,
100            C_MessageVerifyInit,
101            C_VerifyMessage,
102            C_VerifyMessageBegin,
103            C_VerifyMessageNext,
104            C_MessageVerifyFinal,
105            ]
106            v3_2 [
107            C_EncapsulateKey,
108            C_DecapsulateKey,
109            C_VerifySignatureInit,
110            C_VerifySignature,
111            C_VerifySignatureUpdate,
112            C_VerifySignatureFinal,
113            C_GetSessionValidationFlags,
114            C_AsyncComplete,
115            C_AsyncGetID,
116            C_AsyncJoin,
117            C_WrapKeyAuthenticated,
118            C_UnwrapKeyAuthenticated,
119            ]
120        }
121    };
122}
123pub(crate) use function_catalog;
124
125macro_rules! define_names {
126    (base [$($base:ident,)*] v3_0 [$($v3:ident,)*] v3_2 [$($v32:ident,)*]) => {
127        /// All standard function names in table order. The slice index is the ordinal.
128        pub static FUNCTION_NAMES: &[&str] = &[
129            $(stringify!($base),)*
130            $(stringify!($v3),)*
131            $(stringify!($v32),)*
132        ];
133    };
134}
135function_catalog!(define_names);
136
137/// A supported little-endian Linux PKCS#11 data model.
138#[derive(Debug, Clone, Copy, PartialEq, Eq)]
139pub enum LinuxLayout {
140    Lp64,
141    Ilp32,
142}
143
144impl LinuxLayout {
145    /// Size in bytes of a pointer and `CK_ULONG` in this data model.
146    pub const fn word_bytes(self) -> usize {
147        match self {
148            Self::Lp64 => 8,
149            Self::Ilp32 => 4,
150        }
151    }
152
153    const fn function_base(self) -> usize {
154        self.word_bytes()
155    }
156
157    /// Layout of one `CK_INTERFACE` entry: name pointer, function-list pointer, flags.
158    pub const fn interface(self) -> InterfaceLayout {
159        let width = self.word_bytes();
160        InterfaceLayout {
161            name_offset: 0,
162            function_list_offset: width,
163            flags_offset: width * 2,
164            stride: width * 3,
165        }
166    }
167}
168
169/// Byte offsets and total stride of one `CK_INTERFACE` entry.
170#[derive(Debug, Clone, Copy, PartialEq, Eq)]
171pub struct InterfaceLayout {
172    pub name_offset: usize,
173    pub function_list_offset: usize,
174    pub flags_offset: usize,
175    pub stride: usize,
176}
177
178/// Failure while calculating or reading a target layout.
179#[derive(Debug, Clone, Copy, PartialEq, Eq)]
180pub enum LayoutError {
181    FieldOutOfRange,
182    OffsetOverflow,
183    Truncated,
184}
185
186/// Return the name for an ordinal in the shared 104-field catalog.
187pub fn function_name(ordinal: usize) -> Option<&'static str> {
188    FUNCTION_NAMES.get(ordinal).copied()
189}
190
191/// Return a target byte offset for a function-pointer ordinal.
192pub fn function_offset(layout: LinuxLayout, ordinal: usize) -> Result<usize, LayoutError> {
193    if ordinal >= FUNCTION_NAMES.len() {
194        return Err(LayoutError::FieldOutOfRange);
195    }
196    ordinal
197        .checked_mul(layout.word_bytes())
198        .and_then(|n| layout.function_base().checked_add(n))
199        .ok_or(LayoutError::OffsetOverflow)
200}
201
202/// Return the exact target bytes occupied by a known function-list prefix.
203pub fn table_bytes(layout: LinuxLayout, fields: usize) -> Result<usize, LayoutError> {
204    if fields > FUNCTION_NAMES.len() {
205        return Err(LayoutError::FieldOutOfRange);
206    }
207    fields
208        .checked_mul(layout.word_bytes())
209        .and_then(|n| layout.function_base().checked_add(n))
210        .ok_or(LayoutError::OffsetOverflow)
211}
212
213/// Read one complete little-endian target word, zero-extending ILP32 words to `u64`.
214pub fn read_word_le(bytes: &[u8], layout: LinuxLayout, offset: usize) -> Result<u64, LayoutError> {
215    let end = offset.checked_add(layout.word_bytes()).ok_or(LayoutError::OffsetOverflow)?;
216    let word = bytes.get(offset..end).ok_or(LayoutError::Truncated)?;
217    Ok(match layout {
218        LinuxLayout::Lp64 => {
219            u64::from_le_bytes(word.try_into().map_err(|_| LayoutError::Truncated)?)
220        }
221        LinuxLayout::Ilp32 => {
222            u32::from_le_bytes(word.try_into().map_err(|_| LayoutError::Truncated)?) as u64
223        }
224    })
225}
226
227/// Read a complete function pointer by ordinal from a target snapshot.
228pub fn read_function_pointer(
229    bytes: &[u8],
230    layout: LinuxLayout,
231    ordinal: usize,
232) -> Result<u64, LayoutError> {
233    read_word_le(bytes, layout, function_offset(layout, ordinal)?)
234}
235
236/// A PKCS#11 major/minor version used for table-prefix selection.
237#[derive(Debug, Clone, Copy, PartialEq, Eq)]
238pub struct Version {
239    pub major: u8,
240    pub minor: u8,
241}
242
243/// Caller-asserted route by which a function table was obtained.
244#[derive(Debug, Clone, Copy, PartialEq, Eq)]
245pub enum Provenance {
246    LegacyFunctionList,
247    StandardInterface,
248}
249
250/// Result of selecting the safely understood portion of a function table.
251#[derive(Debug, Clone, Copy, PartialEq, Eq)]
252pub enum Selection {
253    /// The complete reported layout is known and contains this many fields.
254    Exact(usize),
255    /// This many leading fields are known; later fields must not be read.
256    KnownPrefix(usize),
257    /// The version/provenance combination is not safe to inspect.
258    Refuse,
259}
260
261/// Bind validated version and provenance to the safe function-list prefix.
262pub const fn select(provenance: Provenance, version: Version) -> Selection {
263    match provenance {
264        Provenance::LegacyFunctionList => match (version.major, version.minor) {
265            (2, 0) => Selection::Exact(67),
266            (2, 1 | 10 | 11 | 20 | 30 | 40) => Selection::Exact(68),
267            // OASIS PKCS#11 v3.2 keeps CK_FUNCTION_LIST at the 68-slot
268            // 2.40 layout (it ends at C_WaitForSlotEvent); longer tables
269            // arrive only via C_GetInterfaceList/C_GetInterface. A legacy
270            // list stamped 3.0 through 3.2 is exactly those 68 slots.
271            (3, 0..=2) => Selection::Exact(68),
272            (2, _) | (3, _) => Selection::KnownPrefix(68),
273            _ => Selection::Refuse,
274        },
275        Provenance::StandardInterface => match (version.major, version.minor) {
276            (2, 40) => Selection::Exact(68),
277            (2, _) => Selection::Refuse,
278            (3, 0) | (3, 1) => Selection::Exact(92),
279            (3, 2) => Selection::Exact(104),
280            (3, _) => Selection::KnownPrefix(104),
281            _ => Selection::Refuse,
282        },
283    }
284}
285
286#[cfg(test)]
287mod tests {
288    use super::*;
289
290    #[test]
291    fn catalog_has_104_unique_ordered_names() {
292        assert_eq!(FUNCTION_NAMES.len(), 104);
293        for (ordinal, name) in FUNCTION_NAMES.iter().enumerate() {
294            assert!(!FUNCTION_NAMES[..ordinal].contains(name), "duplicate {name}");
295        }
296        assert_eq!(function_name(0), Some("C_Initialize"));
297        assert_eq!(function_name(67), Some("C_WaitForSlotEvent"));
298        assert_eq!(function_name(68), Some("C_GetInterfaceList"));
299        assert_eq!(function_name(91), Some("C_MessageVerifyFinal"));
300        assert_eq!(function_name(92), Some("C_EncapsulateKey"));
301        assert_eq!(function_name(103), Some("C_UnwrapKeyAuthenticated"));
302        assert_eq!(function_name(104), None);
303    }
304
305    #[test]
306    fn linux_prefix_sizes_and_offsets_are_checked() {
307        for (layout, expected) in
308            [(LinuxLayout::Lp64, [544, 552, 744, 840]), (LinuxLayout::Ilp32, [272, 276, 372, 420])]
309        {
310            for (fields, bytes) in [67, 68, 92, 104].into_iter().zip(expected) {
311                assert_eq!(table_bytes(layout, fields), Ok(bytes));
312            }
313            assert_eq!(function_offset(layout, 0), Ok(layout.word_bytes()));
314            assert_eq!(function_offset(layout, 103), Ok(expected[3] - layout.word_bytes()));
315        }
316        assert_eq!(function_offset(LinuxLayout::Lp64, 104), Err(LayoutError::FieldOutOfRange));
317        assert_eq!(table_bytes(LinuxLayout::Ilp32, 105), Err(LayoutError::FieldOutOfRange));
318    }
319
320    #[test]
321    fn reads_only_complete_words_and_zero_extends_ilp32() {
322        let bytes = [0, 0, 0, 0, 0x78, 0x56, 0x34, 0xF2];
323        assert_eq!(read_function_pointer(&bytes, LinuxLayout::Ilp32, 0), Ok(0xF234_5678));
324        assert_eq!(read_word_le(&bytes[..7], LinuxLayout::Ilp32, 4), Err(LayoutError::Truncated));
325        assert_eq!(
326            read_word_le(&[], LinuxLayout::Lp64, usize::MAX),
327            Err(LayoutError::OffsetOverflow)
328        );
329
330        for layout in [LinuxLayout::Lp64, LinuxLayout::Ilp32] {
331            let len = table_bytes(layout, 104).unwrap();
332            let mut table = [0u8; 840];
333            let last = function_offset(layout, 103).unwrap();
334            table[last..len].copy_from_slice(&[1, 2, 3, 4, 5, 6, 7, 8][..layout.word_bytes()]);
335            let expected = match layout {
336                LinuxLayout::Lp64 => 0x0807_0605_0403_0201,
337                LinuxLayout::Ilp32 => 0x0403_0201,
338            };
339            assert_eq!(read_function_pointer(&table[..len], layout, 103), Ok(expected));
340            assert_eq!(
341                read_function_pointer(&table[..len - 1], layout, 103),
342                Err(LayoutError::Truncated)
343            );
344        }
345    }
346
347    #[test]
348    fn interface_layout_is_target_sized() {
349        assert_eq!(
350            LinuxLayout::Ilp32.interface(),
351            InterfaceLayout {
352                name_offset: 0,
353                function_list_offset: 4,
354                flags_offset: 8,
355                stride: 12
356            }
357        );
358        assert_eq!(
359            LinuxLayout::Lp64.interface(),
360            InterfaceLayout {
361                name_offset: 0,
362                function_list_offset: 8,
363                flags_offset: 16,
364                stride: 24
365            }
366        );
367    }
368
369    #[test]
370    fn version_and_provenance_boundaries_match_policy() {
371        assert_eq!(
372            select(Provenance::LegacyFunctionList, Version { major: 2, minor: 0 }),
373            Selection::Exact(67)
374        );
375        assert_eq!(
376            select(Provenance::LegacyFunctionList, Version { major: 2, minor: 40 }),
377            Selection::Exact(68)
378        );
379        for minor in [0, 1, 2] {
380            assert_eq!(
381                select(Provenance::LegacyFunctionList, Version { major: 3, minor }),
382                Selection::Exact(68),
383                "a legacy list stamped with published 3.{minor} is the frozen 68-slot layout"
384            );
385        }
386        assert_eq!(
387            select(Provenance::LegacyFunctionList, Version { major: 3, minor: 3 }),
388            Selection::KnownPrefix(68)
389        );
390        assert_eq!(
391            select(Provenance::StandardInterface, Version { major: 2, minor: 30 }),
392            Selection::Refuse
393        );
394        assert_eq!(
395            select(Provenance::StandardInterface, Version { major: 3, minor: 1 }),
396            Selection::Exact(92)
397        );
398        assert_eq!(
399            select(Provenance::StandardInterface, Version { major: 3, minor: 2 }),
400            Selection::Exact(104)
401        );
402        assert_eq!(
403            select(Provenance::StandardInterface, Version { major: 3, minor: 3 }),
404            Selection::KnownPrefix(104)
405        );
406        assert_eq!(
407            select(Provenance::StandardInterface, Version { major: 4, minor: 0 }),
408            Selection::Refuse
409        );
410    }
411}