diff --git a/README.md b/README.md index f51ad0747..fb2aa4561 100644 --- a/README.md +++ b/README.md @@ -7340,8 +7340,7 @@ pod 'SQLCipher', '~> 3.4' - [Creating or Opening an Encrypted Database](#creating-or-opening-an-encrypted-database) - [Changing the Passphrase of an Encrypted Database](#changing-the-passphrase-of-an-encrypted-database) -- [Encrypting a Clear-Text Database](#encrypting-a-clear-text-database) -- [Attempting Several Passphrases](#attempting-several-passphrases) +- [Exporting a Database to an Encrypted Database](#exporting-a-database-to-an-encrypted-database) - [Security Considerations](#security-considerations) @@ -7350,35 +7349,35 @@ pod 'SQLCipher', '~> 3.4' **You create and open an encrypted database** by providing a passphrase to your [database connection](#database-connections): ```swift -var configuration = Configuration() -configuration.prepareDatabase = { db in +var config = Configuration() +config.prepareDatabase = { db in try db.usePassphrase("secret") } -let dbQueue = try DatabaseQueue(path: "...", configuration: configuration) +let dbQueue = try DatabaseQueue(path: dbPath, configuration: config) ``` -After you have set the passphrase, you can perform other [SQLCipher configuration steps](https://www.zetetic.net/sqlcipher/sqlcipher-api/) that must happen very early in the database lifetime. For example: +It is also in the database preparation function that you perform other [SQLCipher configuration steps](https://www.zetetic.net/sqlcipher/sqlcipher-api/) that must happen early in the lifetime of a SQLCipher connection. For example: ```swift -var configuration = Configuration() -configuration.prepareDatabase = { db in +var config = Configuration() +config.prepareDatabase = { db in try db.usePassphrase("secret") try db.execute(sql: "PRAGMA cipher_page_size = ...") try db.execute(sql: "PRAGMA kdf_iter = ...") } -let dbQueue = try DatabaseQueue(path: "...", configuration: configuration) +let dbQueue = try DatabaseQueue(path: dbPath, configuration: config) ``` When you want to open an existing SQLCipher 3 database with SQLCipher 4, you may want to run the `cipher_compatibility` pragma: ```swift // Open an SQLCipher 3 database with SQLCipher 4 -var configuration = Configuration() -configuration.prepareDatabase = { db in +var config = Configuration() +config.prepareDatabase = { db in try db.usePassphrase("secret") try db.execute(sql: "PRAGMA cipher_compatibility = 3") } -let dbQueue = try DatabaseQueue(path: dbPath, configuration: configuration) +let dbQueue = try DatabaseQueue(path: dbPath, configuration: config) ``` See [SQLCipher 4.0.0 Release](https://www.zetetic.net/blog/2018/11/30/sqlcipher-400-release/) and [Upgrading to SQLCipher 4](https://discuss.zetetic.net/t/upgrading-to-sqlcipher-4/3283) for more information. @@ -7388,105 +7387,128 @@ See [SQLCipher 4.0.0 Release](https://www.zetetic.net/blog/2018/11/30/sqlcipher- **You can change the passphrase** of an already encrypted database. -The technique to do so is not the same, depending on whether you are using a [database queue](#database-queues) or a [database pool](#database-pools). - -For database queues, first open the database with the old passphrase, and then apply the new passphrase: +When you use a [database queue](#database-queues), open the database with the old passphrase, and then apply the new passphrase: ```swift -// 1. Open the database queue -var configuration = Configuration() -configuration.prepareDatabase = { db in - try db.usePassphrase("oldSecret") -} -let dbQueue = try DatabaseQueue(path: "...", configuration: configuration) - -// 2. Later on, change the passphrase try dbQueue.write { db in try db.changePassphrase("newSecret") } - -// 3. Keep using the database queue with the new passphrase -try dbQueue.write { ... } -try dbQueue.read { ... } ``` -For database pools, it is a little bit more complicated. This is because pools create SQLite connections on demand. Your application must provide a storage for the passphrase, ready to be queried whenever a new SQLite connection should be created. This "storage" can be, for example, the system keychain. - -In the sample code below, we assume the presence of two functions provided by the application: `loadPassphrase()` and `savePassphrase(_:)`. The first loads the passphrase, and the second stores a new passphrase and makes it available to future calls to `loadPassphrase()`: +When you use a [database pool](#database-pools), make sure that no concurrent read can happen during the passphrase change with the `barrierWriteWithoutTransaction` method, and that all future reads open a new database connection with the `invalidateReadOnlyConnections` method: ```swift -// 1. Open the database pool -var config = Configuration() -config.prepareDatabase = { db in - let passphrase = loadPassphrase() - try db.usePassphrase(passphrase) -} -let dbPool = try DatabasePool(path: ..., configuration: config) - -// 2. Later on, change the passphrase try dbPool.barrierWriteWithoutTransaction { db in - let newPassphrase = "newSecret" - try db.changePassphrase(newPassphrase) - savePassphrase(newPassphrase) + try db.changePassphrase("newSecret") dbPool.invalidateReadOnlyConnections() } - -// 3. Keep using the database pool with the new passphrase -try dbPool.write { ... } -try dbPool.read { ... } ``` -TODO: Explain that database snapshots are not managed and shold be invalidated. - -TODO: Explain that if the `loadPassphrase` function throws an error, it is rethrown. - -TODO: Explain that if the `savePassphrase` function may throw an error, then you have to take in account the risk of passphrase desynchronization. You may have to attempt *several* passphrases (see below). +> :point_up: **Note**: When an application wants to keep on using a database queue or pool after the passphrase has changed, it is responsible for providing the correct passphrase to the `usePassphrase` method called in the database preparation function. +> +> :point_up: **Note**: The `DatabasePool.barrierWriteWithoutTransaction` method does not prevent [database snapshots](#database-snapshots) from accessing the database during the passphrase change, or after the new passphrase has been applied to the database. Those database accesses may throw errors. Applications should provide their own mechanism for invalidating open snapshots before the passphrase is changed. +> +> :point_up: **Note**: Instead of changing the passphrase "in place" as described here, you can also export the database in a new encrypted database that uses the new passphrase. See [Exporting a Database to an Encrypted Database](#exporting-a-database-to-an-encrypted-database). -### Encrypting a Clear-Text Database +### Exporting a Database to an Encrypted Database Providing a passphrase won't encrypt a clear-text database that already exists, though. SQLCipher can't do that, and you will get an error instead: `SQLite error 26: file is encrypted or is not a database`. -**To encrypt an existing clear-text database**, create a new and empty encrypted database, and copy the content of the clear-text database in it. The technique to do that is [documented](https://discuss.zetetic.net/t/how-to-encrypt-a-plaintext-sqlite-database-to-use-sqlcipher-and-avoid-file-is-encrypted-or-is-not-a-database-errors/868/1) by SQLCipher. With GRDB, it gives: +Instead, create a new encrypted database, at a distinct location, and export the content of the existing database. This can both encrypt a clear-text database, or change the passphrase of an encrypted databaase. + +The technique to do that is [documented](https://discuss.zetetic.net/t/how-to-encrypt-a-plaintext-sqlite-database-to-use-sqlcipher-and-avoid-file-is-encrypted-or-is-not-a-database-errors/868/1) by SQLCipher. + +With GRDB, it gives: ```swift -// The clear-text database -let clearDBQueue = try DatabaseQueue(path: "/path/to/clear.db") +// The existing database +let existingDBQueue = try DatabaseQueue(path: "/path/to/existing.db") -// The encrypted database, at some distinct location: -var configuration = Configuration() -configuration.passphrase = "secret" -let encryptedDBQueue = try DatabaseQueue(path: "/path/to/encrypted.db", configuration: config) - -try clearDBQueue.inDatabase { db in - try db.execute(sql: "ATTACH DATABASE ? AS encrypted KEY ?", arguments: [encryptedDBQueue.path, "secret"]) - try db.execute(sql: "SELECT sqlcipher_export('encrypted')") - try db.execute(sql: "DETACH DATABASE encrypted") -} - -// Now the copy is done, and the clear-text database can be deleted. -``` - -### Attempting Several Passphrases - -TODO. Context: synchronizing the passphrase in the keychain, and the passphrase used by the database is tricky: one saving operation may succeed, and the other fail. It is possible that one has to try *two* passphrases: - -```swift +// The new encrypted database, at some distinct location: var config = Configuration() config.prepareDatabase = { db in - do { - try db.usePassphrase(passphrase1) - } catch let error as DatabaseError where error.resultCode == .SQLITE_NOTADB { - try db.usePassphrase(passphrase2) - } + try db.usePassphrase("secret") } +let newDBQueue = try DatabaseQueue(path: "/path/to/new.db", configuration: config) + +try existingDBQueue.inDatabase { db in + try db.execute( + sql: """ + ATTACH DATABASE ? AS encrypted KEY ?; + SELECT sqlcipher_export('encrypted'); + DETACH DATABASE encrypted; + """, + arguments: [newDBQueue.path, "secret"]) +} + +// Now the export is completed, and the existing database can be deleted. ``` ### Security Considerations -- TODO: Connections can be used after passphrase has turned unavailable -- TODO: Advanced passphrase protection (use cases for the raw C SQLCioher functions) +#### Managing the lifetime of passphrase bytes + +GRDB offers convenience methods for providing the database passphrases as Swift strings: `usePassphrase(_:)` and `changePassphrase(_:)`. Those methods don't keep the passphrase String in memory longer than necessary. But they are as secure as the standard String type: the lifetime of actual passphrase bytes in memory is not under control. + +When you want to precisely manage the passphrase bytes, talk directly to SQLCipher, using its raw C functions. + +For example: + +```swift +import GRDB +import SQLCipher + +var config = Configuration() +config.prepareDatabase = { db in + ... // Carefully load passphrase bytes + let code = sqlite3_key(db.sqliteConnection, /* passphrase bytes */) + ... // Carefully dispose passphrase bytes + guard code == SQLITE_OK else { + throw DatabaseError(resultCode: code, message: db.lastErrorMessage) + } +} +let dbQueue = try DatabaseQueue(path: dbPath, configuration: config) +``` + +#### Passphrase availability vs. Database availability + +When the passphrase is securely stored in the system keychain, your application can protect is using the [`kSecAttrAccessible`](https://developer.apple.com/documentation/security/ksecattraccessible) attribute. + +```swift +var config = Configuration() +config.prepareDatabase = { db in + let passphrase = try loadPassphraseFromSystemKeychain() + try db.usePassphrase(passphrase) +} +``` + +Such protection prevents GRDB from creating SQLite connections when the passphrase is not available: + +```swift +// Success if and only if the passphrase is available +let dbQueue = try DatabaseQueue(path: dbPath, configuration: config) +``` + +For the same reason, [database pools](#database-pools), which open SQLite connections on demand, may fail at any time as soon as the passphrase becomes unavailable: + +```swift +// Success if and only if the passphrase is available +let dbPool = try DatabasePool(path: dbPath, configuration: config) + +// May fail if passphrase has turned unavailable +try dbPool.read { ... } + +// May trigger value observation failure if passphrase has turned unavailable +try dbPool.write { ... } +``` + +Those eventual database pool failures are not predictable, because pools maintain a pool of long-lived SQLite connection(s). Some database accesses will use those existing connections, and succeed. Some other database accesses will fail, as soon as the pool wants to open a new connection. + +For the same reason, a database queue, which also maintains a long-lived SQLite connection, will remain available even after the passphrase has turned unavailable. + +Application that want to prevent any database access when the passphrase is unavailable are responsible for destroying their instances of database queue or pool when the passphrase becomes unavailable. ## Backup @@ -8782,10 +8804,10 @@ let dbQueue = try DatabaseQueue(path: databaseURL.path) If your application does not need to modify the database, open a read-only [connection](#database-connections) to your resource: ```swift -var configuration = Configuration() -configuration.readonly = true +var config = Configuration() +config.readonly = true let dbPath = Bundle.main.path(forResource: "db", ofType: "sqlite")! -let dbQueue = try DatabaseQueue(path: dbPath, configuration: configuration) +let dbQueue = try DatabaseQueue(path: dbPath, configuration: config) ``` If the application should modify the database, you need to copy it to a place where it can be modified. For example, in the [Application Support directory](https://developer.apple.com/library/content/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/FileSystemOverview/FileSystemOverview.html). Only then, open a [connection](#database-connections):