Sqlcipher backend
- Although this extention’s code is short, it has not been properly peer-reviewed yet and may have introduced vulnerabilities.
Also note that this code relies on pysqlcipher and sqlcipher, and the code there might have vulnerabilities as well, but since these are widely used crypto modules, we can expect “short zero days” there.
sqlcipher_ext API notes
class SqlCipherDatabase
(database, passphrase, \*kwargs*)
Subclass of SqliteDatabase
that stores the database encrypted. Instead of the standard sqlite3
backend, it uses pysqlcipher: a python wrapper for sqlcipher, which – in turn – is an encrypted wrapper around sqlite3
, so the API is identical to SqliteDatabase
’s, except for object construction parameters:
Parameters: |
|
---|
- If the
database
file doesn’t exist, it will be created with encryption by a key derived frompasshprase
. When trying to open an existing database,
passhprase
should be identical to the ones used when it was created. If the passphrase is incorrect, an error will be raised when first attempting to access the database.rekey
(passphrase)Parameters: passphrase (str) – New passphrase for database. Change the passphrase for database.
Note
SQLCipher can be configured using a number of extension PRAGMAs. The list of PRAGMAs and their descriptions can be found in the SQLCipher documentation.
For example to specify the number of PBKDF2 iterations for the key derivation (64K in SQLCipher 3.x, 256K in SQLCipher 4.x by default):
# Use 1,000,000 iterations.
db = SqlCipherDatabase('my_app.db', pragmas={'kdf_iter': 1000000})
To use a cipher page-size of 16KB and a cache-size of 10,000 pages:
db = SqlCipherDatabase('my_app.db', passphrase='secret!!!', pragmas={
'cipher_page_size': 1024 * 16,
'cache_size': 10000}) # 10,000 16KB pages, or 160MB.
Example of prompting the user for a passphrase:
db = SqlCipherDatabase(None)
class BaseModel(Model):
"""Parent for all app's models"""
class Meta:
# We won't have a valid db until user enters passhrase.
database = db
# Derive our model subclasses
class Person(BaseModel):
name = TextField(primary_key=True)
right_passphrase = False
while not right_passphrase:
db.init(
'testsqlcipher.db',
passphrase=get_passphrase_from_user())
try: # Actually execute a query against the db to test passphrase.
db.get_tables()
except DatabaseError as exc:
# This error indicates the password was wrong.
if exc.args[0] == 'file is encrypted or is not a database':
tell_user_the_passphrase_was_wrong()
db.init(None) # Reset the db.
else:
raise exc
else:
# The password was correct.
right_passphrase = True
See also: a slightly more elaborate example.