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)?;
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, // Use a random label.
206//! key,
207//! KeyCapability::Signing)?;
208//! # Ok(()) }
209//! ```
210//!
211//! ## Generate a Key
212//!
213//! This code shows how to generate a key on a token. Note: the key
214//! cannot normally be exported and thus it is not generally possible
215//! to make a backup. As such, it is often better to generate a key
216//! in software, save a copy, and import it.
217//!
218//! The return value is a bare OpenPGP public key packet. You still
219//! need to turn it into a certificate by creating a direct signature
220//! (using e.g., [`SignatureBuilder::sign_direct_key`]) and adding a
221//! user ID, or you need to attach it to an existing certificate with
222//! a binding signature (using, e.g., [`CertBuilder::add_subkey`]).
223//!
224//! [`SignatureBuilder::sign_direct_key`]: https://docs.rs/sequoia-openpgp/latest/sequoia_openpgp/packet/signature/struct.SignatureBuilder.html#method.sign_direct_key
225//! [`CertBuilder::add_subkey`]: https://docs.rs/sequoia-openpgp/latest/sequoia_openpgp/cert/struct.CertBuilder.html#method.add_subkey
226//!
227//! ```
228//! use sequoia_openpgp as openpgp;
229//! use openpgp::Packet;
230//! use openpgp::serialize::Serialize;
231//!
232//! use sequoia_cryptoki::Context;
233//! use sequoia_cryptoki::TokenSelector;
234//!
235//! # fn main() -> sequoia_openpgp::Result<()> {
236//! let cryptoki = Context::new()?;
237//!
238//! // Get the token that we want to import the key to.
239//! let mut selector = TokenSelector::unconstrained();
240//! selector.token_label = Some("some-initialized-token".into());
241//! let token = match cryptoki.select_one_token(&selector) {
242//! Ok(token) => token,
243//! Err(err) => {
244//! eprintln!("Token not found");
245//! # return Ok(());
246//! return Err(err);
247//! }
248//! };
249//!
250//! // Open a read/write user session, which is needed to generate or
251//! // import a key.
252//! let session = token.open_rw_user_session("1234")?;
253//!
254//! // Import the key.
255//! let key = cryptoki.generate_eddsa(
256//! &session,
257//! token,
258//! None, // Use the current time.
259//! None, // Use a random label.
260//! )?;
261//! let openpgp_key = Packet::from(key.to_openpgp_key()?.role_into_primary());
262//!
263//! # let mut output = Vec::new();
264//! openpgp_key.serialize(&mut output)?;
265//! # Ok(()) }
266//! ```
267//!
268//! # Configuration File
269//!
270//! By default, [`Context`] and [`ContextBuilder`] read a
271//! configuration from the Sequoia home directory. If not using an
272//! alternate location, this is
273//! `.config/sequoia/keystore/cryptoki/config.toml`. When using an
274//! alternate location, this is
275//! `$SEQUOIA_HOME/config/keystore/cryptoki/config.toml`.
276//!
277//! This is a `toml` file, which looks like this:
278//!
279//! ```toml
280//! [[modules]]
281//! path = "/usr/local/lib/libkryoptic_pkcs11.so"
282//!
283//! [[modules]]
284//! path = "/usr/lib/x86_64-linux-gnu/softhsm/libsofthsm2.so"
285//! ```
286//!
287//! That is, there is an array of tables named `modules`, and each
288//! table contains a single key name `path`, which takes a string and
289//! is the path to a cryptoki module to load.
290#![allow(non_camel_case_types)]
291
292use std::sync::OnceLock;
293
294use sequoia_openpgp as openpgp;
295use openpgp::Result;
296
297// Re-export any third-party crates that we use in our API.
298pub use cryptoki;
299
300#[macro_use] mod macros;
301#[macro_use] mod log;
302
303mod algo;
304pub use algo::PublicKeyAlgorithm;
305mod builder;
306pub use builder::ContextBuilder;
307mod capabilities;
308mod check_password;
309mod config;
310pub use config::Config;
311pub use config::ConfigFile;
312pub use config::Error as ConfigError;
313mod decrypt;
314pub use decrypt::Decryptor;
315pub mod dicewords;
316mod export;
317mod keyid;
318mod key_info;
319mod objects;
320pub use objects::*;
321mod oids;
322mod password;
323pub use password::Prompt;
324mod selector;
325pub use selector::*;
326mod sign;
327pub use sign::Signer;
328mod import;
329pub use import::KeyCapability;
330// This comes near the end so that rustdoc puts all of the generate
331// key methods at the end of `Context`'s documentation.
332mod generate_key;
333pub mod toml_edit_tree;
334/// Re-export.
335pub use toml_edit;
336
337/// Configuration for the PKCS#11 interface.
338pub struct Context {
339 /// The configuration.
340 config: Config,
341
342 /// The loaded PKCS#11 modules.
343 backends: OnceLock<Vec<Backend>>,
344}
345
346impl Context {
347 /// Creates a new context.
348 ///
349 /// This reads the default configuration file. To disable this or
350 /// to read an alternate configuration file use [`ContextBuilder`]
351 /// to create the context.
352 pub fn new() -> Result<Self> {
353 ContextBuilder::new().build()
354 }
355
356 /// Returns the configuration.
357 pub fn config(&self) -> &Config {
358 &self.config
359 }
360}