Skip to main content

sequoia_cryptoki/
capabilities.rs

1use std::sync::atomic::Ordering;
2
3use anyhow::Context as _;
4
5use cryptoki::object::Attribute;
6use cryptoki::object::AttributeType;
7
8use crate::Key;
9use crate::Result;
10
11impl Key {
12    fn get_capabilities(&self) -> Result<()> {
13        if self.got_capabilities.load(Ordering::Relaxed) {
14            return Ok(());
15        }
16
17        let (session, object) = self.open_ro_session()?;
18
19        // We have the public key object.  To get the private key, we
20        // need to log in, which means we need a password.  To avoid
21        // that, we assume that the private key's capabilities
22        // correspond to the public key's capabilities.  If that is
23        // not the case, all bets are off.
24        let types = &[
25            // Decryption related.
26            AttributeType::Encrypt,
27            AttributeType::Wrap,
28            AttributeType::Encapsulate,
29            // Signing related.
30            AttributeType::Verify,
31        ][..];
32
33        let attributes = session.get_attributes(object, types)
34            .context("Failed to lookup key attributes")?;
35
36        let mut decryption_capable = false;
37        let mut signing_capable = false;
38
39        for attribute in attributes.into_iter() {
40            match attribute {
41                Attribute::Encrypt(yes)
42                    | Attribute::Wrap(yes)
43                    | Attribute::Encapsulate(yes)
44                    =>
45                {
46                    if yes {
47                        decryption_capable = true;
48                    }
49                }
50                Attribute::Verify(yes) => {
51                    if yes {
52                        signing_capable = true;
53                    }
54                }
55                _ => (),
56            }
57        }
58
59        self.signing_capable.store(signing_capable, Ordering::Relaxed);
60        self.decryption_capable.store(decryption_capable, Ordering::Relaxed);
61        self.got_capabilities.store(true, Ordering::Relaxed);
62
63        Ok(())
64    }
65
66    /// Returns whether the key supports signing.
67    ///
68    /// This is derived from the cryptoki objects and not from an
69    /// OpenPGP self-signature, which is not available.
70    pub fn signing_capable(&self) -> Result<bool> {
71        self.get_capabilities()?;
72        Ok(self.signing_capable.load(Ordering::Relaxed))
73    }
74
75    /// Returns whether the key supports decryption.
76    ///
77    /// This is derived from the cryptoki objects and not from an
78    /// OpenPGP self-signature, which is not available.
79    pub fn decryption_capable(&self) -> Result<bool> {
80        self.get_capabilities()?;
81        Ok(self.decryption_capable.load(Ordering::Relaxed))
82    }
83}