0
# SecretStorage
1
2
Python bindings to the FreeDesktop.org Secret Service API for secure storage and retrieval of passwords and other secrets on Linux systems. SecretStorage integrates with GNOME Keyring, KWallet (version 5.97+), and KeePassXC through D-Bus communication, providing a standardized interface for credential management across Linux desktop environments.
3
4
## Package Information
5
6
- **Package Name**: secretstorage
7
- **Language**: Python
8
- **Installation**: `pip install secretstorage`
9
- **Requires Python**: 3.6+
10
- **Dependencies**: `cryptography>=2.0`, `jeepney>=0.6`
11
- **Version**: 3.3.3
12
13
### Version Constants
14
15
```python { .api }
16
__version__ = '3.3.3' # Version string
17
__version_tuple__ = (3, 3, 3) # Version tuple (major, minor, patch)
18
```
19
20
## Core Imports
21
22
```python
23
import secretstorage
24
```
25
26
Common imports for specific functionality:
27
28
```python
29
from secretstorage import Collection, Item, dbus_init
30
from secretstorage import get_default_collection, create_collection
31
from secretstorage import LockedException, ItemNotFoundException
32
```
33
34
## Basic Usage
35
36
```python
37
import secretstorage
38
39
# Initialize D-Bus connection
40
connection = secretstorage.dbus_init()
41
42
# Get the default collection (keyring)
43
collection = secretstorage.get_default_collection(connection)
44
45
# Store a password
46
item = collection.create_item(
47
'My Application Password', # label
48
{'application': 'myapp', 'username': 'john'}, # attributes
49
b'my_secret_password' # secret data
50
)
51
52
# Retrieve the password later
53
items = list(collection.search_items({'application': 'myapp', 'username': 'john'}))
54
if items:
55
secret = items[0].get_secret()
56
print(f"Retrieved password: {secret.decode()}")
57
58
# Clean up
59
connection.close()
60
```
61
62
## Architecture
63
64
SecretStorage follows the FreeDesktop.org Secret Service specification with these key components:
65
66
- **D-Bus Connection**: Communication channel to the Secret Service daemon
67
- **Collections**: Secure containers (keyrings) that store multiple secret items
68
- **Items**: Individual secrets with labels, attributes, and encrypted data
69
- **Sessions**: Cryptographic sessions for secure data transfer using Diffie-Hellman key exchange
70
- **Prompts**: User authentication dialogs for accessing locked collections
71
72
The library automatically handles encryption/decryption, session management, and D-Bus protocol details, providing a high-level Python interface for secure credential storage.
73
74
## Capabilities
75
76
### Connection Management
77
78
Establishes and manages D-Bus connections to the Secret Service, with service availability checking and proper connection lifecycle management.
79
80
```python { .api }
81
def dbus_init() -> DBusConnection:
82
"""Returns a new connection to the session bus."""
83
84
def check_service_availability(connection: DBusConnection) -> bool:
85
"""Returns True if Secret Service daemon is available."""
86
```
87
88
[Connection Management](./connection-management.md)
89
90
### Collection Operations
91
92
Manages collections (keyrings) including creation, retrieval, locking/unlocking, and deletion. Collections serve as secure containers for organizing related secret items.
93
94
```python { .api }
95
def get_default_collection(connection: DBusConnection, session: Optional[Session] = None) -> Collection:
96
"""Returns the default collection, creating if necessary."""
97
98
def create_collection(connection: DBusConnection, label: str, alias: str = '', session: Optional[Session] = None) -> Collection:
99
"""Creates a new collection with given label and alias."""
100
101
def get_all_collections(connection: DBusConnection) -> Iterator[Collection]:
102
"""Returns generator of all available collections."""
103
104
class Collection:
105
def create_item(self, label: str, attributes: Dict[str, str], secret: bytes, replace: bool = False, content_type: str = 'text/plain') -> Item: ...
106
def search_items(self, attributes: Dict[str, str]) -> Iterator[Item]: ...
107
def is_locked(self) -> bool: ...
108
def unlock(self) -> bool: ...
109
```
110
111
[Collection Operations](./collection-operations.md)
112
113
### Item Management
114
115
Handles individual secret items with comprehensive operations for storing, retrieving, and managing secret data, attributes, and metadata.
116
117
```python { .api }
118
class Item:
119
def get_secret(self) -> bytes:
120
"""Returns item secret data."""
121
122
def set_secret(self, secret: bytes, content_type: str = 'text/plain') -> None:
123
"""Sets item secret data."""
124
125
def get_attributes(self) -> Dict[str, str]:
126
"""Returns item attributes dictionary."""
127
128
def set_attributes(self, attributes: Dict[str, str]) -> None:
129
"""Sets item attributes."""
130
131
def get_label(self) -> str:
132
"""Returns item label."""
133
134
def delete(self) -> None:
135
"""Deletes the item."""
136
```
137
138
[Item Management](./item-management.md)
139
140
### Search Operations
141
142
Provides powerful search capabilities for finding secret items across collections using attribute-based queries with support for global and collection-specific searches.
143
144
```python { .api }
145
def search_items(connection: DBusConnection, attributes: Dict[str, str]) -> Iterator[Item]:
146
"""Searches items across all collections."""
147
```
148
149
[Search Operations](./search-operations.md)
150
151
### Exception Handling
152
153
Comprehensive exception hierarchy for handling various error conditions including service unavailability, locked collections, missing items, and dismissed authentication prompts.
154
155
```python { .api }
156
class SecretStorageException(Exception):
157
"""Base exception class for all SecretStorage errors."""
158
159
class SecretServiceNotAvailableException(SecretStorageException):
160
"""Secret Service API is not available."""
161
162
class LockedException(SecretStorageException):
163
"""Collection or item is locked."""
164
165
class ItemNotFoundException(SecretStorageException):
166
"""Item does not exist or has been deleted."""
167
168
class PromptDismissedException(ItemNotFoundException):
169
"""Authentication prompt was dismissed by user."""
170
```
171
172
[Exception Handling](./exception-handling.md)
173
174
### Session Management
175
176
Handles cryptographic sessions for secure data transfer between client and Secret Service daemon, including Diffie-Hellman key exchange and AES encryption.
177
178
```python { .api }
179
class Session:
180
"""Cryptographic session for secure data transfer."""
181
object_path: Optional[str] # D-Bus object path
182
encrypted: bool # Whether session uses encryption
183
aes_key: Optional[bytes] # AES encryption key (when encrypted)
184
```
185
186
## Types
187
188
```python { .api }
189
from typing import Dict, Iterator, Optional
190
191
# From jeepney.io.blocking (external dependency)
192
class DBusConnection:
193
"""D-Bus connection for communicating with system services."""
194
def close(self) -> None:
195
"""Close the D-Bus connection."""
196
197
# From secretstorage.dhcrypto
198
class Session:
199
"""Cryptographic session for secure data transfer."""
200
object_path: Optional[str]
201
encrypted: bool
202
aes_key: Optional[bytes]
203
my_private_key: int
204
my_public_key: int
205
206
def set_server_public_key(self, server_public_key: int) -> None:
207
"""Sets server's public key and derives shared AES key."""
208
209
# Secret Service Constants (from defines.py)
210
SS_PREFIX: str = 'org.freedesktop.Secret.'
211
SS_PATH: str = '/org/freedesktop/secrets'
212
ALGORITHM_PLAIN: str = 'plain'
213
ALGORITHM_DH: str = 'dh-ietf1024-sha256-aes128-cbc-pkcs7'
214
```