-
Notifications
You must be signed in to change notification settings - Fork 62
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Passing encryption key via a callback #1636
base: main
Are you sure you want to change the base?
Changes from 8 commits
1adb381
c52776e
44549fe
d69884c
cc38c24
2946b8d
3accfe9
59aac57
5e61217
4ca311a
09209b7
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -17,6 +17,7 @@ | |
package io.realm.kotlin | ||
|
||
import io.realm.kotlin.Configuration.SharedBuilder | ||
import io.realm.kotlin.annotations.ExperimentalEncryptionCallbackApi | ||
import io.realm.kotlin.internal.MISSING_PLUGIN_MESSAGE | ||
import io.realm.kotlin.internal.REALM_FILE_EXTENSION | ||
import io.realm.kotlin.internal.platform.PATH_SEPARATOR | ||
|
@@ -106,6 +107,24 @@ public data class InitialRealmFileConfiguration( | |
val checksum: String? | ||
) | ||
|
||
@ExperimentalEncryptionCallbackApi | ||
public interface EncryptionKeyCallback { | ||
/** | ||
* Provides the native memory address of the 64 byte array containing the key used to encrypt and decrypt the Realm file. | ||
* This can be called multiple times internally, so the key needs to be the same for between calls. | ||
nhachicha marked this conversation as resolved.
Show resolved
Hide resolved
|
||
* | ||
* Note: The Realm SDK is not responsible of checking that the pointer is a valid 64 byte array, providing an invalid address will probably | ||
* causes a segmentation fault and will crash the app. | ||
*/ | ||
public fun keyPointer(): Long | ||
|
||
/** | ||
* This callback will be invoked by Realm after it's open. This hint to the user that the key provided in [keyPointer] can now be released. | ||
* This will be called once the Realm is open and it's safe to dispose of the encryption key. | ||
*/ | ||
public fun releaseKey() | ||
} | ||
|
||
/** | ||
* Base configuration options shared between all realm configuration types. | ||
*/ | ||
|
@@ -153,6 +172,14 @@ public interface Configuration { | |
*/ | ||
public val encryptionKey: ByteArray? | ||
|
||
/** | ||
* Native memory address of the 64 byte array containing the key used to encrypt and decrypt the Realm file. | ||
* | ||
* @return null on unencrypted Realms. | ||
*/ | ||
@OptIn(ExperimentalEncryptionCallbackApi::class) | ||
public val encryptionKeyAsCallback: EncryptionKeyCallback? | ||
|
||
/** | ||
* Callback that determines if the realm file should be compacted as part of opening it. | ||
* | ||
|
@@ -234,6 +261,8 @@ public interface Configuration { | |
protected var writeDispatcher: CoroutineDispatcher? = null | ||
protected var schemaVersion: Long = 0 | ||
protected var encryptionKey: ByteArray? = null | ||
@OptIn(ExperimentalEncryptionCallbackApi::class) | ||
protected var encryptionKeyAsCallback: EncryptionKeyCallback? = null | ||
protected var compactOnLaunchCallback: CompactOnLaunchCallback? = null | ||
protected var initialDataCallback: InitialDataCallback? = null | ||
protected var inMemory: Boolean = false | ||
|
@@ -354,6 +383,51 @@ public interface Configuration { | |
public fun encryptionKey(encryptionKey: ByteArray): S = | ||
apply { this.encryptionKey = validateEncryptionKey(encryptionKey) } as S | ||
|
||
/** | ||
* Similar to [encryptionKey] but instead this will read the encryption key from native memory. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Great explanation 💯 |
||
* This can enhance the security of the app, since it reduces the window where the key is available in clear | ||
* in memory (avoid memory dump attack). Once the Realm is open, one can zero-out the memory region holding the key | ||
* as it will be already passed to the C++ storage engine. | ||
* | ||
* There's also extra protection for JVM Windows target, where the underlying storage engine uses the Windows Kernel | ||
* to encrypt/decrypt the Realm's encryption key before each usage. | ||
* | ||
* Note: The RealmConfiguration doesn't take ownership of this native memory, the caller is responsible of disposing it | ||
* appropriately after the Realm is open using the [EncryptionKeyCallback.releaseKey]. | ||
* | ||
* @param encryptionKeyAsCallback Callback providing address/pointer to a 64-byte array containing the AES encryption key. | ||
* This array should be in native memory to avoid copying the key into garbage collected heap memory (for JVM targets). | ||
* | ||
* One way to create such an array in JVM is to use JNI or use `sun.misc.Unsafe` as follow: | ||
* | ||
*``` | ||
* import sun.misc.Unsafe | ||
* | ||
* val field = Unsafe::class.java.getDeclaredField("theUnsafe") | ||
* field.isAccessible = true | ||
* val unsafe: Unsafe = field.get(null) as Unsafe | ||
* | ||
* val key = Random.nextBytes(64) // Replace with your actual AES key | ||
* val keyPointer: Long = unsafe.allocateMemory(key.size.toLong()) | ||
* for (i in key.indices) { // Write the key bytes to native memory | ||
* unsafe.putByte(keyPointer + i, key[i]) | ||
* } | ||
* | ||
* val encryptedConf = RealmConfiguration | ||
* .Builder(schema = setOf(Sample::class)) | ||
* .encryptionKey(object : EncryptionKeyCallback { | ||
* override fun keyPointer() = keyPointer | ||
* override fun releaseKey() = unsafe.freeMemory(keyPointer) | ||
* }) | ||
* .build() | ||
* | ||
* val realm = Realm.open(encryptedConf) | ||
*``` | ||
*/ | ||
@OptIn(ExperimentalEncryptionCallbackApi::class) | ||
public fun encryptionKey(encryptionKeyAsCallback: EncryptionKeyCallback): S = | ||
apply { this.encryptionKeyAsCallback = encryptionKeyAsCallback } as S | ||
|
||
/** | ||
* Sets a callback for controlling whether the realm should be compacted when opened. | ||
* | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
/* | ||
* Copyright 2023 Realm Inc. | ||
* 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 io.realm.kotlin.annotations | ||
|
||
/** | ||
* This annotation mark Realm API for encryption callback **experimental**, i.e. | ||
* there are no guarantees given that this API cannot change without warning between minor and | ||
* major versions. They will not change between patch versions. | ||
* | ||
* For all other purposes these APIs are considered stable, i.e. they undergo the same testing | ||
* as other parts of the API and should behave as documented with no bugs. It is primarily | ||
* marked as experimental because we are unsure if this API provide value and solve the use | ||
* cases that people have. If not, they will be changed or removed altogether. | ||
*/ | ||
@MustBeDocumented | ||
@Target( | ||
AnnotationTarget.CLASS, | ||
AnnotationTarget.PROPERTY, | ||
AnnotationTarget.FUNCTION, | ||
AnnotationTarget.TYPEALIAS | ||
) | ||
@RequiresOptIn(level = RequiresOptIn.Level.ERROR) | ||
public annotation class ExperimentalEncryptionCallbackApi |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -19,6 +19,7 @@ package io.realm.kotlin.internal | |
import io.realm.kotlin.Configuration | ||
import io.realm.kotlin.MutableRealm | ||
import io.realm.kotlin.Realm | ||
import io.realm.kotlin.annotations.ExperimentalEncryptionCallbackApi | ||
import io.realm.kotlin.dynamic.DynamicRealm | ||
import io.realm.kotlin.internal.dynamic.DynamicRealmImpl | ||
import io.realm.kotlin.internal.interop.ClassKey | ||
|
@@ -42,11 +43,12 @@ import kotlinx.atomicfu.AtomicRef | |
import kotlinx.atomicfu.atomic | ||
import kotlinx.coroutines.CoroutineScope | ||
import kotlinx.coroutines.SupervisorJob | ||
import kotlinx.coroutines.async | ||
import kotlinx.coroutines.awaitAll | ||
import kotlinx.coroutines.cancel | ||
import kotlinx.coroutines.channels.BufferOverflow | ||
import kotlinx.coroutines.flow.Flow | ||
import kotlinx.coroutines.flow.MutableSharedFlow | ||
import kotlinx.coroutines.flow.collect | ||
import kotlinx.coroutines.flow.map | ||
import kotlinx.coroutines.flow.withIndex | ||
import kotlinx.coroutines.launch | ||
|
@@ -138,6 +140,24 @@ public class RealmImpl private constructor( | |
} | ||
|
||
realmScope.launch { | ||
@OptIn(ExperimentalEncryptionCallbackApi::class) | ||
configuration.encryptionKeyAsCallback?.let { | ||
// if we're using an encryption key as a callback, we preemptively open the notifier and writer Realm | ||
// with the given configuration because the key might be deleted from memory after the Realm is open. | ||
|
||
// These touches the notifier and writer lazy initialised Realms to open them with the provided configuration. | ||
awaitAll( | ||
async(notificationScheduler.dispatcher) { | ||
notifier.realm.version().version | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Nitpick, would it make sense to have a helper method like There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'll add a TODO. There might be other feedbacks we can incorporate after the POC |
||
}, | ||
async(writeScheduler.dispatcher) { | ||
writer.realm.version().version | ||
} | ||
) | ||
|
||
it.releaseKey() | ||
} | ||
|
||
notifier.realmChanged().collect { | ||
removeInitialRealmReference() | ||
// Closing this reference might be done by the GC: | ||
|
@@ -270,7 +290,6 @@ public class RealmImpl private constructor( | |
current = initialRealmReference.value?.uncheckedVersion(), | ||
active = versionTracker.versions() | ||
) | ||
|
||
return VersionInfo( | ||
main = mainVersions, | ||
notifier = notifier.versions(), | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
add_library(android_jni_test_helper SHARED android_jni_helper.cpp) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I would also document that this can be called multiple times and that release is only called once, so they do not accidentially create a new Pointer for every call to this, but only release it once.
This was also why I thought it might make a better API if this was an symmetric API, i.e. called 3 times, and released 3 times, but I do agree that the current behavior is easier to implement for the sake of an POC.