# Cryptex
A command API for accessing various keychains or secure enclaves.
## The problem
Applications use several credentials today to secure data locally and during transmission.
However, bad habits happen when safeguarding these credentials. For example, when creating an API token for Amazon's AWS, Amazon generates
a secret key on a user's behalf and is downloaded to a CSV file. Programmers do not know how to best
store these downloaded credentials because they must be used in a program to make API calls.
They don't know which of the following is the best option:
- Put these credentials directly in the program like most do as constant variables but this is a terrible option because attackers can analyze the code and extract it.
- Use environment variables. If so, should it be passed at the command level or put in a global variable registry? Both are susceptible to sniffing memory or process information.
- Read a config file that contains the credentials but must rely on the security of the operating system to manage access control.
- Use secure enclaves to store the credentials but this just shifts to another problem as secure enclaves rely on yet another set of credentials to ensure the application has the correct authorization. These come as hardware security modules (HSM) or trusted execution environments (TEE).
- Require interaction with a user or group to supply the credential for each use or cache it for a period of time. This is usually done with passwords, pins, cyber tokens, and biometrics.
Where to put the credential that is directly used by applications or people is called the top level credential problem.
There are services like [LeakLooker](https://github.com/woj-ciech/LeakLooker) that browse the internet looking for credentials that can be scraped and unfortunately but often [succeed](https://hackernoon.com/leaklooker-v2-find-more-open-servers-and-source-code-leaks-25e671700e41?mc_cid=47325dd839&mc_eid=0ff0c85eaf).
Some projects have documented how to test credentials to see if they have been revealed. See [keyhacks](https://github.com/streaak/keyhacks).
This document aims to provide guidance and aid in adopting best practices and developing code to address the top level credential problem — the credential used to protect all others — the keys to the kingdom — or a secret that is used directly by a program that if compromised would yield disastrous consequences.
## The solution
*Cryptex* is a layer that is designed to be a command line tool or API library for storing secrets that tries to make it hard to get wrong.
The default is to use the operating system keychain. The goal is to add to *Cryptex* to allow for
many different enclaves that are optimal for storing the keys to the kingdom like YubiKey, Intel SGX, or Arm Trustzone.
In principle, a system's secure enclave should be able to keep some credentials away from `root` (as in, the attacker can *use* the credential as long as they have access, but they can't extract the credential for persistence), and assuming no other attacks like [Foreshadow](https://foreshadowattack.eu/).
Mac OS X, Linux, and Android have built-in keychains that are guarded by the operating system.
iOS and Android come with hardware secure enclaves or trusted execution environments for managing the secrets stored in the keychain.
*Cryptex* can use the OS keychain, encrypted files, a YubiHSM 2 or a Nitrokey 3, from the command line
or as a Rust library.
Future work could allow for communication over unix or tcp sockets with *Cryptex* running as a daemon process.
Currently Mac OS X offers support for a [CLI tool](https://www.netmeister.org/blog/keychain-passwords.html) and [libraries](https://developer.apple.com/documentation/security) but they are complex to understand and can be prone to misuse due to misunderstandings.
*Cryptex* removes the complexity by choosing secure defaults so developers can focus on their job.
*Cryptex* is written in Rust. The OS keyrings need nothing beyond the operating system (and DBus on
Linux); the optional backends add their own needs, listed under [Build from source](#build-from-source).
*Cryptex* also supports file-backed keyrings instead of the OS keyring. The `file` feature enables
the [SQLCipher](https://www.zetetic.net/sqlcipher/) backend, and the `encrypted-vfs` feature enables
a bundled SQLite VFS encrypted with XChaCha20-Poly1305 by default or AES-256-GCM when requested.
The `turso` feature stores secrets in a [Turso](https://github.com/tursodatabase/turso) database
using Turso's native page encryption (AEGIS-256 by default or AES-256-GCM), and the
`turso-encrypted-io` feature runs Turso over a custom IO layer that applies the same
XChaCha20-Poly1305 / AES-256-GCM page encryption as `encrypted-vfs`. Both Turso backends use
`~/.cryptex/keyring-turso.db3` and depend on a pinned Turso pre-release whose encryption is
experimental upstream.
You can check if SQLCipher is enabled by running `allows_file()`.
| Feature | What it adds |
|---------|--------------|
| `macos-keychain`, `windows-credentials`, `linux-secret-service` | The OS keyrings (default) |
| `file` | SQLCipher keyring |
| `encrypted-vfs` | SQLite keyring with cryptex page encryption, and `migrate` for 2.x files |
| `turso` | Turso keyring with Turso's own page encryption |
| `turso-encrypted-io` | Turso keyring with cryptex page encryption |
| `memory`, `web-storage`, `indexeddb`, `turso-opfs`, `js` | In-memory and browser keyrings |
| `yubihsm-usb`, `yubihsm-http` | YubiHSM 2 |
| `nitrokey` | Nitrokey 3, or any FIDO2 key with `hmac-secret` |
| `serde` | `KeyRingSecret::from_serde` / `to_serde` |
| `fips` | Only FIPS-approved algorithms (see [FIPS mode](#fips-mode)) |
The file-backed keyrings derive the encryption key from a password and a salt. Similar to how
databases use connection strings, this library employs a connection string to indicate the values.
The SQLCipher and native Turso backends need both:
```text
password=<password> salt=<salt value>
```
The encrypted VFS and Turso encrypted IO backends generate a random 32-byte salt when they create a
keyring and store it in a header at the start of the file, along with the cipher and the key
derivation costs. They need only the password, and a `salt=` value is not used:
```text
password=<password>
```
The header is not encrypted, but its SHA-256 digest is bound into every encrypted page, so editing
it makes the keyring unreadable. When reopening, the header decides the cipher and costs; the
connection string's `cipher`, `memory`, `threads` and `parallel` only apply to a new keyring or a
rekey, which writes a new header. New keyrings refuse Argon2 costs below Argon2's own defaults.
Each page is also bound to its position and to the kind of file it sits in, so pages cannot be
swapped, or copied between the database, its journal or WAL, and another keyring.
`key=<64 hex digits>` supplies a raw 32-byte key instead of a password.
The password and salt are hashed using Argon2id. The memory cost is measured in KiB blocks, not
bytes. These defaults are part of the current release configuration and may be tuned in future
minor releases:
| Parameter | Default | Description |
|-----------|---------|-------------|
| `memory` | `32768` | Argon2 memory cost in KiB blocks |
| `threads` | `3` | Argon2 time/thread cost |
| `parallel` | `2` | Argon2 parallelism cost |
The values can be overridden in the connection string:
```text
password=<password> salt=<salt value> memory=<integer> threads=<integer> parallel=<integer>
```
For the encrypted VFS and Turso encrypted IO backends, the cipher can also be selected:
```text
password=<password> cipher=xchacha20poly1305
password=<password> cipher=aes256gcm
```
Both store a random nonce with each page. XChaCha20-Poly1305's 192-bit nonce never practically
repeats. AES-256-GCM's 96-bit nonce is good for about 2^32 page writes under one key, so rekey a
long-lived AES keyring now and then.
### FIPS mode
The `fips` feature restricts every keyring to FIPS-approved algorithms:
- AES-256-GCM is the only cipher for the encrypted VFS, Turso encrypted IO, native Turso and
in-memory keyrings. Asking for XChaCha20, ChaCha20 or AEGIS is an error.
- Passwords are stretched with PBKDF2-HMAC-SHA256 instead of Argon2id. The connection string takes
`iterations=<integer>` (default and minimum `600000`) in place of `memory`, `threads` and
`parallel`, and salts must be at least 16 bytes.
- SQLCipher keeps its own AES-256-CBC with HMAC-SHA512; only the key cryptex hands it changes.
The algorithms are approved, but the implementations are the pure-Rust RustCrypto crates, not a
CMVP-validated module. A `fips` build and a normal build cannot open each other's keyrings, because
they derive keys differently, and a `fips` build refuses files that use a non-approved cipher.
For the native Turso backend:
```text
password=<password> salt=<salt value> cipher=aegis256
password=<password> salt=<salt value> cipher=aes256gcm
```
The `file_keyring` example walks through creating, listing, rekeying and deleting with the
encrypted VFS:
```bash
cargo run --example file_keyring --no-default-features --features encrypted-vfs
```
The `default_argon2_params` example derives a key and prints elapsed time for the current defaults.
It can also be used to try alternate values without changing code:
```bash
cargo run --quiet --example default_argon2_params --no-default-features --features file,encrypted-vfs
CRYPTEX_ARGON2_MEMORY=32768 CRYPTEX_ARGON2_THREADS=3 CRYPTEX_ARGON2_PARALLEL=2 cargo run --quiet --example default_argon2_params --no-default-features --features file,encrypted-vfs
```
The program can be compiled from any OS to run on any OS. Cryptex-CLI is the command line tool while Cryptex is the library.
### In-memory keyrings
The `memory` feature adds `MemoryKeyring`, which keeps its secrets in RAM and
never writes a file. It builds for every target, including wasm. Secrets leave
memory only as a single AEAD-sealed blob:
```rust
use cryptex::KeyRing;
use cryptex::memory::{ConnectionParams, MemoryKeyring};
let params: ConnectionParams =
"password=<password> salt=<salt value>".parse().unwrap();
let mut keyring = MemoryKeyring::with_params(¶ms)?;
keyring.set_secret("token", b"secret value")?;
// Persist this anywhere you like; it is sealed with a fresh nonce.
let blob = keyring.export()?;
// The salt, cipher and Argon2 parameters travel inside the blob.
let mut reopened = MemoryKeyring::import(&blob, b"<password>")?;
# Ok::<(), cryptex::KeyRingError>(())
```
A blob made from `key=<hex>` instead of a password needs that same raw key to
open. `rekey` re-derives the key without touching the secrets.
---
## WebAssembly and WASI
`cryptex` builds for `wasm32-unknown-unknown` and for `wasm32-wasip1` /
`wasm32-wasip2`. Which backends exist there:
| Feature | `wasm32-unknown-unknown` | WASI | Notes |
|---------|--------------------------|------|-------|
| `memory` | yes | yes | encrypted in RAM, export/import |
| `turso` | yes | yes | Turso's native page encryption, including in-memory and OPFS keyrings |
| `turso-encrypted-io` | builds | yes | the page cipher needs a `PageStore`; the file-backed one is native only |
| `web-storage` | yes | no | a `MemoryKeyring` sealed into `localStorage` |
| `indexeddb` | yes | no | encrypted image snapshots, one per keyring |
| `turso-opfs` | yes | no | the database file itself in the origin private file system |
| `js` | yes | no | the `wasm-bindgen` `Keyring` class |
| `file`, `encrypted-vfs` | no | no | SQLCipher and the bundled C VFS are native only |
| OS keyrings, `yubihsm-*` | no | no | no OS keychain or USB device |
Asking for an unsupported backend on wasm is a compile error that names the
problem, rather than a linker failure.
`getrandom` needs its Web Crypto backend on `wasm32-unknown-unknown`. The
repository's `.cargo/config.toml` sets it, and a CI job that overrides
`RUSTFLAGS` must repeat it:
```bash
RUSTFLAGS='--cfg getrandom_backend="wasm_js"' \
cargo check --target wasm32-unknown-unknown --no-default-features --features turso
```
### Browser keyrings
The `js` feature wraps the backends in a `Keyring` class for JavaScript:
```bash
wasm-pack build --target web --no-default-features --features js
```
```js
import init, { Keyring, requestPersistentStorage } from "./pkg/cryptex.js";
await init();
// An encrypted Turso database, persisted in IndexedDB. These are the defaults.
const keyring = await Keyring.open("password=hunter2 salt=0okm9ijn8uhb7ygv", "settings");
await keyring.set("api-token", new TextEncoder().encode("s3cret"));
const token = keyring.get("api-token"); // Uint8Array
await keyring.delete("api-token");
// Ask the browser not to evict the origin's storage.
await requestPersistentStorage();
await keyring.close();
```
`open(connection, name, options)` chooses where the keyring lives:
| `backend` | `store` | What is persisted |
|-----------|---------|-------------------|
| `"turso"` (default) | `"indexeddb"` (default) | the encrypted database image, saved after every change |
| `"turso"` | `"opfs"` | the database file itself, in the origin private file system |
| `"turso"` | `"memory"` | nothing; `export()` the image yourself |
| `"memory"` | `"indexeddb"` | the sealed image, saved after every change |
| `"memory"` | `"localstorage"` | a sealed blob under `localStorage["cryptex:<name>"]` |
| `"memory"` | `"memory"` | nothing |
`import(connection, image, options)` reopens an image returned by `export()`,
and `rekey(connection)` changes its password.
`keyring.keys()` lists the ids inside an open keyring, and
`storedKeyrings({ store })` lists the keyrings the origin already has in
`"indexeddb"` (the default), `"localstorage"` or `"opfs"`, without opening
anything. Listing OPFS works from a page; opening an OPFS keyring does not.
Every store keeps the data encrypted; the key comes from the password (or raw
key) in the connection string, so a store with the wrong connection string
fails with `AccessDenied` instead of returning garbage.
A `set` or `delete` that resolves has reached the store, and every call on a
closed keyring throws. An IndexedDB or localStorage keyring also holds a Web
Lock named after itself, so a second tab that opens the same name fails with
`AccessDenied` instead of overwriting the first tab's secrets; `close()`
releases the lock, and with OPFS the sync access handle, so close a keyring
before opening it again in the same context. The Rust-level
`WebStorageKeyring` does not take that lock: it is synchronous by design, and
taking a lock is not.
OPFS needs `createSyncAccessHandle()`, which browsers expose only in a
dedicated worker, so `store: "opfs"` is refused on the main thread. A worker
can use IndexedDB too. `examples/web/` has a page that uses IndexedDB and a
worker that uses OPFS; serve it over HTTP (`python3 -m http.server`), because
wasm modules and OPFS are not available on `file://` URLs.
Errors are `Error` objects whose message starts with the kind, so a caller can
switch on `ItemNotFound:`, `AccessDenied:`, `TypeError:` or `GeneralError:`
without parsing the rest.
Two costs are worth planning for. Any script the origin loads can read
IndexedDB, OPFS and `localStorage`, so the encryption protects against other
origins and other users, not against a compromised page.
`requestPersistentStorage()` asks the browser to keep the data, but it may
refuse, and clearing site data always removes it. Key derivation runs Argon2,
which blocks the thread it runs on: with a large `memory=` value, open the
keyring in a worker or the page freezes until it finishes.
What the encryption does not detect is a *stale* image. Code that can write
origin storage can put back an earlier one, or drop the `-wal` beside it, and
the keyring opens with the secrets it held then; a rotated secret can come
back that way. Keep a version or counter of your own outside the store if that
matters.
The password reaches the library through the connection string, which is a
small DSL: `\` starts an escape, a leading `'` quotes a value, and whitespace
separates entries. A password containing those characters is not passed
through unchanged, so derive a key yourself or hex-encode the secret when the
password is user-supplied. A repeated keyword (`password=a password=b`) is an
error rather than a silent override. The examples use one fixed salt to stay
readable; an application should give each keyring a salt of its own.
### Bringing your own storage
`TursoKeyring` can adopt a connection you opened, or open through an IO you
supply, so one database can hold the keyring's `secrets` table and your own
tables under a single key:
```rust
use cryptex::turso::TursoKeyring;
// A connection opened by the caller, e.g. with a custom IO and encryption.
let keyring = TursoKeyring::from_connection(conn)?;
// Or let cryptex build the database through your IO (such as OPFS).
let keyring = TursoKeyring::with_io(io, "keyring.db3", ¶ms)?;
# Ok::<(), cryptex::KeyRingError>(())
```
In both cases cryptex creates and owns only its own tables, and `rekey` reports
an error because cryptex does not own that storage: copy the secrets into a
keyring that owns its file instead. `cryptex::turso` re-exports `Connection`,
`TursoBuilder` and `core` so callers construct matching types.
Turso's synchronous API is driven on the current thread. Native builds park the
thread while a future is pending; wasm builds poll a bounded number of times
and return an error instead of spinning, so an IO backend must complete its
reads in place.
On WASI there is no file locking: `try_lock` reports `Unsupported`, which the
keyring treats as success, and the default keyring directory is `./.cryptex`
because there is no home directory. Keep a single writer per database there.
The CLI is native only: a wasm binary prints that and exits.
---
## KMS/HSM Backends
Beyond OS keychains and SQLCipher, Cryptex supports a class of backends where a **Key Management
Service (KMS) or Hardware Security Module (HSM)** holds one master HMAC-SHA256 key that never
leaves the device, and Cryptex stores an unlimited number of secrets as small encrypted files on
disk. This avoids pushing secrets into the KMS itself while still ensuring that every secret is
cryptographically bound to a specific key and device.
### Cryptographic protocol
For each secret stored by a KMS backend:
1. **Nonce** (12 bytes): `SHA-256("cryptex-nonce" ‖ OS_rng₃₂ [‖ backend_rng₃₂])[..12]`
Two independent entropy sources are mixed so that compromising either one alone does not
allow nonce prediction.
2. **K_enc** (32 bytes): `HMAC-SHA256(master_key, "cryptex-keyring" ‖ version ‖ key_id ‖ device_id ‖ nonce)`
This is computed **inside** the KMS/HSM — the raw key never leaves. The HMAC output is
used directly as a 32-byte AES-256-GCM encryption key, making it per-entry and per-nonce
unique.
3. **Ciphertext**: `AES-256-GCM(K_enc, nonce, plaintext, AAD)`
where `AAD = version ‖ key_id ‖ device_id ‖ nonce`.
The `key_id` is the backend's identifier for the signing key (e.g. `"2"` for YubiHSM, a UUID
for AWS KMS). The `device_id` is a 16-byte hash derived from the device/instance identity
(e.g. YubiHSM serial number). Both are stored inside the entry file and bound into the AAD and
HMAC input, so a ciphertext created on one device with one key cannot be decrypted with a
different device or a different key — the GCM authentication tag will fail.
Each secret is stored as a binary file under `~/.cryptex/<backend>/<service>/`, named
`hex(SHA-256(secret_id)).bin`. The file format is:
```
[u16 LE: id_len][id bytes][entry bytes]
```
where `entry bytes` is:
```
version(1) | key_id_len_LE(2) | key_id(variable) | device_id(16) | nonce(12) | ct_len_LE(4) | ciphertext
```
### The `KmsBackend` trait
All KMS/HSM backends implement the `KmsBackend` trait:
```rust
pub trait KmsBackend: Send + Sync {
/// Short filesystem-safe name, used as a storage directory component.
fn backend_name(&self) -> &'static str;
/// The key identifier string (e.g. "2", a UUID, or a KMS ARN).
fn key_id(&self) -> &str;
/// A stable 16-byte identifier for the device/instance (e.g. from HSM serial).
fn device_id(&self) -> [u8; 16];
/// Optional backend entropy — return Ok(Vec::new()) if unavailable.
fn get_random(&self, n: usize) -> Result<Vec<u8>>;
/// Compute HMAC-SHA256 using the backend's secret key.
fn hmac_sha256(&self, msg: Vec<u8>) -> Result<[u8; 32]>;
}
```
A `KmsKeyRing<B: KmsBackend>` is automatically a `KeyRing` once a backend is provided — all
encryption, decryption, nonce generation, and file I/O are handled by the shared layer.
---
### YubiHSM 2
The `yubihsm-usb` and `yubihsm-http` features enable the [YubiHSM 2](https://www.yubico.com/products/hardware-security-module/) backend.
One HMAC-SHA256 key is stored on the device; Cryptex derives a per-secret AES-256-GCM key
from it without ever exposing the master key.
**Cargo features:**
```toml
[dependencies]
cryptex = { version = "...", features = ["yubihsm-usb"] }
# or
cryptex = { version = "...", features = ["yubihsm-http"] }
```
`yubihsm-usb` communicates directly over libusb (no daemon needed).
`yubihsm-http` communicates via the `yubihsm-connector` HTTP daemon.
#### One-time setup
Before first use, generate the HMAC key on the device (run once per device):
```rust
use cryptex::yubihsm::YubiHsmKeyRing;
YubiHsmKeyRing::setup(
"connector=usb auth_key_id=1 password=password domain=1",
2, // object ID for the new HMAC key
)?;
```
#### Connection string
```text
# USB (no daemon required, just libusb):
connector=usb hmac_key_id=2 auth_key_id=1 password=password domain=1 service=myapp
# HTTP (requires yubihsm-connector running locally):
connector=http addr=127.0.0.1 port=12345 hmac_key_id=2 auth_key_id=1 password=password domain=1 service=myapp
```
| Parameter | Default | Description |
|-----------|---------|-------------|
| `connector` | `usb` | Transport: `usb` or `http` |
| `hmac_key_id` | `1` | Object ID of the HMAC-SHA256 key on the YubiHSM |
| `auth_key_id` | `1` | Object ID of the authentication key |
| `password` | `password` | Authentication key password |
| `domain` | `1` | HSM domain (1–16) |
| `service` | `default` | Service name, used as a storage subdirectory |
| `addr` | `127.0.0.1` | HTTP connector address (http only) |
| `port` | `12345` | HTTP connector port (http only) |
#### Usage
```rust
use cryptex::{KeyRing, NewKeyRing};
use cryptex::yubihsm::YubiHsmKeyRing;
let mut ring = YubiHsmKeyRing::new(
"connector=usb hmac_key_id=2 auth_key_id=1 password=password domain=1 service=myapp"
)?;
ring.set_secret("db-password", b"s3cr3t")?;
let value = ring.get_secret("db-password")?;
ring.delete_secret("db-password")?;
// List stored secrets (id, key_id, device_id) without decrypting:
let entries = ring.list_hsm_secrets()?;
```
---
### Nitrokey 3 (FIDO2 `hmac-secret`)
The `nitrokey` feature uses a [Nitrokey 3](https://www.nitrokey.com/products/nitrokeys) over USB.
The Nitrokey has no HMAC key object like the YubiHSM, so the backend uses FIDO2's `hmac-secret`
extension: the token generates a random key for a credential, never exports it, and returns
`HMAC-SHA256(key, SHA-256(msg))` on request. That is the HMAC the shared protocol above needs.
Nothing is Nitrokey-specific, so a YubiKey, SoloKey or other FIDO2 key with `hmac-secret` works
too.
The firmware requires a touch for every `hmac-secret` call, so each `get` and `set` waits for a
touch (prompted on stderr). `list` and `delete` do not. FIDO2 has no serial number or random
number command, so `device_id` is derived from the credential ID and nonces use the OS RNG alone.
#### One-time setup
Create the credential (one touch) and keep the ID it returns:
```rust
use cryptex::nitrokey::NitrokeyKeyRing;
let credential = NitrokeyKeyRing::setup("")?; // or "pin=123456" if the token has a FIDO2 PIN
```
```bash
cryptex -k nitrokey setup
```
The credential ID is not stored on the token. Losing it loses the secrets, so back it up with
the files in `~/.cryptex/nitrokey/`.
#### Connection string
```text
credential=<hex from setup> service=myapp
credential=<hex from setup> pin=123456 rp_id=cryptex service=myapp
```
| Parameter | Default | Description |
|-----------|---------|-------------|
| `credential` | (required) | Credential ID from setup, as hex |
| `pin` | (none) | FIDO2 PIN, if the token has one |
| `rp_id` | `cryptex` | Relying party ID; must match setup |
| `service` | `default` | Service name, used as a storage subdirectory |
```bash
cryptex -k nitrokey set "credential=<hex> service=myapp" aws-key ./aws-key.txt
cryptex -k nitrokey get "credential=<hex> service=myapp" aws-key
```
The `nitrokey` example does the setup on its first run and a set, get, list and delete after:
```bash
cargo run --example nitrokey --no-default-features --features nitrokey
```
## Future KMS Backends
The `KmsBackend` trait is designed to be implemented by any system that can compute an
HMAC-SHA256 without exposing the raw key. The following backends are planned:
### AWS KMS
AWS Key Management Service supports [GenerateMAC](https://docs.aws.amazon.com/kms/latest/APIReference/API_GenerateMAC.html)
for HMAC-SHA256 using a symmetric HMAC key. The backend's `key_id` would be the KMS key ARN
or alias (e.g. `arn:aws:kms:us-east-1:123456789012:key/mrk-...`), and `device_id` would
be derived from the AWS account ID and region to provide geographic/account binding.
```text
# Anticipated connection string:
provider=aws-kms key_id=arn:aws:kms:us-east-1:123456789012:key/mrk-... region=us-east-1 service=myapp
```
### Azure Key Vault
Azure Key Vault supports [HMAC operations](https://learn.microsoft.com/en-us/rest/api/keyvault/keys/sign/sign)
via its managed HSM. The backend's `key_id` would be the Key Vault key identifier URI, and
`device_id` would be derived from the vault's tenant ID and vault name.
```text
# Anticipated connection string:
provider=azure-keyvault vault=https://myvault.vault.azure.net key_id=my-hmac-key service=myapp
```
### HashiCorp Vault
HashiCorp Vault's [Transit secrets engine](https://developer.hashicorp.com/vault/docs/secrets/transit)
supports HMAC computation on stored keys via the `/transit/hmac/:key_name` endpoint. The
backend's `key_id` would be the Transit key name, and `device_id` would be derived from
the Vault cluster identifier.
```text
# Anticipated connection string:
provider=vault addr=https://vault.example.com:8200 token=hvs.xxx key_id=my-hmac-key service=myapp
```
---
## Upgrading to 3.0
3.0 changes how the OS keyrings and the encrypted VFS and Turso encrypted IO keyrings store
secrets:
- **Windows:** secrets go straight into Credential Manager, which already encrypts them with your login. 2.x also wrapped them in a second DPAPI layer; 3.0 recognises those, unwraps them on the first `get` and stores them again without the wrapper. Secrets are now stored with `CRED_PERSIST_LOCAL_MACHINE`, so they no longer roam with a domain profile.
- **macOS:** `set` and `delete` now make one keychain call instead of a lookup followed by a write, so the keychain checks access once. Existing items are read as before. An unsigned build is still asked for access after each rebuild, because macOS ties "Always Allow" to the binary's signature.
- **Linux:** new items are tagged `application=cryptex` instead of `lox`. Items with the old tag are still read and deleted, and `set` replaces them.
- **Encrypted VFS and Turso encrypted IO:** the file format changed. Files now start with a header, pages carry a 24-byte nonce slot and XChaCha20-Poly1305 replaces ChaCha20-Poly1305, so 3.0 cannot open a 2.x keyring file. Move the secrets into a new keyring with `cryptex::migrate::migrate_v2` or `cryptex -k evfs migrate` (see [File keyrings from the command line](#file-keyrings-from-the-command-line)); a Turso keyring must have been closed cleanly so its WAL is empty. Use `cipher=xchacha20poly1305` where you used `cipher=chacha20poly1305`. SQLCipher and native Turso files are unchanged.
## Using as a library
This crate enables running as a Rust library.
```rust
use cryptex::{get_os_keyring, KeyRing};
let mut keyring = get_os_keyring("myapp")?;
keyring.set_secret("test_key", b"secret")?;
// Retrieve secret later
let secret = keyring.get_secret("test_key")?;
// Remove the secret from the keyring
keyring.delete_secret("test_key")?;
```
A file keyring is opened from a connection string and a directory (`None` for `~/.cryptex`):
```rust
use cryptex::KeyRing;
use cryptex::encrypted_vfs::EncryptedVfsKeyring;
let params = "password='correct horse battery staple'".parse()?;
let mut keyring = EncryptedVfsKeyring::with_params(¶ms, None)?;
keyring.set_secret("test_key", b"secret")?;
let ids = keyring.keys()?; // every id, in order
```
## Run the program
Basic Usage
Requires dbus library on Linux.
On Ubuntu, this is `libdbus-1-3` when running.
On RedHat, this is `dbus` when running.
Gnome-keyring or KWallet must also be installed on Linux.
*Cryptex* can be run either using **cargo run -- \<args\>** or if it is already built from [source](#build-from-source)
using *./cryptex*.
*Cryptex* tries to determine if input is a file or text. If a file exists that matches the entered text, *Cryptex* will
read the contents. Otherwise, it will prompt the user for either the id of the secret or to enter a secret.
*Cryptex* stores secrets based on a service name and an ID. The service name is the name of the program or process that only is allowed to access the secret with that ID.
Secrets can be retrieved, stored, or deleted.
When secrets are stored, care should be given to not pass the value over the command line as it could be stored in the command line history.
For this reason, either put the value in a file or *Cryptex* will read it from STDIN. After *Cryptex* stores the secret, Cryptex will securely wipe it from memory.
### File keyrings from the command line
`--keyring` also takes `sqlcipher`, `evfs`, `turso` and `turso-io`, when the matching feature is
compiled in. For these the SERVICE argument is the keyring's directory, or `default` for
`~/.cryptex`. The connection string is read from `CRYPTEX_CONNECTION`; without it *Cryptex* prompts
for the password (and the salt, for `sqlcipher` and `turso`). It is never taken from the command
line, where other users could see it.
```bash
cryptex -k evfs set ~/.my-keyring aws-key ./aws-key.txt
cryptex -k evfs get ~/.my-keyring aws-key
cryptex -k evfs list ~/.my-keyring
```
`migrate` copies the secrets of a 2.x `evfs` or `turso-io` keyring file into a 3.x keyring. The
2.x connection string is read from `CRYPTEX_V2_CONNECTION`, or prompted for:
```bash
cryptex -k evfs migrate ~/.my-keyring-3 ~/.cryptex/keyring.db3
```
## Caveat
One remaining problem is how to solve the service name provided to *Cryptex*. Ideally *Cryptex* could compute it instead of supplied from the calling endpoint which can lie about the name.
We can imagine an attacker who wants access to the AWS credentials in the keychain just needs to know the service name and the id of the secret to request it. Access is still blocked by
the operating system if the attacker doesn't know the keychain credentials similar to a password vault. If *Cryptex* could compute the service name then this makes it harder for an attacker
to retrieve targeted secrets. However, this is better than the secrets existing in plaintext in code, config files, or environment variables.
## Examples
*Cryptex* takes at least two arguments: service_name and ID.
When storing a secret, an additional parameter is needed. If omitted (the preferred method) the value is read from STDIN.
For a file-backed keyring (`--keyring sqlcipher|evfs|turso|turso-io`) the service_name is the
keyring's directory, and the connection string comes from `CRYPTEX_CONNECTION` or a prompt; see
[File keyrings from the command line](#file-keyrings-from-the-command-line).
### Storing a secret
```bash
cryptex set aws 1qwasdrtyuhjnjyt987yh
prompt> ...<Return>
Success
```
### Retrieve a secret
```bash
cryptex get aws 1qwasdrtyuhjnjyt987yh
<Secret Value>
```
### Delete a secret
```bash
cryptex delete aws 1qwasdrtyuhjnjyt987yh
```
### List all secrets
*Cryptex* can read all values stored in the keyring. List will just list the name
of all the values in the keyring without retrieving their actual values.
```bash
cryptex list
```
```
{"application": "cryptex", "id": "apikey", "service": "aws", "username": "mike", "xdg:schema": "org.freedesktop.Secret.Generic"}
{"application": "cryptex", "id": "walletkey", "service": "indy", "username": "mike", "xdg:schema": "org.freedesktop.Secret.Generic"}
```
### Peek secrets
*Cryptex* can retrieve all or a subset of secrets in the keyring. Peek without
any arguments will pull out all keyring names and their values, as the OS
keyring stores them. Peek is only for OS keyrings, and its filtering differs by
operating system.
For OSX, filtering is based on the **kind** that should be read. It can be __generic__ or __internet__ passwords.
__generic__ only requires the *service* and *account* labels. __internet__ requires the *server*, *account*, *protocol*, *authentication_type* values.
Filters are supplied as name value pairs separated by `=` and multiple pairs separated by a comma.
```bash
cryptex peek service=aws,account=apikey
```
For Linux, filtering is based on a subset of name value pairs of the attributes that match.
For example, if the attributes in the keyring were like this
```
{"application": "cryptex", "id": "apikey", "service": "aws", "username": "mike", "xdg:schema": "org.freedesktop.Secret.Generic"}
{"application": "cryptex", "id": "walletkey", "service": "indy", "username": "mike", "xdg:schema": "org.freedesktop.Secret.Generic"}
```
To filter based on *id*, run
```bash
cryptex peek id=apikey
```
To filter based on *username* AND *service*, run
```bash
cryptex peek username=mike,service=aws
```
For Windows, filtering is based on the credentials targetname and globbing.
For example, if *list* returned
```
{"targetname": "MicrosoftAccount:target=SSO_POP_Device"}
{"targetname": "WindowsLive:target=virtualapp/didlogical"}
{"targetname": "LegacyGeneric:target=IEUser:aws:apikey"}
```
then filtering searches everything after `:target=`. In this case, if the value
to be peeked is IEUser:aws:apikey, the following will return just that result
```bash
cryptex.exe peek IE*
cryptex.exe peek IE*apikey
cryptex.exe peek IEUser:aws:apikey
```
## Build from source
[build-from-source]: #build-from-source
To make a distributable executable, run the following commands:
1. On Linux install the dbus library. On a Debian-based OS this is `libdbus-1-dev`. On a RedHat-based OS this is `dbus-devel`.
1. `curl https://sh.rustup.rs -sSf | sh -s -- -y` — installs the Rust compiler.
1. `cargo build --release` — when this is finished the executable is `target/release/cryptex`.
1. For \*nix users `cp target/release/cryptex /usr/local/bin && chmod +x /usr/local/bin/cryptex`.
1. For Windows users copy `target/release/cryptex.exe` to a folder and add that folder to your `%PATH` variable.
For Nitrokey (or any FIDO2 key) support build with `--features nitrokey`; on Linux this needs
`libudev-dev` and read access to the token's `/dev/hidraw*` node (a udev rule, as for any FIDO2
key).
For YubiHSM support, install [libusb](https://libusb.info/) first, then build with:
```bash
cargo build --release --features yubihsm-usb
# or
cargo build --release --features yubihsm-http
```
For file keyrings, add their features; `encrypted-vfs` needs libclang. Add `fips` to restrict
everything to FIPS-approved algorithms:
```bash
cargo build --release --features file,encrypted-vfs,turso,turso-encrypted-io
cargo build --release --no-default-features --features encrypted-vfs,fips
```
Libcryptex is the library that can be linked to programs to manage secrets.
Use the library for the underlying operating system that meets your needs:
- **libcryptex.dll** — Windows
- **libcryptex.so** — Linux
- **libcryptex.dylib** — Mac OS X
## Future work
- **AWS KMS backend** — HMAC-SHA256 via `GenerateMAC`, key ID is a KMS key ARN or alias.
- **Azure Key Vault backend** — HMAC via the managed HSM sign endpoint, key ID is a Key Vault key URI.
- **HashiCorp Vault backend** — HMAC via the Transit secrets engine, key ID is a Transit key name.
- Allow for communication over Unix or TCP sockets with *Cryptex* running as a daemon process.
- Allow for steganography methods like using images or Microsoft Office files for storing the secrets.
- Allow for other enclaves like LastPass, 1Password.