diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index 18934e3ff..e67e7b924 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -82,21 +82,10 @@ public struct Configuration { /// Default: nil public var passphrase: String? - /// The cipher_page_size setting for the encrypted database. - /// - /// See https://www.zetetic.net/sqlcipher/sqlcipher-api/#cipher_page_size - /// - /// Default: 1024 - this corresponds to the default used by SQLCipher 3 - public var cipherPageSize: Int = 1024 - - /// The kdf_iter setting for the encrypted database. - /// - /// See https://www.zetetic.net/sqlcipher/sqlcipher-api/#kdf_iter - /// - /// Default: 64000 - this corresponds to the default used by SQLCipher 3 - public var kdfIterations: Int = 64000 #endif - + + // TODO DOC + public var prepareDatabase: ((Database) throws -> Void)? // MARK: - Transactions diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index cee17ca88..7362b0d3b 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -166,28 +166,10 @@ public final class Database { // MARK: - Initializer init(path: String, configuration: Configuration, schemaCache: DatabaseSchemaCache) throws { - let sqliteConnection = try Database.openConnection(path: path, flags: configuration.SQLiteOpenFlags) - do { - try Database.activateExtendedCodes(sqliteConnection) - #if SQLITE_HAS_CODEC - try Database.validateSQLCipher(sqliteConnection) - if let passphrase = configuration.passphrase { - try Database.set(passphrase: passphrase, forConnection: sqliteConnection) - try Database.set(cipherPageSize: configuration.cipherPageSize, forConnection: sqliteConnection) - try Database.set(kdfIterations: configuration.kdfIterations, forConnection: sqliteConnection) - } - #endif - try Database.validateDatabaseFormat(sqliteConnection) - } catch { - Database.closeConnection(sqliteConnection) - throw error - } - - self.sqliteConnection = sqliteConnection + + self.sqliteConnection = try Database.openConnection(path: path, flags: configuration.SQLiteOpenFlags) self.configuration = configuration self.schemaCache = schemaCache - - configuration.SQLiteConnectionDidOpen?() } deinit { @@ -269,36 +251,6 @@ extension Database { throw DatabaseError(resultCode: code, message: String(cString: sqlite3_errmsg(sqliteConnection))) } } - - private static func set(cipherPageSize: Int, forConnection sqliteConnection: SQLiteConnection) throws { - var sqliteStatement: SQLiteStatement? = nil - var code = sqlite3_prepare_v2(sqliteConnection, "PRAGMA cipher_page_size = \(cipherPageSize)", -1, &sqliteStatement, nil) - guard code == SQLITE_OK else { - throw DatabaseError(resultCode: code, message: String(cString: sqlite3_errmsg(sqliteConnection))) - } - defer { - sqlite3_finalize(sqliteStatement) - } - code = sqlite3_step(sqliteStatement) - if code != SQLITE_DONE { - throw DatabaseError(resultCode: code, message: String(cString: sqlite3_errmsg(sqliteConnection))) - } - } - - private static func set(kdfIterations: Int, forConnection sqliteConnection: SQLiteConnection) throws { - var sqliteStatement: SQLiteStatement? = nil - var code = sqlite3_prepare_v2(sqliteConnection, "PRAGMA kdf_iter = \(kdfIterations)", -1, &sqliteStatement, nil) - guard code == SQLITE_OK else { - throw DatabaseError(resultCode: code, message: String(cString: sqlite3_errmsg(sqliteConnection))) - } - defer { - sqlite3_finalize(sqliteStatement) - } - code = sqlite3_step(sqliteStatement) - if code != SQLITE_DONE { - throw DatabaseError(resultCode: code, message: String(cString: sqlite3_errmsg(sqliteConnection))) - } - } #endif private static func validateDatabaseFormat(_ sqliteConnection: SQLiteConnection) throws { @@ -317,11 +269,30 @@ extension Database { extension Database { // MARK: - Database Setup - + func setupConnection() throws { + do { + try Database.activateExtendedCodes(sqliteConnection) + #if SQLITE_HAS_CODEC + try Database.validateSQLCipher(sqliteConnection) + #endif + if let passphrase = configuration.passphrase { + try Database.set(passphrase: passphrase, forConnection: sqliteConnection) + } + try configuration.prepareDatabase?(self) + + try Database.validateDatabaseFormat(sqliteConnection) + } catch { + throw error + } + configuration.SQLiteConnectionDidOpen?() + } + /// This method must be called after database initialization func setup() throws { // Setup trace first, so that setup queries are traced. setupTrace() + + try setupConnection() try setupForeignKeys() setupBusyMode() setupDefaultFunctions() diff --git a/GRDB/Core/SerializedDatabase.swift b/GRDB/Core/SerializedDatabase.swift index 5417d7844..7fabe2ee2 100644 --- a/GRDB/Core/SerializedDatabase.swift +++ b/GRDB/Core/SerializedDatabase.swift @@ -42,7 +42,12 @@ final class SerializedDatabase { self.queue = configuration.makeDispatchQueue(defaultLabel: defaultLabel, purpose: purpose) SchedulingWatchdog.allowDatabase(db, onQueue: queue) try queue.sync { - try db.setup() + do { + try db.setup() + } catch { + db.close() + throw error + } } } diff --git a/Tests/GRDBTests/EncryptionTests.swift b/Tests/GRDBTests/EncryptionTests.swift index d96d4b16f..163e5df33 100644 --- a/Tests/GRDBTests/EncryptionTests.swift +++ b/Tests/GRDBTests/EncryptionTests.swift @@ -343,7 +343,9 @@ class EncryptionTests: GRDBTestCase { func testCipherPageSize() throws { do { dbConfiguration.passphrase = "secret" - dbConfiguration.cipherPageSize = 8192 + dbConfiguration.prepareDatabase = { db in + try db.execute(sql: "PRAGMA cipher_page_size = 8192") + } let dbQueue = try makeDatabaseQueue(filename: "test.sqlite") try dbQueue.inDatabase({ db in @@ -352,7 +354,10 @@ class EncryptionTests: GRDBTestCase { } do { - dbConfiguration.cipherPageSize = 4096 + dbConfiguration.passphrase = "secret" + dbConfiguration.prepareDatabase = { db in + try db.execute(sql: "PRAGMA cipher_page_size = 4096") + } let dbPool = try makeDatabasePool(filename: "testpool.sqlite") try dbPool.write({ db in @@ -371,7 +376,9 @@ class EncryptionTests: GRDBTestCase { func testCipherKDFIterations() throws { do { dbConfiguration.passphrase = "secret" - dbConfiguration.kdfIterations = 128000 + dbConfiguration.prepareDatabase = { db in + try db.execute(sql: "PRAGMA kdf_iter = 128000") + } let dbQueue = try makeDatabaseQueue(filename: "test.sqlite") try dbQueue.inDatabase { db in @@ -380,8 +387,11 @@ class EncryptionTests: GRDBTestCase { } do { - dbConfiguration.kdfIterations = 128000 - + dbConfiguration.passphrase = "secret" + dbConfiguration.prepareDatabase = { db in + try db.execute(sql: "PRAGMA kdf_iter = 128000") + } + let dbPool = try makeDatabasePool(filename: "testpool.sqlite") try dbPool.write { db in XCTAssertEqual(try Int.fetchOne(db, sql: "PRAGMA kdf_iter"), 128000) @@ -395,6 +405,49 @@ class EncryptionTests: GRDBTestCase { } } } + + func testCipherWithMismatchedKDFIterations() throws { + do { + dbConfiguration.passphrase = "secret" + dbConfiguration.prepareDatabase = { db in + try db.execute(sql: "PRAGMA kdf_iter = 128000") + } + + let dbPool = try makeDatabasePool(filename: "testpool.sqlite") + try dbPool.write { db in + XCTAssertEqual(try Int.fetchOne(db, sql: "PRAGMA kdf_iter"), 128000) + try db.execute(sql: "CREATE TABLE data(value INTEGER)") + try db.execute(sql: "INSERT INTO data(value) VALUES(1)") + } + + try dbPool.read { db in + XCTAssertEqual(try Int.fetchOne(db, sql: "PRAGMA kdf_iter"), 128000) + XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT value FROM data"), 1) + } + } + + do { + dbConfiguration.passphrase = "secret" + dbConfiguration.prepareDatabase = { db in + try db.execute(sql: "PRAGMA kdf_iter = 64000") + } + + do { + let dbPool = try makeDatabasePool(filename: "testpool.sqlite") + + try dbPool.read { db in + XCTAssertEqual(try Int.fetchOne(db, sql: "PRAGMA kdf_iter"), 64000) + XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT value FROM data"), 1) + } + XCTFail("Expected error") + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_NOTADB) + XCTAssertEqual(error.message!, "file is not a database") + XCTAssertTrue(error.sql == nil) + XCTAssertEqual(error.description, "SQLite error 26: file is not a database") + } + } + } func testExportPlainTextDatabaseToEncryptedDatabase() throws { // See 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?source_topic_id=939