Skip to main content

pkcs11_abi/
tables.rs

1//! Compile-time tables mapping function field names to their byte offsets
2//! within CK_FUNCTION_LIST, CK_FUNCTION_LIST_3_0, and CK_FUNCTION_LIST_3_2.
3//!
4//! These native-layout tables support bounds-checked snapshot reads and NULL
5//! function-pointer detection without manual field-by-field code.
6
7use cryptoki_sys::*;
8
9use crate::layout::{Provenance, Selection, Version, function_catalog, select};
10
11/// A (field_name, byte_offset) pair for a function pointer field.
12#[derive(Debug)]
13pub struct FnField {
14    pub name: &'static str,
15    pub offset: usize,
16}
17
18macro_rules! fn_fields {
19    ($struct_type:ty, [$( $field:ident,)*]) => {
20        &[$(
21            FnField {
22                name: stringify!($field),
23                offset: std::mem::offset_of!($struct_type, $field),
24            },
25        )*]
26    };
27}
28
29macro_rules! define_native_fields {
30    (base [$($base:ident,)*] v3_0 [$($v3:ident,)*] v3_2 [$($v32:ident,)*]) => {
31        /// All 68 native `CK_FUNCTION_LIST` function fields.
32        pub static FUNCTION_LIST_FIELDS: &[FnField] =
33            fn_fields!(CK_FUNCTION_LIST, [$($base,)*]);
34        /// The 24 native `CK_FUNCTION_LIST_3_0` additions.
35        pub static FUNCTION_LIST_3_0_EXTRA_FIELDS: &[FnField] =
36            fn_fields!(CK_FUNCTION_LIST_3_0, [$($v3,)*]);
37        /// The 12 native `CK_FUNCTION_LIST_3_2` additions.
38        pub static FUNCTION_LIST_3_2_EXTRA_FIELDS: &[FnField] =
39            fn_fields!(CK_FUNCTION_LIST_3_2, [$($v32,)*]);
40    };
41}
42function_catalog!(define_native_fields);
43
44/// Check a function list struct for NULL function pointers.
45///
46/// # Safety
47/// `base` must point to a valid, live struct of the type that `fields`
48/// was generated from. The struct must remain valid for the duration
49/// of this call.
50pub unsafe fn detect_null_functions(base: *const u8, fields: &[FnField]) -> Vec<String> {
51    let mut nulls = Vec::new();
52    for field in fields {
53        // Each function pointer field is `Option<unsafe extern "C" fn(...)>`,
54        // which is pointer-sized. A None value is all-zero bytes. read_unaligned:
55        // on the packed Windows-MSVC cryptoki-sys bindings these fields start at
56        // offset 2 (after CK_VERSION), where an aligned read is UB.
57        let ptr_val = unsafe { (base.add(field.offset) as *const usize).read_unaligned() };
58        if ptr_val == 0 {
59            nulls.push(field.name.to_string());
60        }
61    }
62    nulls
63}
64
65/// Read every function-pointer field from an owned table snapshot.
66pub fn read_fn_pointers(
67    bytes: &[u8],
68    fields: &[FnField],
69) -> Result<Vec<(&'static str, usize)>, String> {
70    let width = std::mem::size_of::<usize>();
71    fields
72        .iter()
73        .map(|field| {
74            let end = field
75                .offset
76                .checked_add(width)
77                .ok_or_else(|| format!("{} offset overflows", field.name))?;
78            let src = bytes.get(field.offset..end).ok_or_else(|| {
79                format!(
80                    "{} needs bytes {}..{end}, snapshot has {}",
81                    field.name,
82                    field.offset,
83                    bytes.len()
84                )
85            })?;
86            let mut raw = [0u8; std::mem::size_of::<usize>()];
87            raw.copy_from_slice(src);
88            Ok((field.name, usize::from_ne_bytes(raw)))
89        })
90        .collect()
91}
92
93/// Caller-asserted origin and reported version of a function table.
94///
95/// This value determines which fields [`tables_for`] permits a caller to walk.
96/// It does not validate the pointer, authenticate the origin, or prove that an
97/// interface is standard-shaped; callers must establish those properties.
98#[derive(Debug, Clone, Copy)]
99pub enum Surface {
100    /// Obtained via `C_GetFunctionList`, with its bounded-read version.
101    LegacyFunctionList { version: cryptoki_sys::CK_VERSION },
102    /// A standard or independently corroborated standard-shaped interface,
103    /// with its bounded-read reported version.
104    StandardInterface { version: cryptoki_sys::CK_VERSION },
105}
106
107/// A prefix of one shared field table. The 2.00 ABI reuses the first 67
108/// entries of the 68-entry base table instead of copying their names.
109#[derive(Debug, Clone, Copy)]
110pub struct TableSpan {
111    fields: &'static [FnField],
112    len: usize,
113}
114
115impl TableSpan {
116    pub fn fields(&self) -> &'static [FnField] {
117        &self.fields[..self.len]
118    }
119}
120
121/// The tables that may be walked over a surface, in walk order.
122#[derive(Debug, Clone, Copy)]
123pub enum TableSet {
124    Walk(&'static [TableSpan]),
125    /// Only the listed prefix is supported by the asserted surface/version.
126    /// This includes legacy 3.x versions newer than 3.2, unknown 2.x minors,
127    /// and standard interfaces newer than 3.2. Do not infer or walk fields
128    /// beyond this prefix.
129    WalkKnownPrefix(&'static [TableSpan]),
130    /// Unknown major/layout: record, walk nothing.
131    Refuse,
132}
133
134static V2_00: &[TableSpan] = &[TableSpan { fields: FUNCTION_LIST_FIELDS, len: 67 }];
135static BASE: &[TableSpan] =
136    &[TableSpan { fields: FUNCTION_LIST_FIELDS, len: FUNCTION_LIST_FIELDS.len() }];
137static V3_0: &[TableSpan] = &[
138    TableSpan { fields: FUNCTION_LIST_FIELDS, len: FUNCTION_LIST_FIELDS.len() },
139    TableSpan { fields: FUNCTION_LIST_3_0_EXTRA_FIELDS, len: FUNCTION_LIST_3_0_EXTRA_FIELDS.len() },
140];
141static V3_2: &[TableSpan] = &[
142    TableSpan { fields: FUNCTION_LIST_FIELDS, len: FUNCTION_LIST_FIELDS.len() },
143    TableSpan { fields: FUNCTION_LIST_3_0_EXTRA_FIELDS, len: FUNCTION_LIST_3_0_EXTRA_FIELDS.len() },
144    TableSpan { fields: FUNCTION_LIST_3_2_EXTRA_FIELDS, len: FUNCTION_LIST_3_2_EXTRA_FIELDS.len() },
145];
146
147/// Select the native field-table spans that are safe for the asserted surface.
148pub fn tables_for(surface: Surface) -> TableSet {
149    let (provenance, version) = match surface {
150        Surface::LegacyFunctionList { version } => (Provenance::LegacyFunctionList, version),
151        Surface::StandardInterface { version } => (Provenance::StandardInterface, version),
152    };
153    match select(provenance, Version { major: version.major, minor: version.minor }) {
154        Selection::Exact(67) => TableSet::Walk(V2_00),
155        Selection::Exact(68) => TableSet::Walk(BASE),
156        Selection::Exact(92) => TableSet::Walk(V3_0),
157        Selection::Exact(104) => TableSet::Walk(V3_2),
158        Selection::KnownPrefix(68) => TableSet::WalkKnownPrefix(BASE),
159        Selection::KnownPrefix(104) => TableSet::WalkKnownPrefix(V3_2),
160        Selection::Exact(_) | Selection::KnownPrefix(_) | Selection::Refuse => TableSet::Refuse,
161    }
162}
163
164#[cfg(test)]
165mod tests {
166    use super::*;
167
168    /// A byte buffer standing in for a CK_FUNCTION_LIST: one non-NULL slot
169    /// written at the C_Initialize offset, everything else zero.
170    fn fake_base_table() -> Vec<u8> {
171        let mut buf = vec![0u8; std::mem::size_of::<cryptoki_sys::CK_FUNCTION_LIST>()];
172        let off = FUNCTION_LIST_FIELDS[0].offset; // C_Initialize
173        buf[off..off + std::mem::size_of::<usize>()]
174            .copy_from_slice(&0xDEAD_BEEFusize.to_ne_bytes());
175        buf
176    }
177
178    #[test]
179    fn detect_null_functions_reports_all_but_the_set_slot() {
180        let buf = fake_base_table();
181        let nulls = unsafe { detect_null_functions(buf.as_ptr(), FUNCTION_LIST_FIELDS) };
182        assert!(!nulls.contains(&"C_Initialize".to_string()));
183        assert_eq!(nulls.len(), FUNCTION_LIST_FIELDS.len() - 1);
184    }
185
186    #[test]
187    fn read_fn_pointers_returns_names_with_values() {
188        let buf = fake_base_table();
189        let ptrs = read_fn_pointers(&buf, FUNCTION_LIST_FIELDS).unwrap();
190        assert_eq!(ptrs.len(), FUNCTION_LIST_FIELDS.len());
191        assert_eq!(ptrs[0], ("C_Initialize", 0xDEAD_BEEF));
192        assert!(ptrs[1..].iter().all(|(_, v)| *v == 0));
193    }
194
195    #[test]
196    fn read_fn_pointers_rejects_a_short_snapshot() {
197        let last = FUNCTION_LIST_FIELDS.last().unwrap();
198        let short = vec![0u8; last.offset + std::mem::size_of::<usize>() - 1];
199        let err = read_fn_pointers(&short, FUNCTION_LIST_FIELDS).unwrap_err();
200        assert!(err.contains("C_WaitForSlotEvent"), "unexpected error: {err}");
201    }
202
203    #[test]
204    fn table_sizes_match_the_documented_counts() {
205        assert_eq!(FUNCTION_LIST_FIELDS.len(), 68);
206        assert_eq!(FUNCTION_LIST_3_0_EXTRA_FIELDS.len(), 24);
207        assert_eq!(FUNCTION_LIST_3_2_EXTRA_FIELDS.len(), 12);
208    }
209
210    #[cfg(target_os = "linux")]
211    #[test]
212    fn every_native_name_and_offset_matches_the_linux_catalog() {
213        let layout = if cfg!(target_pointer_width = "64") {
214            crate::layout::LinuxLayout::Lp64
215        } else {
216            crate::layout::LinuxLayout::Ilp32
217        };
218        let fields = FUNCTION_LIST_FIELDS
219            .iter()
220            .chain(FUNCTION_LIST_3_0_EXTRA_FIELDS)
221            .chain(FUNCTION_LIST_3_2_EXTRA_FIELDS);
222        for (ordinal, field) in fields.enumerate() {
223            assert_eq!(field.name, crate::layout::function_name(ordinal).unwrap());
224            assert_eq!(
225                field.offset,
226                crate::layout::function_offset(layout, ordinal).unwrap(),
227                "{}",
228                field.name
229            );
230        }
231
232        let interface = layout.interface();
233        assert_eq!(
234            interface.name_offset,
235            std::mem::offset_of!(cryptoki_sys::CK_INTERFACE, pInterfaceName)
236        );
237        assert_eq!(
238            interface.function_list_offset,
239            std::mem::offset_of!(cryptoki_sys::CK_INTERFACE, pFunctionList)
240        );
241        assert_eq!(interface.flags_offset, std::mem::offset_of!(cryptoki_sys::CK_INTERFACE, flags));
242        assert_eq!(interface.stride, std::mem::size_of::<cryptoki_sys::CK_INTERFACE>());
243    }
244
245    fn std_iface(major: u8, minor: u8) -> Surface {
246        Surface::StandardInterface { version: cryptoki_sys::CK_VERSION { major, minor } }
247    }
248
249    fn walked(set: TableSet) -> Vec<*const FnField> {
250        match set {
251            TableSet::Walk(s) | TableSet::WalkKnownPrefix(s) => {
252                s.iter().map(|span| span.fields().as_ptr()).collect()
253            }
254            TableSet::Refuse => Vec::new(),
255        }
256    }
257
258    fn field_count(set: TableSet) -> usize {
259        match set {
260            TableSet::Walk(spans) | TableSet::WalkKnownPrefix(spans) => {
261                spans.iter().map(|span| span.fields().len()).sum()
262            }
263            TableSet::Refuse => 0,
264        }
265    }
266
267    #[test]
268    fn legacy_200_walks_67_fields_and_201_walks_68() {
269        let legacy = |minor| Surface::LegacyFunctionList {
270            version: cryptoki_sys::CK_VERSION { major: 2, minor },
271        };
272        assert_eq!(field_count(tables_for(legacy(0))), 67);
273        assert_eq!(field_count(tables_for(legacy(1))), 68);
274    }
275
276    #[test]
277    fn every_published_later_legacy_revision_walks_68_fields() {
278        for minor in [10, 11, 20, 30, 40] {
279            let set = tables_for(Surface::LegacyFunctionList {
280                version: cryptoki_sys::CK_VERSION { major: 2, minor },
281            });
282            assert!(matches!(set, TableSet::Walk(_)), "2.{minor:02} must be exact");
283            assert_eq!(field_count(set), 68, "2.{minor:02}");
284        }
285    }
286
287    #[test]
288    fn unpublished_later_legacy_versions_are_known_prefixes() {
289        for version in [
290            cryptoki_sys::CK_VERSION { major: 2, minor: 2 },
291            cryptoki_sys::CK_VERSION { major: 2, minor: 41 },
292            cryptoki_sys::CK_VERSION { major: 3, minor: 3 },
293            cryptoki_sys::CK_VERSION { major: 3, minor: 255 },
294        ] {
295            let set = tables_for(Surface::LegacyFunctionList { version });
296            assert!(matches!(set, TableSet::WalkKnownPrefix(_)), "{version:?}");
297            assert_eq!(field_count(set), 68, "{version:?}");
298        }
299    }
300
301    #[test]
302    fn legacy_unknown_majors_are_refused() {
303        for major in [0, 1, 4] {
304            assert!(matches!(
305                tables_for(Surface::LegacyFunctionList {
306                    version: cryptoki_sys::CK_VERSION { major, minor: 0 },
307                }),
308                TableSet::Refuse
309            ));
310        }
311    }
312
313    #[test]
314    fn legacy_30_through_32_walk_the_exact_base() {
315        for minor in [0, 1, 2] {
316            let set = tables_for(Surface::LegacyFunctionList {
317                version: cryptoki_sys::CK_VERSION { major: 3, minor },
318            });
319            assert!(matches!(set, TableSet::Walk(_)), "3.{minor} must be exact");
320            assert_eq!(walked(set), vec![FUNCTION_LIST_FIELDS.as_ptr()], "3.{minor}");
321            assert_eq!(field_count(set), 68, "3.{minor}");
322        }
323    }
324
325    #[test]
326    fn standard_240_walks_base_and_other_2x_is_refused() {
327        let set = tables_for(std_iface(2, 40));
328        assert!(matches!(set, TableSet::Walk(_)));
329        assert_eq!(walked(set), vec![FUNCTION_LIST_FIELDS.as_ptr()]);
330        // This structure is defined for version 0x02/0x28 (2.40);
331        // an older 2.x table is not guaranteed to contain the full 2.40 tail.
332        assert!(matches!(tables_for(std_iface(2, 30)), TableSet::Refuse));
333        assert!(matches!(tables_for(std_iface(2, 20)), TableSet::Refuse));
334    }
335
336    #[test]
337    fn standard_30_and_31_walk_base_plus_30() {
338        for minor in [0, 1] {
339            let set = tables_for(std_iface(3, minor));
340            assert!(matches!(set, TableSet::Walk(_)));
341            assert_eq!(
342                walked(set),
343                vec![FUNCTION_LIST_FIELDS.as_ptr(), FUNCTION_LIST_3_0_EXTRA_FIELDS.as_ptr()],
344            );
345        }
346    }
347
348    #[test]
349    fn standard_32_walks_all_three() {
350        let set = tables_for(std_iface(3, 2));
351        assert!(matches!(set, TableSet::Walk(_)));
352        assert_eq!(
353            walked(set),
354            vec![
355                FUNCTION_LIST_FIELDS.as_ptr(),
356                FUNCTION_LIST_3_0_EXTRA_FIELDS.as_ptr(),
357                FUNCTION_LIST_3_2_EXTRA_FIELDS.as_ptr(),
358            ],
359        );
360    }
361
362    #[test]
363    fn standard_3_minor_above_2_walks_known_prefix() {
364        let set = tables_for(std_iface(3, 3));
365        assert!(matches!(set, TableSet::WalkKnownPrefix(_)));
366        assert_eq!(
367            walked(set),
368            vec![
369                FUNCTION_LIST_FIELDS.as_ptr(),
370                FUNCTION_LIST_3_0_EXTRA_FIELDS.as_ptr(),
371                FUNCTION_LIST_3_2_EXTRA_FIELDS.as_ptr(),
372            ],
373        );
374    }
375
376    #[test]
377    fn unknown_majors_are_refused() {
378        assert!(matches!(tables_for(std_iface(4, 0)), TableSet::Refuse));
379        assert!(matches!(tables_for(std_iface(1, 0)), TableSet::Refuse));
380        assert!(matches!(tables_for(std_iface(0, 0)), TableSet::Refuse));
381    }
382}