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