sequoia_cryptoki/lib.rs
1//! A library for using cryptoki (PKCS#11) tokens from Sequoia.
2//!
3//! This library supports the use of cryptographic mechanisms via a
4//! [cryptoki (PKCS#11) interface] with Sequoia PGP. The cryptoki
5//! interface is usually implemented by a library that interfaces with
6//! a hardware token.
7//!
8//! [cryptoki (PKCS#11) interface]: https://docs.oasis-open.org/pkcs11/pkcs11-spec/v3.2/pkcs11-spec-v3.2.html
9//!
10//! This library is specifically not a generic interface to cryptoki
11//! tokens. Instead, it assumes that the user wants to use the tokens
12//! in an OpenPGP context. For instance, when generating or importing
13//! a key, the key's key ID is constructed in such a way that the
14//! OpenPGP parameters that cannot be inferred from the information
15//! stored on the token are encoded in the key ID. This allows
16//! reconstructing the public key packet and consequently the key's
17//! OpenPGP fingerprint using just data stored on the token.
18//!
19//! It is not currently possible to use a key whose key ID does not
20//! include the OpenPGP parameters. This means that you can't use a
21//! generic tool to generate the key, and then use that key with this
22//! library. This is usually a reasonable restriction, as key
23//! material should not be shared between different protocols.
24//!
25//! # Examples
26//!
27//! ## Iterate Over Keys
28//!
29//! The following code creates a default context and iterates over the
30//! available keys. The configuration file is read from the user's
31//! Sequoia home directory and respects the `SEQUOIA_HOME` environment
32//! variable. The configuration indicates what cryptoki modules to
33//! load.
34//!
35//! ```
36//! use sequoia_cryptoki::Context;
37//! # use sequoia_cryptoki::ContextBuilder;
38//!
39//! # fn main() -> sequoia_openpgp::Result<()> {
40//! # if false {
41//! let cryptoki = Context::new()?;
42//! # }
43//! # let cryptoki = ContextBuilder::new().disable_config_file().build()?;
44//! for key in cryptoki.keys()? {
45//! eprintln!("Key: {}",
46//! key.key_id()
47//! .map(|keyid| String::from_utf8_lossy(keyid))
48//! .unwrap_or_else(|| "missing key ID".into()));
49//! if let Ok(key) = key.to_openpgp_key() {
50//! eprintln!(" Fingerprint: {}", key.fingerprint());
51//! } else {
52//! eprintln!(" Not for OpenPGP");
53//! }
54//! }
55//! # Ok(()) }
56//! ```
57//!
58//! You can disable the use of the configuration file by using
59//! [`ContextBuilder::disable_config_file`] and then using
60//! [`ContextBuilder::add_module`] to specify what modules to load.
61//!
62//! ## Sign a Message
63//!
64//! The sample code signs a message using a specified key. We get a
65//! key descriptor (a [`Key`]), then use it to instantiate a
66//! [`Signer`]. We can do a similar thing to decrypt a message, but
67//! in that case we instantiate a [`Decryptor`].
68//!
69//! ```
70//! use sequoia_openpgp as openpgp;
71//! use openpgp::crypto::Password;
72//! use openpgp::packet::signature::SignatureBuilder;
73//! use openpgp::types::SignatureType;
74//! # use openpgp::Fingerprint;
75//!
76//! use sequoia_cryptoki::Context;
77//! use sequoia_cryptoki::Prompt;
78//! use sequoia_cryptoki::Signer;
79//! # use sequoia_cryptoki::ContextBuilder;
80//!
81//! # fn main() -> sequoia_openpgp::Result<()> {
82//! # let fpr: Fingerprint = "EC710462524581C4C3A5224A573784508844731C".parse().expect("valid fingerprint");
83//! #
84//! # if false {
85//! let cryptoki = Context::new()?;
86//! # }
87//! # let cryptoki = ContextBuilder::new().disable_config_file().build()?;
88//!
89//! // Get the first key with the specified fingerprint. Note:
90//! // there may be multiple keys with the same fingerprint, if the key
91//! // was copied.
92//! let mut key = None;
93//! for k in cryptoki.keys()? {
94//! if k.fingerprint().as_ref() == Some(&fpr) {
95//! key = Some(k);
96//! break;
97//! }
98//! }
99//!
100//! let Some(key) = key else {
101//! eprintln!("No token has a copy of {}.", fpr);
102//! # return Ok(());
103//! return Err(anyhow::anyhow!("Key not found"));
104//! };
105//!
106//! // Now, sign a message.
107//!
108//! // How to prompt the user for a password.
109//! struct Prompter;
110//! impl Prompt for Prompter {
111//! fn prompt_password(&self, _prompt: &str) -> anyhow::Result<Password> {
112//! Err(anyhow::anyhow!("Password prompting disabled").into())
113//! }
114//! }
115//!
116//! // Turn a `Key` into a `Signer`.
117//! let mut signer = Signer::new(Prompter, &key, None, None)?;
118//!
119//! let msg = b"Hello, world!";
120//! let mut sig = SignatureBuilder::new(SignatureType::Binary)
121//! .sign_message(&mut signer, msg)?;
122//! # Ok(()) }
123//! ```
124//!
125//! ## Find a Key
126//!
127//! This shows how to use a [`KeySelector`] to select a key by its key
128//! ID:
129//!
130//! ```
131//! use sequoia_cryptoki::Context;
132//! use sequoia_cryptoki::KeySelector;
133//! use sequoia_cryptoki::SelectorScope;
134//!
135//! # fn main() -> sequoia_openpgp::Result<()> {
136//! let cryptoki = Context::new()?;
137//! let mut selector = KeySelector::unconstrained();
138//! selector.key_id = Some("pgp:v4:eddsa:20251118T090408Z:scrap-heat-mouse".into());
139//! match cryptoki.select_one_key(&selector, SelectorScope::PublicKeys) {
140//! Ok(key) => {
141//! // ...
142//! }
143//! Err(err) => eprintln!("Key not found"),
144//! }
145//! # Ok(()) }
146//! ```
147//!
148//! It is also possible to search by unique ID, label and URL. If
149//! multiple constraints are specified, then only keys that match all
150//! of the constraints are returned.
151//!
152//! We can do something similar to search for tokens using
153//! [`Context::select_one_token`] and [`TokenSelector`].
154//!
155//! ## Import a Key
156//!
157//! This example shows how to import a key. We need to first get the
158//! token, which we find using [`Context::select_one_token`] (see the
159//! previous example). We then open a read-write user session. A
160//! session is similar to a transaction: it guarantees that the
161//! operations are atomic. A read-write session allows modifying the
162//! token, which is what we do when we generate or import a key.
163//! Finally, we import the key.
164//!
165//! ```
166//! use anyhow::Context as _;
167//! #
168//! # use sequoia_openpgp as openpgp;
169//! # use openpgp::cert::prelude::*;
170//!
171//! use sequoia_cryptoki::Context;
172//! use sequoia_cryptoki::TokenSelector;
173//! use sequoia_cryptoki::KeyCapability;
174//!
175//! # fn main() -> sequoia_openpgp::Result<()> {
176//! # let (cert, _) =
177//! # CertBuilder::general_purpose(Some("alice@example.org"))
178//! # .generate()?;
179//! // Import the primary key.
180//! let key = cert.primary_key().key()
181//! .parts_as_secret().context("No secret key material")?
182//! .role_as_unspecified();
183//!
184//! let cryptoki = Context::new()?;
185//!
186//! // Get the token that we want to import the key to.
187//! let mut selector = TokenSelector::unconstrained();
188//! selector.token_label = Some("some-initialized-token".into());
189//! let token = match cryptoki.select_one_token(&selector) {
190//! Ok(token) => token,
191//! Err(err) => {
192//! eprintln!("Token not found");
193//! # return Ok(());
194//! return Err(err);
195//! }
196//! };
197//!
198//! // Open a read/write user session, which is needed to generate or
199//! // import a key.
200//! let session = token.open_rw_user_session("1234")?;
201//!
202//! // Import the key.
203//! cryptoki.import(&session,
204//! token,
205//! None, // Import any PQC component to the same token.
206//! None, // Use a random label.
207//! key,
208//! KeyCapability::Signing)?;
209//! # Ok(()) }
210//! ```
211//!
212//! ## Generate a Key
213//!
214//! This code shows how to generate a key on a token. Note: the key
215//! cannot normally be exported and thus it is not generally possible
216//! to make a backup. As such, it is often better to generate a key
217//! in software, save a copy, and import it.
218//!
219//! The return value is a bare OpenPGP public key packet. You still
220//! need to turn it into a certificate by creating a direct signature
221//! (using e.g., [`SignatureBuilder::sign_direct_key`]) and adding a
222//! user ID, or you need to attach it to an existing certificate with
223//! a binding signature (using, e.g., [`CertBuilder::add_subkey`]).
224//!
225//! [`SignatureBuilder::sign_direct_key`]: https://docs.rs/sequoia-openpgp/latest/sequoia_openpgp/packet/signature/struct.SignatureBuilder.html#method.sign_direct_key
226//! [`CertBuilder::add_subkey`]: https://docs.rs/sequoia-openpgp/latest/sequoia_openpgp/cert/struct.CertBuilder.html#method.add_subkey
227//!
228//! ```
229//! use sequoia_openpgp as openpgp;
230//! use openpgp::Packet;
231//! use openpgp::serialize::Serialize;
232//!
233//! use sequoia_cryptoki::Context;
234//! use sequoia_cryptoki::TokenSelector;
235//!
236//! # fn main() -> sequoia_openpgp::Result<()> {
237//! let cryptoki = Context::new()?;
238//!
239//! // Get the token that we want to import the key to.
240//! let mut selector = TokenSelector::unconstrained();
241//! selector.token_label = Some("some-initialized-token".into());
242//! let token = match cryptoki.select_one_token(&selector) {
243//! Ok(token) => token,
244//! Err(err) => {
245//! eprintln!("Token not found");
246//! # return Ok(());
247//! return Err(err);
248//! }
249//! };
250//!
251//! // Open a read/write user session, which is needed to generate or
252//! // import a key.
253//! let session = token.open_rw_user_session("1234")?;
254//!
255//! // Import the key.
256//! let key = cryptoki.generate_eddsa(
257//! &session,
258//! token,
259//! None, // Use the current time.
260//! None, // Use a random label.
261//! )?;
262//! let openpgp_key = Packet::from(key.to_openpgp_key()?.role_into_primary());
263//!
264//! # let mut output = Vec::new();
265//! openpgp_key.serialize(&mut output)?;
266//! # Ok(()) }
267//! ```
268//!
269//! # Configuration File
270//!
271//! By default, [`Context`] and [`ContextBuilder`] read a
272//! configuration from the Sequoia home directory. If not using an
273//! alternate location, this is
274//! `.config/sequoia/keystore/cryptoki/config.toml`. When using an
275//! alternate location, this is
276//! `$SEQUOIA_HOME/config/keystore/cryptoki/config.toml`.
277//!
278//! This is a `toml` file, which looks like this:
279//!
280//! ```toml
281//! [[modules]]
282//! path = "/usr/local/lib/libkryoptic_pkcs11.so"
283//!
284//! [[modules]]
285//! path = "/usr/lib/x86_64-linux-gnu/softhsm/libsofthsm2.so"
286//! ```
287//!
288//! That is, there is an array of tables named `modules`, and each
289//! table contains a single key name `path`, which takes a string and
290//! is the path to a cryptoki module to load.
291#![allow(non_camel_case_types)]
292
293use std::sync::OnceLock;
294
295use sequoia_openpgp as openpgp;
296use openpgp::Result;
297
298// Re-export any third-party crates that we use in our API.
299pub use cryptoki;
300
301#[macro_use] mod macros;
302#[macro_use] mod log;
303
304mod algo;
305pub use algo::PublicKeyAlgorithm;
306mod builder;
307pub use builder::ContextBuilder;
308mod capabilities;
309mod check_password;
310mod config;
311pub use config::Config;
312pub use config::ConfigFile;
313pub use config::Error as ConfigError;
314mod decrypt;
315pub use decrypt::Decryptor;
316pub mod dicewords;
317mod export;
318mod keyid;
319mod key_info;
320mod objects;
321pub use objects::*;
322mod oids;
323mod password;
324pub use password::Prompt;
325mod selector;
326pub use selector::*;
327mod sign;
328pub use sign::Signer;
329mod import;
330pub use import::KeyCapability;
331// This comes near the end so that rustdoc puts all of the generate
332// key methods at the end of `Context`'s documentation.
333mod generate_key;
334pub mod toml_edit_tree;
335/// Re-export.
336pub use toml_edit;
337
338/// Configuration for the PKCS#11 interface.
339pub struct Context {
340 /// The configuration.
341 config: Config,
342
343 /// The loaded PKCS#11 modules.
344 backends: OnceLock<Vec<Backend>>,
345}
346
347impl Context {
348 /// Creates a new context.
349 ///
350 /// This reads the default configuration file. To disable this or
351 /// to read an alternate configuration file use [`ContextBuilder`]
352 /// to create the context.
353 pub fn new() -> Result<Self> {
354 ContextBuilder::new().build()
355 }
356
357 /// Returns the configuration.
358 pub fn config(&self) -> &Config {
359 &self.config
360 }
361}
362
363/// Returns whether the algorithm has a post-quantum component.
364fn algo_has_post_quantum_component(algo: &PublicKeyAlgorithm) -> bool {
365 use PublicKeyAlgorithm::*;
366
367 match algo {
368 MLDSA65_Ed25519 => true,
369 MLDSA87_Ed448 => true,
370 SLHDSA128s => true,
371 SLHDSA128f => true,
372 SLHDSA256s => true,
373 MLKEM768_X25519 => true,
374 MLKEM1024_X448 => true,
375 _ => false,
376 }
377}
378
379/// Returns whether the algorithm has a traditional (non-post
380/// quantum) component.
381fn algo_has_traditional_component(algo: &PublicKeyAlgorithm) -> bool {
382 use PublicKeyAlgorithm::*;
383
384 match algo {
385 SLHDSA128s => false,
386 SLHDSA128f => false,
387 SLHDSA256s => false,
388 _ => true,
389 }
390}
391
392/// Returns whether the algorithm is a composite algorithm, i.e., it
393/// has traditional and post quantum components.
394fn algo_is_composite(algo: &PublicKeyAlgorithm) -> bool {
395 algo_has_post_quantum_component(algo)
396 && algo_has_traditional_component(algo)
397}