1
//! File backend implementation that can be backed by the [Secret portal](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Secret.html).
2
//!
3
//! ```no_run
4
//! use oo7::{Secret, file::UnlockedKeyring};
5
//!
6
//! # async fn run() -> oo7::Result<()> {
7
//! let keyring = UnlockedKeyring::load("default.keyring", Some(Secret::text("some_text"))).await?;
8
//! keyring
9
//!     .create_item("My Label", &[("account", "alice")], "My Password", true)
10
//!     .await?;
11
//!
12
//! let items = keyring.search_items(&[("account", "alice")]).await?;
13
//! assert_eq!(items[0].secret(), oo7::Secret::blob("My Password"));
14
//!
15
//! keyring.delete(&[("account", "alice")]).await?;
16
//! #   Ok(())
17
//! # }
18
//! ```
19
//!
20
//! # File format
21
//!
22
//! Keyrings use the format of libsecret's file backend. A file starts with
23
//! the `GnomeKeyring\n\r\0\n` header, the major and minor versions as two
24
//! bytes (`1`, `0`), and a little-endian
25
//! [GVariant](https://docs.gtk.org/glib/struct.Variant.html) of type
26
//! `(uayutua(a{say}ay))`:
27
//!
28
//! | Type          | Field                                         |
29
//! | ------------- | --------------------------------------------- |
30
//! | `u`           | salt size                                     |
31
//! | `ay`          | salt                                          |
32
//! | `u`           | PBKDF2 iteration count                        |
33
//! | `t`           | modification time, in seconds since the epoch |
34
//! | `u`           | usage count                                   |
35
//! | `a(a{say}ay)` | items                                         |
36
//!
37
//! Each item is a pair of:
38
//!
39
//! - `a{say}`: its attributes, mapping each name to the HMAC of its value, so
40
//!   items can be searched without decrypting them.
41
//! - `ay`: the encrypted item, `ciphertext ‖ IV ‖ HMAC(ciphertext ‖ IV)`.
42
//!
43
//! Decrypted, an item is a `(a{ss}sttay)` GVariant holding its attributes,
44
//! label, creation and modification times, and secret.
45
//!
46
//! The key is derived from the password with PBKDF2-HMAC-SHA256, using at
47
//! least 100000 iterations and a 32 bytes salt. Items are encrypted with
48
//! AES-128-CBC, with PKCS#7 padding and a random IV, and the same key is used
49
//! for HMAC-SHA256. These algorithms were chosen for being FIPS 140-3
50
//! approved.
51
//!
52
//! oo7 also supports keyrings without a password, which store attribute
53
//! values and items in plain text.
54
//!
55
//! gnome-keyring keyrings, in either its encrypted binary format or the plain
56
//! text one used for keyrings without a password, are migrated to this
57
//! format.
58

            
59
#[cfg(feature = "unstable")]
60
#[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
61
pub mod api;
62
#[cfg(not(feature = "unstable"))]
63
pub(crate) mod api;
64

            
65
mod error;
66
mod locked_item;
67
mod locked_keyring;
68
mod unlocked_item;
69
mod unlocked_keyring;
70

            
71
pub use error::{Error, InvalidItemError, WeakKeyError};
72
pub use locked_item::LockedItem;
73
pub use locked_keyring::LockedKeyring;
74
pub use unlocked_item::UnlockedItem;
75
pub use unlocked_keyring::{ItemDefinition, UnlockedKeyring};
76

            
77
use crate::{AsAttributes, GENERIC_SCHEMA, Key, Secret, XDG_SCHEMA_ATTRIBUTE};
78

            
79
#[derive(Debug)]
80
pub enum Item {
81
    Locked(LockedItem),
82
    Unlocked(UnlockedItem),
83
}
84

            
85
impl From<UnlockedItem> for Item {
86
17
    fn from(item: UnlockedItem) -> Self {
87
17
        Self::Unlocked(item)
88
    }
89
}
90

            
91
impl From<LockedItem> for Item {
92
    fn from(item: LockedItem) -> Self {
93
        Self::Locked(item)
94
    }
95
}
96

            
97
impl Item {
98
16
    pub const fn is_locked(&self) -> bool {
99
16
        matches!(self, Self::Locked(_))
100
    }
101

            
102
15
    pub fn as_unlocked(&self) -> &UnlockedItem {
103
15
        match self {
104
15
            Self::Unlocked(item) => item,
105
            _ => panic!("The item is locked"),
106
        }
107
    }
108

            
109
11
    pub fn as_mut_unlocked(&mut self) -> &mut UnlockedItem {
110
11
        match self {
111
11
            Self::Unlocked(item) => item,
112
            _ => panic!("The item is locked"),
113
        }
114
    }
115

            
116
    pub fn as_locked(&self) -> &LockedItem {
117
        match self {
118
            Self::Locked(item) => item,
119
            _ => panic!("The item is unlocked"),
120
        }
121
    }
122

            
123
    /// Check if this item matches the given attributes
124
16
    pub fn matches_attributes(&self, attributes: &impl AsAttributes, key: Option<&Key>) -> bool {
125
17
        match self {
126
15
            Self::Unlocked(unlocked) => {
127
16
                let item_attrs = unlocked.attributes();
128
63
                attributes.search_attributes().iter().all(|(k, value)| {
129
17
                    if k == XDG_SCHEMA_ATTRIBUTE
130
8
                        && !item_attrs.contains_key(XDG_SCHEMA_ATTRIBUTE)
131
4
                        && value == GENERIC_SCHEMA
132
                    {
133
4
                        return true;
134
                    }
135
49
                    item_attrs.get(k.as_str()).map(|v| v.as_ref()) == Some(value.as_str())
136
                })
137
            }
138
8
            Self::Locked(locked) => locked.inner.matches(attributes, key),
139
        }
140
    }
141

            
142
    /// Check if this item has exactly the given attributes.
143
8
    pub fn matches_attributes_exact(
144
        &self,
145
        attributes: &impl AsAttributes,
146
        key: Option<&Key>,
147
    ) -> bool {
148
8
        match self {
149
8
            Self::Unlocked(unlocked) => unlocked.matches_exact(attributes),
150
            Self::Locked(locked) => locked.inner.matches_exact(attributes, key),
151
        }
152
    }
153
}
154

            
155
#[derive(Debug)]
156
pub enum Keyring {
157
    Locked(LockedKeyring),
158
    Unlocked(UnlockedKeyring),
159
}
160

            
161
impl From<LockedKeyring> for Keyring {
162
    fn from(keyring: LockedKeyring) -> Self {
163
        Self::Locked(keyring)
164
    }
165
}
166

            
167
impl From<UnlockedKeyring> for Keyring {
168
    fn from(keyring: UnlockedKeyring) -> Self {
169
        Self::Unlocked(keyring)
170
    }
171
}
172

            
173
impl Keyring {
174
    /// Validate that a secret can decrypt the items in this keyring.
175
    #[cfg_attr(feature = "tracing", tracing::instrument(skip(self, secret)))]
176
32
    pub async fn validate_secret(&self, secret: &Secret) -> Result<bool, Error> {
177
8
        match self {
178
16
            Self::Locked(keyring) => keyring.validate_secret(secret).await,
179
            Self::Unlocked(keyring) => keyring.validate_secret(secret).await,
180
        }
181
    }
182

            
183
    pub async fn validate_unencrypted(&self) -> Result<bool, Error> {
184
        match self {
185
            Self::Locked(keyring) => keyring.validate_unencrypted().await,
186
            Self::Unlocked(keyring) => keyring.validate_unencrypted().await,
187
        }
188
    }
189

            
190
    /// Get the modification timestamp
191
140
    pub async fn modified_time(&self) -> std::time::Duration {
192
35
        match self {
193
8
            Self::Locked(keyring) => keyring.modified_time().await,
194
70
            Self::Unlocked(keyring) => keyring.modified_time().await,
195
        }
196
    }
197

            
198
    /// Get the creation timestamp from the filesystem if the keyring has an
199
    /// associated file.
200
132
    pub async fn created_time(&self) -> Option<std::time::Duration> {
201
100
        let path = self.path()?;
202

            
203
        #[cfg(feature = "tokio")]
204
        let metadata = tokio::fs::metadata(path).await.ok()?;
205
        #[cfg(feature = "async-std")]
206
        let metadata = async_fs::metadata(path).await.ok()?;
207

            
208
12
        metadata
209
            .created()
210
            .ok()
211
32
            .and_then(|time| time.duration_since(std::time::SystemTime::UNIX_EPOCH).ok())
212
    }
213

            
214
154
    pub async fn items(&self) -> Result<Vec<Item>, Error> {
215
31
        match self {
216
20
            Self::Locked(keyring) => Ok(keyring
217
4
                .items()
218
12
                .await?
219
4
                .into_iter()
220
4
                .map(Item::Locked)
221
4
                .collect()),
222
138
            Self::Unlocked(keyring) => Ok(keyring
223
30
                .items()
224
110
                .await?
225
29
                .into_iter()
226
24
                .map(Item::Unlocked)
227
60
                .collect()),
228
        }
229
    }
230

            
231
    /// Return the associated file if any.
232
34
    pub fn path(&self) -> Option<&std::path::Path> {
233
31
        match self {
234
4
            Self::Locked(keyring) => keyring.path(),
235
31
            Self::Unlocked(keyring) => keyring.path(),
236
        }
237
    }
238

            
239
19
    pub const fn is_locked(&self) -> bool {
240
22
        matches!(self, Self::Locked(_))
241
    }
242

            
243
23
    pub fn as_unlocked(&self) -> &UnlockedKeyring {
244
23
        match self {
245
24
            Self::Unlocked(unlocked_keyring) => unlocked_keyring,
246
            _ => panic!("The keyring is locked"),
247
        }
248
    }
249

            
250
    pub fn as_locked(&self) -> &LockedKeyring {
251
        match self {
252
            Self::Locked(locked_keyring) => locked_keyring,
253
            _ => panic!("The keyring is unlocked"),
254
        }
255
    }
256
}