Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions pir/pir-impl/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,11 @@ dependencies {
implementation AndroidX.work.runtimeKtx
implementation "androidx.work:work-multiprocess:_"

// Encryption
implementation "net.zetetic:sqlcipher-android:_"
implementation project(':library-loader-api')
implementation AndroidX.security.crypto

testImplementation Testing.junit4
testImplementation "org.mockito.kotlin:mockito-kotlin:_"
testImplementation project(path: ':common-test')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@

package com.duckduckgo.pir.impl.di

import android.content.Context
import androidx.room.Room
import com.duckduckgo.app.di.AppCoroutineScope
import com.duckduckgo.common.utils.CurrentTimeProvider
import com.duckduckgo.common.utils.DispatcherProvider
Expand Down Expand Up @@ -63,6 +61,7 @@ import com.duckduckgo.pir.impl.store.db.OptOutResultsDao
import com.duckduckgo.pir.impl.store.db.ScanLogDao
import com.duckduckgo.pir.impl.store.db.ScanResultsDao
import com.duckduckgo.pir.impl.store.db.UserProfileDao
import com.duckduckgo.pir.impl.store.secure.PirSecureStorageDatabaseFactory
import com.squareup.anvil.annotations.ContributesTo
import com.squareup.moshi.Moshi
import com.squareup.moshi.adapters.PolymorphicJsonAdapterFactory
Expand All @@ -71,6 +70,7 @@ import dagger.Module
import dagger.Provides
import dagger.SingleInstanceIn
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.runBlocking
import javax.inject.Named

@Module
Expand All @@ -79,11 +79,12 @@ class PirModule {

@SingleInstanceIn(AppScope::class)
@Provides
fun bindPirDatabase(context: Context): PirDatabase {
return Room.databaseBuilder(context, PirDatabase::class.java, "pir.db")
.enableMultiInstanceInvalidation()
.fallbackToDestructiveMigration()
.build()
fun bindPirDatabase(
databaseFactory: PirSecureStorageDatabaseFactory,
): PirDatabase {
return runBlocking {
databaseFactory.getDatabase()
} ?: throw IllegalStateException("Failed to create PIR encrypted database")
}

@SingleInstanceIn(AppScope::class)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
/*
* Copyright (c) 2025 DuckDuckGo
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.duckduckgo.pir.impl.store.secure

import android.content.Context
import androidx.room.Room
import com.duckduckgo.di.scopes.AppScope
import com.duckduckgo.library.loader.LibraryLoader
import com.duckduckgo.pir.impl.store.PirDatabase
import com.squareup.anvil.annotations.ContributesBinding
import dagger.SingleInstanceIn
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import logcat.LogPriority.ERROR
import logcat.asLog
import logcat.logcat
import net.zetetic.database.sqlcipher.SupportOpenHelperFactory
import javax.inject.Inject

interface PirSecureStorageDatabaseFactory {
suspend fun getDatabase(): PirDatabase?
}

@SingleInstanceIn(AppScope::class)
@ContributesBinding(
scope = AppScope::class,
boundType = PirSecureStorageDatabaseFactory::class,
)
class RealPirSecureStorageDatabaseFactory @Inject constructor(
private val context: Context,
private val keyProvider: PirSecureStorageKeyProvider,
) : PirSecureStorageDatabaseFactory {
private var _database: PirDatabase? = null

private val mutex = Mutex()

init {
logcat { "PIR-DB: Loading the sqlcipher native library" }
try {
LibraryLoader.loadLibrary(context, "sqlcipher")
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If this method is called more than once with the same library name, the second and subsequent calls are ignored. (source)

It should be fine for both Autofill and PIR to call this multiple times

logcat { "PIR-DB: sqlcipher native library loaded ok" }
} catch (t: Throwable) {
// error loading the library
logcat(ERROR) { "PIR-DB: Error loading sqlcipher library: ${t.asLog()}" }
}
}

override suspend fun getDatabase(): PirDatabase? {
_database?.let { return it }
return mutex.withLock {
getInnerDatabase()
}
}

@OptIn(ExperimentalStdlibApi::class)
private suspend fun getInnerDatabase(): PirDatabase? {
// If we have already the DB instance then let's use it
if (_database != null) {
return _database
}

// If we can't access the keystore, it means that L1Key will be null. We don't want to encrypt the db with a null key.
return if (keyProvider.canAccessKeyStore()) {
// At this point, we are guaranteed that if L1key is null, it's because it hasn't been generated yet. Else, we always use the one stored.
_database = Room.databaseBuilder(
context,
PirDatabase::class.java,
"pir_encrypted.db",
)
.openHelperFactory(
SupportOpenHelperFactory(
keyProvider.getl1Key(),
),
)
.enableMultiInstanceInvalidation()
.fallbackToDestructiveMigration()
.build()
_database
} else {
logcat(ERROR) { "PIR-DB: Cannot access key store!" }
null
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/*
* Copyright (c) 2025 DuckDuckGo
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.duckduckgo.pir.impl.store.secure

import com.duckduckgo.di.scopes.AppScope
import com.squareup.anvil.annotations.ContributesBinding
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import javax.inject.Inject

/**
* This class provides the usable decrypted keys to be used for encryption
*/
interface PirSecureStorageKeyProvider {
suspend fun canAccessKeyStore(): Boolean

/**
* Ready to use key for L1 encryption
*/
suspend fun getl1Key(): ByteArray
}

@ContributesBinding(AppScope::class)
class RealPirSecureStorageKeyProvider @Inject constructor(
private val randomBytesGenerator: PirRandomBytesGenerator,
private val secureStorageKeyRepository: PirSecureStorageKeyRepository,
) : PirSecureStorageKeyProvider {

override suspend fun canAccessKeyStore(): Boolean =
secureStorageKeyRepository.canUseEncryption()

private val l1KeyMutex = Mutex()

override suspend fun getl1Key(): ByteArray {
l1KeyMutex.withLock {
return innerGetL1Key()
}
}

private suspend fun innerGetL1Key(): ByteArray {
// If no key exists in the keystore, we generate a new one and store it
return if (secureStorageKeyRepository.getL1Key() == null) {
randomBytesGenerator.generateBytes(L1_PASSPHRASE_SIZE).also {
secureStorageKeyRepository.setL1Key(it)
}
} else {
secureStorageKeyRepository.getL1Key()!!
}
}

companion object {
private const val L1_PASSPHRASE_SIZE = 32
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/*
* Copyright (c) 2025 DuckDuckGo
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.duckduckgo.pir.impl.store.secure

import com.duckduckgo.di.scopes.AppScope
import com.squareup.anvil.annotations.ContributesBinding
import dagger.SingleInstanceIn
import javax.inject.Inject

interface PirSecureStorageKeyRepository {
/**
* Key used for L1 encryption
*/
suspend fun getL1Key(): ByteArray?
suspend fun setL1Key(value: ByteArray?)

/**
* This method can be checked if the keystore has support for encryption
*
* @return `true` if keystore encryption is supported and `false` otherwise
*/
suspend fun canUseEncryption(): Boolean
}

@SingleInstanceIn(AppScope::class)
@ContributesBinding(
scope = AppScope::class,
boundType = PirSecureStorageKeyRepository::class,
)
class RealPirSecureStorageKeyRepository @Inject constructor(
private val keyStore: PirSecureStorageKeyStore,
) : PirSecureStorageKeyRepository {
override suspend fun getL1Key(): ByteArray? = keyStore.getKey(KEY_L1KEY)
override suspend fun setL1Key(value: ByteArray?) {
keyStore.updateKey(KEY_L1KEY, value)
}

override suspend fun canUseEncryption(): Boolean = keyStore.canUseEncryption()

companion object {
private const val KEY_L1KEY = "KEY_L1KEY"
}
}
Loading
Loading