Skip to main content

sequoia_cryptoki/
sign.rs

1use std::borrow::Cow;
2
3use anyhow::Context;
4
5use sequoia_openpgp as openpgp;
6use openpgp::crypto::mpi;
7use openpgp::crypto;
8use openpgp::packet::key::PublicParts;
9use openpgp::packet::key::UnspecifiedRole;
10use openpgp::packet;
11use openpgp::types::HashAlgorithm;
12use openpgp::types::PublicKeyAlgorithm;
13
14use cryptoki::mechanism::Mechanism;
15use cryptoki::mechanism::eddsa::EddsaParams;
16use cryptoki::mechanism::eddsa::EddsaSignatureScheme;
17use cryptoki::mechanism::dsa;
18use cryptoki::object::KeyType;
19use cryptoki::session::UserType;
20use cryptoki::types::AuthPin;
21
22use crate::Result;
23use crate::Prompt;
24use crate::key_info::KeyInfo;
25use crate::objects::Key;
26
27/// A signer for a PKCS#11 key.
28///
29/// This implements [`sequoia_openpgp::crypto::Signer`] and hence can
30/// be used wherever a Sequoia method needs to create a signature.
31///
32///   [`sequoia_openpgp::crypto::Signer`]: https://docs.rs/sequoia-openpgp/latest/sequoia_openpgp/crypto/trait.Signer.html
33pub struct Signer<'key, 'prompt> {
34    key: Cow<'key, Key>,
35    openpgp_key: packet::Key<PublicParts, UnspecifiedRole>,
36    user_pin: Option<AuthPin>,
37    prompt: Box<dyn Prompt + 'prompt>,
38}
39
40impl<'key, 'prompt> Signer<'key, 'prompt> {
41    /// Creates a `Signer`.
42    ///
43    /// This is a bit ugly, because we can't stash a PKCS#11
44    /// `Session`: a struct that implements `Signer` has to implement
45    /// `Sync`, but a `Session` is not `Sync`.
46    ///
47    /// If the user PIN is known, pass it through to avoid prompting
48    /// the user.  (If `user_pin` is wrong, we don't prompt the user,
49    /// but immediately return an error.)  Otherwise, the user is
50    /// prompted.
51    pub fn new<P>(prompt: P, key: &'key Key, user_pin: Option<AuthPin>)
52        -> Result<Self>
53    where
54        P: Prompt + 'prompt
55    {
56        // Before we prompt for the PIN, make sure we can convert the
57        // public key to an OpenPGP key.
58        let openpgp_key = key.to_openpgp_key()
59            .context("Converting public key to OpenPGP format")?
60            .role_into_unspecified();
61
62        Ok(Self {
63            key: Cow::Borrowed(key),
64            openpgp_key,
65            user_pin,
66            prompt: Box::new(prompt),
67        })
68    }
69
70    /// Creates a `Signer`.
71    ///
72    /// Like [`Signer::new`], but takes ownership of `key`.
73    pub fn new_owned<P>(prompt: P, key: Key, user_pin: Option<AuthPin>)
74        -> Result<Self>
75    where
76        P: Prompt + 'prompt
77    {
78        // Before we prompt for the PIN, make sure we can convert the
79        // public key to an OpenPGP key.
80        let openpgp_key = key.to_openpgp_key()
81            .context("Converting public key to OpenPGP format")?
82            .role_into_unspecified();
83
84        Ok(Self {
85            key: Cow::Owned(key),
86            openpgp_key,
87            user_pin,
88            prompt: Box::new(prompt),
89        })
90    }
91}
92
93impl crypto::Signer for Signer<'_, '_> {
94    fn public(&self) -> &packet::Key<PublicParts, UnspecifiedRole> {
95        &self.openpgp_key
96    }
97
98    fn sign(&mut self, hash_algo: HashAlgorithm, digest: &[u8])
99            -> Result<mpi::Signature>
100    {
101        let (session, _object) = self.key.open_ro_session()?;
102
103        // Login as the user.
104        if let Some(user_pin) = self.user_pin.as_ref() {
105            // PIN was supplied.
106            session.login(UserType::User, Some(&user_pin))
107                .context("Logging in to token")?;
108        } else {
109            // Prompt the user for the PIN.
110            loop {
111                let user_pin = self.prompt.prompt_to_unlock("the user PIN")?;
112                let user_pin = String::from_utf8(user_pin.map(|p| p.to_vec()))
113                    .context("Parsing user PIN")?;
114                let user_pin = AuthPin::new(user_pin.into());
115
116                match session.login(UserType::User, Some(&user_pin)) {
117                    Ok(_) => {
118                        self.user_pin = Some(user_pin);
119                        break;
120                    }
121                    Err(err) => {
122                        eprintln!("Error logging in: {}", err);
123                    }
124                }
125            }
126        }
127
128        let key_info = KeyInfo::new(&session, &self.key)?;
129
130        let composite_info = if let Some(composite)
131            = self.key.composite_key().as_ref()
132        {
133            Some(KeyInfo::new(&session, composite)?)
134        } else {
135            None
136        };
137        match self.openpgp_key.pk_algo() {
138            PublicKeyAlgorithm::Ed25519 => {
139                let key_info = key_info.check_standalone(
140                    &self.openpgp_key, composite_info, KeyType::EC_EDWARDS)?;
141
142                // RFC 9580, Section 12.7:
143                //
144                // [W]hile [RFC8032] describes different variants of EdDSA,
145                // OpenPGP uses the "pure" variant (PureEdDSA). The hashing
146                // that happens with OpenPGP is done as part of the standard
147                // OpenPGP signature process, and that hash itself is fed as
148                // the input message to the PureEdDSA algorithm.
149                //
150                // https://www.rfc-editor.org/rfc/rfc9580.html#section-12.7
151                let eddsa_params = EddsaParams::new(EddsaSignatureScheme::Pure);
152
153                let raw = session.sign(&Mechanism::Eddsa(eddsa_params),
154                                       key_info.private_key.clone(), digest)
155                    .with_context(|| {
156                        format!("Signing data")
157                    })?;
158
159                if raw.len() != 64 {
160                    return Err(anyhow::anyhow!(
161                        "Token returned an invalid signature: expected \
162                         64 bytes of signature data, got {} bytes",
163                        raw.len()));
164                }
165
166                Ok(mpi::Signature::Ed25519 {
167                    s: raw.try_into().expect("checked length above"),
168                })
169            },
170
171            PublicKeyAlgorithm::Ed448 => {
172                let key_info = key_info.check_standalone(
173                    &self.openpgp_key, composite_info, KeyType::EC_EDWARDS)?;
174
175                // RFC 9580, Section 12.7:
176                //
177                // [W]hile [RFC8032] describes different variants of EdDSA,
178                // OpenPGP uses the "pure" variant (PureEdDSA). The hashing
179                // that happens with OpenPGP is done as part of the standard
180                // OpenPGP signature process, and that hash itself is fed as
181                // the input message to the PureEdDSA algorithm.
182                //
183                // As specified in [RFC8032], Ed448 also expects a "context
184                // string". In OpenPGP, Ed448 is used with the empty string as
185                // a context string.
186                //
187                // https://www.rfc-editor.org/rfc/rfc9580.html#section-12.7
188                let eddsa_params =
189                    EddsaParams::new(EddsaSignatureScheme::Ed448(&[]));
190
191                let raw = session.sign(&Mechanism::Eddsa(eddsa_params),
192                                       key_info.private_key.clone(), digest)
193                    .with_context(|| {
194                        format!("Signing data")
195                    })?;
196
197                if raw.len() != 114 {
198                    return Err(anyhow::anyhow!(
199                        "Token returned an invalid signature: expected \
200                         114 bytes of signature data, got {} bytes",
201                        raw.len()));
202                }
203
204                Ok(mpi::Signature::Ed448 {
205                    s: raw.try_into().expect("checked length above"),
206                })
207            },
208
209            // MLDSA65_Ed25519.
210            PublicKeyAlgorithm::MLDSA65_Ed25519 => {
211                let (mldsa, eddsa) = key_info.check_composite(
212                    &self.openpgp_key, composite_info,
213                    KeyType::ML_DSA, KeyType::EC_EDWARDS)?;
214
215                let eddsa = session.sign(
216                    &Mechanism::Eddsa(EddsaParams::new(
217                        EddsaSignatureScheme::Pure)),
218                    eddsa.private_key, digest)
219                    .context("Generating the Ed25519 signature")?
220                    .try_into()
221                    .map_err(|_| anyhow::anyhow!("signature has wrong size"))?;
222
223                let mldsa = session.sign(
224                    &Mechanism::MlDsa(dsa::SignAdditionalContext::new(
225                        dsa::HedgeType::Required, None)),
226                    mldsa.private_key, digest)
227                    .context("Generating the ML-DSA signature")?
228                    .try_into()
229                    .map_err(|_| anyhow::anyhow!("signature has wrong size"))?;
230
231                Ok(mpi::Signature::MLDSA65_Ed25519 {
232                    eddsa: Box::new(eddsa),
233                    mldsa: Box::new(mldsa),
234                })
235            },
236
237            // MLDSA87_Ed448.
238            PublicKeyAlgorithm::MLDSA87_Ed448 => {
239                let (mldsa, eddsa) = key_info.check_composite(
240                    &self.openpgp_key, composite_info,
241                    KeyType::ML_DSA, KeyType::EC_EDWARDS)?;
242
243                let eddsa = session.sign(
244                    &Mechanism::Eddsa(EddsaParams::new(
245                        EddsaSignatureScheme::Ed448(&[]))),
246                    eddsa.private_key, digest)
247                    .context("Generating the Ed448 signature")?
248                    .try_into()
249                    .map_err(|_| anyhow::anyhow!("signature has wrong size"))?;
250
251                let mldsa = session.sign(
252                    &Mechanism::MlDsa(dsa::SignAdditionalContext::new(
253                        dsa::HedgeType::Required, None)),
254                    mldsa.private_key, digest)
255                    .context("Generating the ML-DSA signature")?
256                    .try_into()
257                    .map_err(|_| anyhow::anyhow!("signature has wrong size"))?;
258
259                Ok(mpi::Signature::MLDSA87_Ed448 {
260                    eddsa: Box::new(eddsa),
261                    mldsa: Box::new(mldsa),
262                })
263            },
264
265            // SLH-DSA-128s.
266            PublicKeyAlgorithm::SLHDSA128s => {
267                let key_info = key_info.check_standalone(
268                    &self.openpgp_key, composite_info, KeyType::SLH_DSA)?;
269
270                let sig = session.sign(
271                    &Mechanism::SlhDsa(dsa::SignAdditionalContext::new(
272                        dsa::HedgeType::Required, None)),
273                    key_info.private_key, digest)?
274                    .try_into()
275                    .map_err(|_| anyhow::anyhow!("signature has wrong size"))?;
276
277                Ok(mpi::Signature::SLHDSA128s {
278                    sig,
279                })
280            },
281
282            // SLH-DSA-128f.
283            PublicKeyAlgorithm::SLHDSA128f => {
284                let key_info = key_info.check_standalone(
285                    &self.openpgp_key, composite_info, KeyType::SLH_DSA)?;
286
287                let sig = session.sign(
288                    &Mechanism::SlhDsa(dsa::SignAdditionalContext::new(
289                        dsa::HedgeType::Required, None)),
290                    key_info.private_key, digest)?
291                    .try_into()
292                    .map_err(|_| anyhow::anyhow!("signature has wrong size"))?;
293
294                Ok(mpi::Signature::SLHDSA128f {
295                    sig,
296                })
297            },
298
299            // SLH-DSA-256s.
300            PublicKeyAlgorithm::SLHDSA256s => {
301                let key_info = key_info.check_standalone(
302                    &self.openpgp_key, composite_info, KeyType::SLH_DSA)?;
303
304                let sig = session.sign(
305                    &Mechanism::SlhDsa(dsa::SignAdditionalContext::new(
306                        dsa::HedgeType::Required, None)),
307                    key_info.private_key, digest)?
308                    .try_into()
309                    .map_err(|_| anyhow::anyhow!("signature has wrong size"))?;
310
311                Ok(mpi::Signature::SLHDSA256s {
312                    sig,
313                })
314            },
315
316            // Ed25519Legacy.
317            PublicKeyAlgorithm::EdDSA => {
318                let key_info = key_info.check_standalone(
319                    &self.openpgp_key, composite_info, KeyType::EC_EDWARDS)?;
320
321                // RFC 9580, Section 12.7:
322                //
323                // [W]hile [RFC8032] describes different variants of EdDSA,
324                // OpenPGP uses the "pure" variant (PureEdDSA). The hashing
325                // that happens with OpenPGP is done as part of the standard
326                // OpenPGP signature process, and that hash itself is fed as
327                // the input message to the PureEdDSA algorithm.
328                //
329                // https://www.rfc-editor.org/rfc/rfc9580.html#section-12.7
330                let eddsa_params = EddsaParams::new(EddsaSignatureScheme::Pure);
331
332                let raw = session.sign(&Mechanism::Eddsa(eddsa_params),
333                                       key_info.private_key.clone(), digest)
334                    .with_context(|| {
335                        format!("Signing data")
336                    })?;
337
338                if raw.len() != 64 {
339                    return Err(anyhow::anyhow!(
340                        "Token returned an invalid signature: expected \
341                         64 bytes of signature data, got {} bytes",
342                        raw.len()));
343                }
344
345                let r = mpi::MPI::new(&raw[..32]);
346                let s = mpi::MPI::new(&raw[32..]);
347                Ok(mpi::Signature::EdDSA { r, s, })
348            },
349
350            #[allow(deprecated)]
351            PublicKeyAlgorithm::RSASign | PublicKeyAlgorithm::RSAEncryptSign => {
352                let key_info = key_info.check_standalone(
353                    &self.openpgp_key, composite_info, KeyType::RSA)?;
354
355                // We use the raw RSA signing mechanism because we
356                // handle the hashing in the OpenPGP layer.  But, that
357                // means we have to do part of EMSA-PKCS1-v1_5
358                // ourselves.
359
360                // Form the DigestInfo sequence.
361                const MAX_OID_SIZE: usize = 20;
362                let mut v = Vec::with_capacity(MAX_OID_SIZE + digest.len());
363                v.extend(hash_algo.oid()?);
364                v.extend(digest);
365
366                // Then sign that.
367                let raw = session.sign(&Mechanism::RsaPkcs,
368                                       key_info.private_key.clone(),
369                                       &v)?;
370
371                Ok(mpi::Signature::RSA { s: mpi::MPI::new(&raw[..]) })
372            },
373
374            algo => {
375                Err(anyhow::anyhow!("{} keys are not supported", algo))
376            },
377        }
378    }
379}