mirror of
https://github.com/shadowsocks/ShadowsocksX-NG.git
synced 2026-11-23 14:24:12 +00:00
refactor: adopt age configuration storage
Replace the custom encrypted container with AgeSwift 0.1.0 so standard age tools can inspect sensitive configuration independently of the app. Use independent Keychain X25519 identities for catalog.age and proxy-listening.age. Preserve atomic commits and confirmed recovery; reject historical NG2 formats without migration or cleanup.
This commit is contained in:
@@ -1,91 +1,23 @@
|
||||
# Server Library Encryption File Format v2
|
||||
# Sensitive Configuration Encryption with age
|
||||
|
||||
English | [简体中文](server-library-encryption-format.zh-CN.md)
|
||||
|
||||
Recorded on 2026-10-18. Implementation snapshot: `507917a`.
|
||||
The server library and proxy listening configuration use standard [age v1](https://age-encryption.org/v1) files through [AgeSwift](https://github.com/qiuyuzhou/AgeSwift). See [ADR-0050](adr/0050-age-encrypted-configuration-storage.md) for the decision and recovery boundaries.
|
||||
|
||||
This document describes the `catalog.enc` format at that commit. It supports maintenance, troubleshooting, and compatible reader implementations. This is a point-in-time format description, not a continuously maintained account of the latest implementation. The source code and [ADR-0035](adr/0035-encrypt-persistent-server-library.md) define current behavior.
|
||||
## Files and payloads
|
||||
|
||||
## 1. File and Protection Scope
|
||||
Both files live in `~/Library/Application Support/ShadowsocksX-NG2/configuration/`:
|
||||
|
||||
The default path is `~/Library/Application Support/ShadowsocksX-NG2/configuration/catalog.enc`. The file is binary:
|
||||
|
||||
```text
|
||||
complete file = plaintext header || nonce || ciphertext || tag
|
||||
additional authenticated data (AAD) = the original 45 header bytes
|
||||
algorithm = AES-256-GCM
|
||||
```
|
||||
|
||||
`||` means byte concatenation. The header is authenticated but not encrypted. The file does not contain the master key.
|
||||
|
||||
The ciphertext contains the complete configuration catalog, subscription records, ordered favorites, with passwords, complete plugin options, and subscription URLs stored directly in their owning records. This format does not cover the runtime configuration `sslocal-active.json`, derived listener authentication files, or files that users explicitly share or export.
|
||||
|
||||
## 2. Binary Layout
|
||||
|
||||
Offsets start at zero. All offsets and lengths are in bytes. Let `P` be the UTF-8 byte length of the complete payload before encryption. The AES-GCM ciphertext also has length `P`.
|
||||
|
||||
| Offset | Length | Field | Encoding and Meaning |
|
||||
| --- | --- | --- | --- |
|
||||
| 0 | 8 | magic | ASCII `SSXNG2LB`; hexadecimal `53 53 58 4E 47 32 4C 42` |
|
||||
| 8 | 1 | envelopeVersion | The binary value `0x02`, not the character `2` |
|
||||
| 9 | 36 | keyID | A UUID encoded as UTF-8 text, including hyphens, without quotes, a terminating zero byte, or a newline |
|
||||
| 45 | 12 | nonce | A random nonce generated by CryptoKit with its default configuration |
|
||||
| 57 | `P` | ciphertext | AES-GCM ciphertext of the complete payload |
|
||||
| `57 + P` | 16 | tag | GCM authentication tag |
|
||||
|
||||
Thus:
|
||||
|
||||
```text
|
||||
headerLength = 8 + 1 + 36 = 45
|
||||
combined = nonce || ciphertext || tag
|
||||
fileLength = P + 73
|
||||
P = fileLength - 73
|
||||
```
|
||||
|
||||
The file has no additional length field, padding, separator, compression layer, or outer Base64 encoding. An example `keyID` is `65A4F8AE-28F6-46A2-B61F-7CFA9A85D7F2`. The writer generates this text with `UUID.uuidString`. Do not substitute the UUID's 16-byte binary representation.
|
||||
|
||||
Version 2 has no separate algorithm field. Version `0x02` specifies AES-256-GCM. The reader does not try a different algorithm after a failure.
|
||||
|
||||
## 3. Master Key and Authentication
|
||||
|
||||
`SymmetricKey(size: .bits256)` generates a random 32-byte master key. The key is neither a user password nor a value derived from `keyID`.
|
||||
|
||||
Production storage uses a Generic Password item in the classic keychain:
|
||||
|
||||
| Attribute | Value |
|
||||
| --- | --- |
|
||||
| `kSecClass` | `kSecClassGenericPassword` |
|
||||
| `kSecAttrService` | `com.qiuyuzhou.ShadowsocksX-NG2.server-library` |
|
||||
| `kSecAttrAccount` | The `uuidString` of the UUID parsed from the file header |
|
||||
| `kSecValueData` | The raw 32-byte master key, not hexadecimal or Base64 text |
|
||||
| `kSecAttrSynchronizable` | `false` |
|
||||
| `kSecUseDataProtectionKeychain` | `false` |
|
||||
|
||||
When creating the item, `SecAccessCreate` receives a trusted application list containing only the current application. The header identifies the key; it does not grant keychain access. A copy of `catalog.enc` without the corresponding master key cannot decrypt the server library.
|
||||
|
||||
The writer uses CryptoKit's default nonce generation and generates a new nonce for each save. Normal saves retain the master key. A user-confirmed library reset generates a new key. The nonce and tag use the layout provided by `AES.GCM.SealedBox.combined`.
|
||||
|
||||
Encryption and decryption both use the original header bytes as AAD. A compatible reader must use the original 45 bytes from the file. Do not replace them with a header reconstructed after parsing the UUID.
|
||||
|
||||
## 4. Decrypted Payload
|
||||
|
||||
Decryption produces the catalog itself as UTF-8 JSON. There is no outer `catalog`/`secrets` object, nested Base64 catalog, or separate credential reference mapping.
|
||||
|
||||
The writer emits catalog schema v7, and the reader accepts only v7. This schema version is independent of the header's envelopeVersion: `0x02` does not mean catalog schema v2.
|
||||
|
||||
### 4.1 Catalog JSON
|
||||
|
||||
All five top-level fields are required, including arrays that are empty:
|
||||
|
||||
| Field | JSON Type | Meaning |
|
||||
| File | Decrypted UTF-8 JSON | Maximum plaintext size |
|
||||
| --- | --- | --- |
|
||||
| `version` | number | Catalog schema version, exactly `7` |
|
||||
| `rootChildren` | array | Ordered root-level node identities |
|
||||
| `entries` | array | All nodes, sorted by node `id.rawValue` when written |
|
||||
| `subscriptions` | array | Subscription records, including their URL values and refresh information |
|
||||
| `favoriteIDs` | array | Ordered favorite node identities |
|
||||
| `catalog.age` | Catalog schema v7: `version`, `rootChildren`, `entries`, `subscriptions`, `favoriteIDs` | 64 MiB |
|
||||
| `proxy-listening.age` | `{ "version": 1, "configuration": { "local": …, "lan": … } }` | 1 MiB |
|
||||
|
||||
An empty library has this payload:
|
||||
The server library contains the entire catalog, subscriptions and ordered favorites, including server passwords, complete plugin options and subscription URLs in their owning records. Listener credentials belong to the separate listening configuration. Runtime JSON, LAN authentication sidecars, user exports and sharing are outside this format's scope.
|
||||
|
||||
Writers produce binary age v1, with a single X25519 recipient and no application header, UUID prefix, sidecar index, outer Base64 layer or custom cryptographic container. Readers also accept standard ASCII armor. Saving an armored input writes binary age. JSON schema versions are inside the encrypted payload, independent of the age format version. Readers validate the complete decoded model before publishing it.
|
||||
|
||||
An empty catalog payload is:
|
||||
|
||||
```json
|
||||
{
|
||||
@@ -97,77 +29,56 @@ An empty library has this payload:
|
||||
}
|
||||
```
|
||||
|
||||
`rootChildren` and each configuration group's child array define hierarchy and display order. Do not substitute the order of the `entries` array. The writer enables `prettyPrinted` and `sortedKeys`; compatible readers must not depend on whitespace or object key order.
|
||||
Catalog hierarchy and ordering come from `rootChildren` and group child arrays. Secrets remain ordinary record values, not credential references. Codable models define the full schema; whitespace and object key order carry no meaning.
|
||||
|
||||
### 4.2 Secrets Belong to Records
|
||||
## Keychain identities
|
||||
|
||||
| Owning Model | Field | JSON Type | Meaning |
|
||||
| --- | --- | --- | --- |
|
||||
| `ServerFields` | `password` | string | Server password |
|
||||
| `ServerFields` | `pluginOptions` | optional string | Complete, opaque plugin options |
|
||||
| `SubscriptionRecord` | `url` | string | Complete subscription URL |
|
||||
Each store uses its own classic login Keychain Generic Password service:
|
||||
|
||||
These are ordinary string values inside the decrypted JSON, protected by encryption of the complete payload. The writer does not replace them with `passwordRef`, `pluginOptionsRef`, or `urlRef`, and there is no reference-set consistency check. LAN listener authentication credentials remain outside the server library.
|
||||
|
||||
`ServerFields` is the associated value of `CatalogEntry.Kind.server`; its JSON is nested under the node's `kind.server._0` object. A subscription's `url` is directly inside its `subscriptions` array record. Optional fields are omitted when nil by the synthesized Codable encoder. The corresponding Swift Codable models define the complete encoding of nodes, subscriptions, enum fields, and optional metadata; this document does not duplicate the full catalog schema.
|
||||
|
||||
## 5. Read Order and Errors
|
||||
|
||||
For an existing `catalog.enc`, the reader checks the file in this order:
|
||||
|
||||
1. Check the file size.
|
||||
2. Validate magic.
|
||||
3. Validate envelopeVersion.
|
||||
4. Parse keyID.
|
||||
5. Use the cached key when its ID matches, or read the corresponding key from Keychain; verify its length is 32 bytes.
|
||||
6. Authenticate and decrypt `combined`, using the original header as AAD.
|
||||
7. Decode the catalog JSON into the current payload model.
|
||||
8. Require schema v7, then validate unique node identities, catalog structure, subscription identities and fixed-group associations, and favorites.
|
||||
|
||||
The current limit is `P ≤ 64 × 1024 × 1024`, or 67,108,864 bytes. It applies to the complete catalog JSON, including the encoded password, plugin option, and URL values. There is no nested Base64 overhead.
|
||||
|
||||
The file size check accepts **73–67,108,937 bytes**. The 73-byte minimum is only a structural check. An empty payload is not valid JSON, so a 73-byte file cannot represent a valid empty library.
|
||||
|
||||
| Condition | Current Error |
|
||||
| File | Service |
|
||||
| --- | --- |
|
||||
| Size out of range, invalid magic, or invalid UUID | `ServerLibraryError.malformedFile` |
|
||||
| envelopeVersion is not `0x02` | `ServerLibraryError.unsupportedVersion` |
|
||||
| Key missing or not 32 bytes long | `ServerLibraryError.keyUnavailable` |
|
||||
| GCM authentication or SealedBox parsing fails | `ServerLibraryError.authenticationFailed` |
|
||||
| Catalog JSON decoding, schema version, or catalog structure validation fails | `CatalogFileStore.PersistenceError.corrupt` |
|
||||
| Keychain denies access or requires interactive authorization | `CredentialStoreError.keychainStatus`, preserving the system status code |
|
||||
| The file disappears after this storage instance loaded it, or a save is attempted without a successfully loaded or reset library | `ServerLibraryError.notLoaded` |
|
||||
| `catalog.age` | `com.qiuyuzhou.ShadowsocksX-NG2.server-library.age` |
|
||||
| `proxy-listening.age` | `com.qiuyuzhou.ShadowsocksX-NG2.proxy-listening.age` |
|
||||
|
||||
File system read errors propagate as their original errors. If multiple conditions fail, the reader reports the first error encountered in its read order. Codable decoding precedes the schema version check, so an incompatible payload can fail decoding before its version is checked.
|
||||
Each account is a UUID; its value is the UTF-8 standard `AGE-SECRET-KEY-1...` identity, not raw AES bytes. Items do not synchronize and do not use the Data Protection Keychain. Creation grants access only to the current application through a classic Keychain ACL.
|
||||
|
||||
When `catalog.enc` exists, a read failure does not trigger fallback to `catalog.json`, plaintext decoding, or automatic empty-library creation. The application blocks library writes and preserves the existing proxy runtime. Overwriting the library requires explicit user confirmation to discard the existing configuration.
|
||||
The file contains no Keychain account locator. The reader enumerates accounts in the relevant service and tries identities until one decrypts the file. Inaccessible or unrelated candidates do not prevent an accessible matching identity from succeeding. Normal saves reuse the matched identity, cached in the current process. A confirmed reset stores and reads back a new identity before atomically replacing ciphertext; older identities remain available if the commit fails or the process exits midway. Records therefore grow with resets. Identity cleanup and manual rotation are not provided.
|
||||
|
||||
## 6. Writing and Historical Formats
|
||||
Startup/background reads do not request authorization UI. Existing explicit application interaction controls remain in force. Losing a matching identity prevents decryption; changing the file format does not bypass Keychain authorization or provide independent recovery.
|
||||
|
||||
The write sequence is: encode the complete catalog JSON → encrypt in memory → write an encrypted temporary file → atomically replace the target. There is no separate secret collection or credential write journal for the library. Workflow changes use a complete working value; the application publishes the new committed value only after persistence succeeds.
|
||||
## Inspect with standard tools
|
||||
|
||||
The directory permission is `0700`. Temporary files are created with permission `0600`. Temporary files reside in the target directory and use the name `.catalog.enc.tmp-<UUID>`. They contain the complete encrypted format too. The current writer does not explicitly call `fsync`; this document does not promise durability through power loss.
|
||||
Install the reference CLI with `brew install age`. In Keychain Access, search for the exact service above and inspect the account UUIDs. Use the system `security` tool to retrieve an identity after system authorization. Replace `ACCOUNT_UUID`; repeat with other accounts into the same identity file if the service contains several identities.
|
||||
|
||||
NG2 has not shipped, so the reader does not migrate historical NG2 data:
|
||||
```bash
|
||||
umask 077
|
||||
workdir=$(mktemp -d)
|
||||
trap 'rm -rf "$workdir"' EXIT
|
||||
security find-generic-password \
|
||||
-s com.qiuyuzhou.ShadowsocksX-NG2.server-library.age \
|
||||
-a ACCOUNT_UUID -w >> "$workdir/identities.txt"
|
||||
age --decrypt -i "$workdir/identities.txt" \
|
||||
"$HOME/Library/Application Support/ShadowsocksX-NG2/configuration/catalog.age" | jq .
|
||||
```
|
||||
|
||||
- An existing envelope v1 file is rejected as `ServerLibraryError.unsupportedVersion`; catalog schemas v1–v6 are not supported.
|
||||
- If `catalog.enc` is absent but `catalog.json` exists, startup returns `ServerLibraryError.unsupportedVersion`. It checks only the old file's existence; it does not read its content, resolve old per-item Keychain credentials, or delete either.
|
||||
- A fresh storage instance creates an encrypted empty library only when neither library file exists. It stores and reads back the new master key before committing ciphertext.
|
||||
- A user-confirmed reset writes a new empty `catalog.enc` with a new master key. It does not delete the old `catalog.json` or old per-item Keychain credentials. The current key and committed application state change only after the new file is successfully saved.
|
||||
For listening configuration, substitute its service and `proxy-listening.age`. Choose one-time authorization when prompted; do not broaden the application's ACL. The identity file is a secret and the output contains configuration credentials. These commands deliberately export a temporary identity for maintenance; the application never writes identities to ordinary files, logs or diagnostic reports. Removal does not promise secure erasure.
|
||||
|
||||
The user-facing import from the old ShadowsocksX-NG application remains available. It constructs new records carrying their secret values; it is distinct from migration of NG2's historical storage formats.
|
||||
Standard age tools can also encrypt JSON to the corresponding `age1...` recipient. Such a file still has to satisfy the application's schema and size checks. Quit the GUI before manually replacing a persistent configuration, since the running app holds committed data in memory. No application-specific decryptor or private-key export UI is required.
|
||||
|
||||
## 7. Format Limitations
|
||||
## Reads, writes and recovery
|
||||
|
||||
- The header, file size, and file system timestamps remain visible.
|
||||
- Authentication detects tampering, but this format has no independent rollback protection state.
|
||||
- After authorized access, the current application process retains the master key and decrypted data until exit.
|
||||
- This is not a password-encrypted backup format that works independently of the local keychain.
|
||||
Reads limit encoded file size before decryption, accounting for age chunk tags, header allowance and armor overhead; plaintext is checked against its original limit after decryption. Invalid age data, missing identities, authentication failures and invalid JSON fail loading. There is no plaintext fallback or automatic replacement with defaults.
|
||||
|
||||
## 8. Source Entry Points
|
||||
Writes encode and validate the entire value, encrypt in memory, then atomically replace the destination with a ciphertext-only temporary file in the same directory. Directories use `0700`; temporary and destination files use `0600`. The current writer does not explicitly `fsync`, so atomic replacement does not promise power-loss durability. Application state is published only after successful persistence.
|
||||
|
||||
- [ServerLibraryStorage.swift](../ShadowsocksX-NG2/Domain/Catalog/ServerLibraryStorage.swift): header, encryption, decryption, payload size limits, and historical-file handling.
|
||||
- [CatalogFileStore.swift](../ShadowsocksX-NG2/Domain/Catalog/CatalogFileStore.swift): direct catalog JSON encoding, schema v7, and structure validation.
|
||||
- [MasterKeyStore.swift](../ShadowsocksX-NG2/Domain/Credentials/MasterKeyStore.swift): master key attributes and keychain access.
|
||||
- [CatalogModels.swift](../ShadowsocksX-NG2/Domain/Catalog/CatalogModels.swift) and [SubscriptionRecord.swift](../ShadowsocksX-NG2/Domain/Subscription/SubscriptionRecord.swift): Codable models for catalog records and inline secrets.
|
||||
- [AtomicFileWriter.swift](../ShadowsocksX-NG2/Domain/Runtime/AtomicFileWriter.swift): temporary files and permission baseline.
|
||||
The `.age` file takes precedence when present. If absent, an existing corresponding `.enc` or legacy `.json` file causes an unsupported-format error, not fresh initialization. NG2 historical formats are not migrated, read, deleted or used as fallback; old AES and per-item Keychain records are not accessed or cleaned up. A confirmed reset creates the new `.age` file and leaves historical files untouched.
|
||||
|
||||
The server library retains retry/unlock and confirmed empty-library creation. Listening configuration retains its startup gate and confirmed reset to defaults with LAN listening disabled. Loading failure or failed reset preserves existing files and running proxy/system-proxy state. The user-initiated legacy ShadowsocksX-NG import remains available.
|
||||
|
||||
## Verification and limitations
|
||||
|
||||
`AgeConfigurationStorageTests` exercises standard age CLI decryption and encryption in binary and armor for both stores, historical-file rejection, candidate identity selection, failed reset commits, schema/size checks and an isolated real Keychain. The test requires `age` on PATH or in a Homebrew bin directory and an accessible login Keychain.
|
||||
|
||||
age protects stored content; file size and timestamps remain visible. It does not provide rollback protection, safe memory erasure, cross-machine identity recovery or an independent password-encrypted backup. The application retains decrypted values and the matching identity until exit.
|
||||
|
||||
Source entry points: [EncryptedFileStorage](../ShadowsocksX-NG2/Domain/Credentials/EncryptedFileStorage.swift), [MasterKeyStore](../ShadowsocksX-NG2/Domain/Credentials/MasterKeyStore.swift), [CatalogFileStore](../ShadowsocksX-NG2/Domain/Catalog/CatalogFileStore.swift), [ProxyListeningFileStore](../ShadowsocksX-NG2/Domain/Settings/ProxyListeningFileStore.swift), [AtomicFileWriter](../ShadowsocksX-NG2/Domain/Runtime/AtomicFileWriter.swift).
|
||||
|
||||
Reference in New Issue
Block a user