Archived
X25519 in DER form, because Android is not the JVM
Running the app on a phone threw "No AlgorithmParameterSpec classes are supported" the first time anyone tapped Create account. Android's provider is Conscrypt, not the JDK's, and its XDH key-pair generator rejects every parameter spec while its key factory does not speak the XEC* specs at all — none of which the JVM suite could see, because it passes there. X25519 now goes through PKCS#8 and X.509 encodings, which both providers already speak. That also removes the RFC 7748 little-endian BigInteger conversion entirely, and with it a class of byte-order bug that produces plausible keys agreeing with nothing. An instrumented suite runs the published vectors on a device, so the next provider difference fails in CI rather than in someone's hands. Three consequences worth stating plainly: minSdk is 33, not 26. Android exposes XDH from API 33; below that a provider has to be registered at startup and nothing here does that, so claiming 26 was claiming something untrue. Cleartext is refused with a reason rather than failing as an unexplained connection error. Bearer tokens ride every request, so a plain-http server would put an account on a café network. material-icons-extended is gone. It generates a class per icon and added 44 MB of dex for the five glyphs this app uses; three hand-written vector paths replace it.
This commit is contained in:
@@ -10,7 +10,7 @@ client](https://gitlab.com/paulhitt/flamenet-files).
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| `engine/` | The cryptography, in plain Kotlin over JCA. Implements [docs/SPEC.md](https://gitlab.com/paulhitt/flamenet-files/-/blob/main/docs/SPEC.md) — the lattice, key derivation, the key hierarchy, recovery codes, filename digests, chunked content, share links. |
|
||||
| `engine/` | The cryptography, in plain Kotlin over JCA. **Requires API 33+** — that is where Android exposes X25519. Implements [docs/SPEC.md](https://gitlab.com/paulhitt/flamenet-files/-/blob/main/docs/SPEC.md) — the lattice, key derivation, the key hierarchy, recovery codes, filename digests, chunked content, share links. |
|
||||
| `client/` | The wire layer: server discovery, the account service, the file API, a session that ties them together, and `filesctl`, a command-line client. |
|
||||
|
||||
Both are plain JVM libraries, not Android modules, so `gradle test` runs them
|
||||
@@ -97,3 +97,20 @@ export JAVA_HOME=$(brew --prefix openjdk@21)/libexec/openjdk.jdk/Contents/Home
|
||||
|
||||
The APK lands in `app/build/outputs/apk/debug/`. `local.properties` points at
|
||||
the SDK and is not committed.
|
||||
|
||||
A debug APK is around 54 MB and a minified release one is 2.5 MB — R8 is doing
|
||||
almost all of that, so do not read the debug figure as the size of the app.
|
||||
|
||||
### On-device tests
|
||||
|
||||
```bash
|
||||
./gradlew :app:connectedDebugAndroidTest
|
||||
```
|
||||
|
||||
⚠️ **These are not redundant with `:engine:test`.** Android's security provider
|
||||
is Conscrypt, not the JDK's, and the two disagree: the obvious X25519
|
||||
implementation using `NamedParameterSpec` and `XECPublicKeySpec` passes every
|
||||
JVM test and then throws `No AlgorithmParameterSpec classes are supported` the
|
||||
first time somebody taps *Create account* on a phone. That happened. The
|
||||
engine now speaks DER to both providers, and the published vectors run on a
|
||||
device as well as on the JVM so the next such difference fails in CI.
|
||||
|
||||
+21
-2
@@ -13,10 +13,23 @@ android {
|
||||
|
||||
defaultConfig {
|
||||
applicationId = "io.flamenet.files"
|
||||
minSdk = 26 // X25519 through JCA needs API 26.
|
||||
// Android exposes the XDH algorithm from API 33. Below that a provider
|
||||
// such as BouncyCastle has to be registered at startup; the engine is
|
||||
// provider-agnostic, but nothing here does that registration yet, so
|
||||
// claiming a lower floor would be claiming something untrue.
|
||||
minSdk = 33
|
||||
targetSdk = 35
|
||||
versionCode = 1
|
||||
versionName = "0.1"
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
}
|
||||
|
||||
sourceSets {
|
||||
getByName("androidTest") {
|
||||
java.srcDir("src/androidTest/kotlin")
|
||||
assets.srcDir("src/androidTest/assets")
|
||||
}
|
||||
getByName("main") { java.srcDir("src/main/kotlin") }
|
||||
}
|
||||
|
||||
buildFeatures { compose = true }
|
||||
@@ -41,9 +54,15 @@ dependencies {
|
||||
implementation(platform("androidx.compose:compose-bom:2024.12.01"))
|
||||
implementation("androidx.compose.material3:material3")
|
||||
implementation("androidx.compose.ui:ui")
|
||||
implementation("androidx.compose.material:material-icons-extended")
|
||||
implementation("androidx.activity:activity-compose:1.9.3")
|
||||
implementation("androidx.core:core-ktx:1.15.0")
|
||||
implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.8.7")
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.9.0")
|
||||
|
||||
// On-device tests. The engine's JVM suite cannot see a provider difference,
|
||||
// and a provider difference is what broke X25519 the first time this ran on
|
||||
// a phone.
|
||||
androidTestImplementation("androidx.test.ext:junit:1.2.1")
|
||||
androidTestImplementation("androidx.test:runner:1.6.2")
|
||||
androidTestImplementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.7.3")
|
||||
}
|
||||
|
||||
Vendored
@@ -0,0 +1,136 @@
|
||||
{
|
||||
"version": 1,
|
||||
"note": "Decrypt these. See docs/SPEC.md.",
|
||||
"cases": {
|
||||
"labelBytes": [
|
||||
{
|
||||
"classification": 3,
|
||||
"compartments": [
|
||||
0
|
||||
],
|
||||
"expected": "AAMAAAAAAAAAAQ=="
|
||||
},
|
||||
{
|
||||
"classification": 1,
|
||||
"compartments": [],
|
||||
"expected": "AAEAAAAAAAAAAA=="
|
||||
},
|
||||
{
|
||||
"classification": 0,
|
||||
"compartments": [
|
||||
63
|
||||
],
|
||||
"expected": "AACAAAAAAAAAAA=="
|
||||
},
|
||||
{
|
||||
"classification": 2,
|
||||
"compartments": [
|
||||
0,
|
||||
1,
|
||||
63
|
||||
],
|
||||
"expected": "AAKAAAAAAAAAAw=="
|
||||
}
|
||||
],
|
||||
"kdf": {
|
||||
"passphrase": "correct horse battery staple",
|
||||
"salt": "BwcHBwcHBwcHBwcHBwcHBw==",
|
||||
"iterations": 1000,
|
||||
"contexts": {
|
||||
"filesIdentity": "flamenet/files/identity/v1",
|
||||
"filesAuth": "flamenet/files/auth/v1",
|
||||
"messengerIdentity": "flamenet/messenger/identity/v1"
|
||||
},
|
||||
"authSecret": "67XBl7YK3eWLxlwCsQfvGZKiokbcY8mEqCw1E8QDxaE="
|
||||
},
|
||||
"hierarchy": {
|
||||
"label": {
|
||||
"classification": 3,
|
||||
"compartments": [
|
||||
0,
|
||||
1
|
||||
]
|
||||
},
|
||||
"identityPublicKey": "rx6FBwu0ekejPG/KuVDGUjDGgpk1KeuneLAjxSQ4Ul0=",
|
||||
"identityRecord": {
|
||||
"v": 1,
|
||||
"kdf": 1,
|
||||
"iterations": 1000,
|
||||
"context": "flamenet/files/identity/v1",
|
||||
"salt": "3nW9N41kTjy+XV4MTrZpBw==",
|
||||
"nonce": "/RfcIYNdqzoJjFJ0",
|
||||
"privateKey": "Cq0gk03SqDC0QrYMdhyz/KwdwRxAaG95Cow0sE2+nilEjAnbgeDZPDSkKoZKSVla5Jv2Tf0AsDwYmGS01EWVGQ=="
|
||||
},
|
||||
"labelKey": "mdghL5vAIw5DeSsY9/BwRARhADaDBQnCxZDqeRHxl20=",
|
||||
"nodeKey": "Xlb5FpmFRr06pADUaHGW9+uXIqtbhcnEVy2Ht8om3lM=",
|
||||
"contentKey": "WP2IXXEHgqN9B4LosOtkeQgbfNgaqmLPSm9t02XQkc0=",
|
||||
"labelKeyGrant": "Acacc9qfWCLxyXcc6rRTEyUDJxwdc0wxqy4UW8NSHwlhv/rvokK6kYMRfcTyUfXoE8H68Sk6nvIuC3sBAYMIcGkX/El9tUms+c90ffr+EbRZqyR16dREwtPowST+",
|
||||
"wrappedNodeKey": "EUITJmLQVJgoL8z+lcfoKXIxHsGDWGVXDsxqdQnoPghuMvbD3eyhCCVT3lkDOQJ2sOKrfm8aAgEpzUSGMw==",
|
||||
"wrappedContentKey": "EUQ1b+IbuxUblsm1gKGp1GWk8Tw3IsNNCGvTVwfQBA8OHLWmiHgpDburxl3GweXMzo9rFbhPazZkYKBsmw==",
|
||||
"nameDigest": "zEu1hnRTyD+91Vke88XDSSVa/jfVERPIbMLB2kul4hY=",
|
||||
"nameCiphertext": "AZlKWc9giJcswo4Fva4Ez7BhdljC5MfIsUpeSYz4LxwlAl9bobFz6Te/jCQ=",
|
||||
"expectedName": "Q3 Forecast.txt",
|
||||
"content": "RU5DTAEAAAAQfPLZFLMzaHtthhTgPXIbF6Q5iDW4RM+x97t9Ggd4lEJ3V1xMmyKvg8ISLjEUixPNrNGpzhx58+qfkj0pXqqzZijC",
|
||||
"expectedContent": "cmV2ZW51ZTogNDEKaGVhZGNvdW50OiAxMgo=",
|
||||
"contentChunkSize": 16
|
||||
},
|
||||
"nameDigest": [
|
||||
{
|
||||
"folderKey": "Xlb5FpmFRr06pADUaHGW9+uXIqtbhcnEVy2Ht8om3lM=",
|
||||
"name": "Q3 Forecast.txt",
|
||||
"expected": "zEu1hnRTyD+91Vke88XDSSVa/jfVERPIbMLB2kul4hY="
|
||||
},
|
||||
{
|
||||
"folderKey": "Xlb5FpmFRr06pADUaHGW9+uXIqtbhcnEVy2Ht8om3lM=",
|
||||
"name": "café",
|
||||
"expected": "yiuuJ6pdJeJX7gQ3YJFGWbtu10Qz4VvUwE2cdWhMLB4="
|
||||
},
|
||||
{
|
||||
"folderKey": "Xlb5FpmFRr06pADUaHGW9+uXIqtbhcnEVy2Ht8om3lM=",
|
||||
"name": "Payroll",
|
||||
"expected": "NN1zYjaALbTzp1MAf8dUNbfd/DVQVQ8jN3cN0DiEZt8="
|
||||
}
|
||||
],
|
||||
"recovery": {
|
||||
"code": "BKKR-SJXB-E8M8-1A6B-CN47-WNM7-6RQN",
|
||||
"entropy": "XOeMy6tyKICoy2VIflaHNg=="
|
||||
}
|
||||
},
|
||||
"recovery": [
|
||||
{
|
||||
"entropy": "AEeO1RxjqvE4f8YNVJviKQ==",
|
||||
"code": "013R-XN8W-CENF-2E3Z-RR6N-96Z2-57K9",
|
||||
"kdfSecret": "00478ed51c63aaf1387fc60d549be229"
|
||||
},
|
||||
{
|
||||
"entropy": "JWyz+kGIzxZdpOsyecAHTg==",
|
||||
"code": "4NPB-7YJ1-H37H-CQD4-XCS7-KG07-9RBA",
|
||||
"kdfSecret": "256cb3fa4188cf165da4eb3279c0074e"
|
||||
},
|
||||
{
|
||||
"entropy": "SpHYH2at9DuCyRBXnuUscw==",
|
||||
"code": "9A8X-G7V6-NQT3-Q0P9-21BS-XS9C-EE7C",
|
||||
"kdfSecret": "4a91d81f66adf43b82c910579ee52c73"
|
||||
},
|
||||
{
|
||||
"entropy": "b7b9RIvSGWCn7jV8wwpRmA==",
|
||||
"code": "DYVF-TH4B-T8CP-19ZE-6NYC-62JH-K3JD",
|
||||
"kdfSecret": "6fb6fd448bd21960a7ee357cc30a5198"
|
||||
},
|
||||
{
|
||||
"entropy": "lNsiabD3PoXME1qh6C92vQ==",
|
||||
"code": "JKDJ-4TDG-YWZ8-BK0K-BAGY-GBVP-QN2Y",
|
||||
"kdfSecret": "94db2269b0f73e85cc135aa1e82f76bd"
|
||||
},
|
||||
{
|
||||
"entropy": "uQBHjtUcY6rxOH/GDVSb4g==",
|
||||
"code": "Q404-F3PN-3HHT-NW9R-FZ30-TN4V-W87R",
|
||||
"kdfSecret": "b900478ed51c63aaf1387fc60d549be2"
|
||||
}
|
||||
],
|
||||
"recoveryWithQ": {
|
||||
"entropy": "AB06V3SRrsvoBSI/XHmWsw==",
|
||||
"code": "00EK-MNVM-J6QC-QT05-48ZN-RYCP-PDSA",
|
||||
"kdfSecret": "001d3a577491aecbe805223f5c7996b3"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
package io.flamenet.files.app
|
||||
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import io.flamenet.files.engine.Content
|
||||
import io.flamenet.files.engine.Identity
|
||||
import io.flamenet.files.engine.Kdf
|
||||
import io.flamenet.files.engine.Keys
|
||||
import io.flamenet.files.engine.Label
|
||||
import io.flamenet.files.engine.Names
|
||||
import io.flamenet.files.engine.Recovery
|
||||
import io.flamenet.files.engine.Shares
|
||||
import io.flamenet.files.engine.X25519
|
||||
import kotlinx.serialization.json.*
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import java.util.Base64
|
||||
|
||||
/**
|
||||
* The engine, on a real Android runtime.
|
||||
*
|
||||
* ⚠️ **This exists because the JVM suite cannot see the bug that matters.**
|
||||
* Android's security provider is Conscrypt, not the JDK's, and the two disagree
|
||||
* about X25519: the obvious `NamedParameterSpec`/`XECPublicKeySpec` implementation
|
||||
* passes every JVM test and then throws "No AlgorithmParameterSpec classes are
|
||||
* supported" the first time somebody taps Create account on a phone. That is
|
||||
* exactly what happened, and it was found by running the app rather than by any
|
||||
* test.
|
||||
*
|
||||
* So the same published vectors run here too. A provider difference now fails in
|
||||
* CI instead of in a user's hands.
|
||||
*/
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class EngineOnDeviceTest {
|
||||
private val vectors: JsonObject by lazy {
|
||||
val bytes = InstrumentationRegistry.getInstrumentation().context.assets
|
||||
.open("v1.json").use { it.readBytes() }
|
||||
Json.parseToJsonElement(String(bytes, Charsets.UTF_8)).jsonObject
|
||||
}
|
||||
|
||||
private fun b64(text: String): ByteArray = Base64.getDecoder().decode(text)
|
||||
private val cases get() = vectors["cases"]!!.jsonObject
|
||||
|
||||
/** The one that broke. Generation, both raw conversions, and agreement. */
|
||||
@Test
|
||||
fun x25519WorksOnThisProvider() {
|
||||
val pair = X25519.generate()
|
||||
val rawPublic = X25519.rawFromPublic(pair.public)
|
||||
val rawPrivate = X25519.rawFromPrivate(pair.private)
|
||||
assertEquals(32, rawPublic.size)
|
||||
assertEquals(32, rawPrivate.size)
|
||||
|
||||
// Round-trip through the raw form, then agree both ways.
|
||||
val reimportedPrivate = X25519.privateFromRaw(rawPrivate)
|
||||
val reimportedPublic = X25519.publicFromRaw(rawPublic)
|
||||
val other = X25519.generate()
|
||||
assertArrayEquals(
|
||||
X25519.agree(reimportedPrivate, other.public),
|
||||
X25519.agree(other.private, reimportedPublic),
|
||||
)
|
||||
|
||||
// And the derivation a session depends on after unlocking a record.
|
||||
assertArrayEquals(
|
||||
rawPublic,
|
||||
X25519.rawFromPublic(X25519.publicFromPrivate(reimportedPrivate)),
|
||||
)
|
||||
}
|
||||
|
||||
/** An identity record written by the browser must open on a phone. */
|
||||
@Test
|
||||
fun unlocksTheBrowsersIdentityRecord() {
|
||||
val hierarchy = cases["hierarchy"]!!.jsonObject
|
||||
val record = hierarchy["identityRecord"]!!.jsonObject
|
||||
val opened = Identity.unlock(
|
||||
Identity.Record(
|
||||
v = record["v"]!!.jsonPrimitive.int,
|
||||
kdf = record["kdf"]!!.jsonPrimitive.int,
|
||||
iterations = record["iterations"]!!.jsonPrimitive.int,
|
||||
context = record["context"]!!.jsonPrimitive.content,
|
||||
salt = record["salt"]!!.jsonPrimitive.content,
|
||||
nonce = record["nonce"]!!.jsonPrimitive.content,
|
||||
privateKey = record["privateKey"]!!.jsonPrimitive.content,
|
||||
),
|
||||
cases["kdf"]!!.jsonObject["passphrase"]!!.jsonPrimitive.content,
|
||||
)
|
||||
assertEquals(32, X25519.rawFromPrivate(opened).size)
|
||||
}
|
||||
|
||||
/** Recovery codes must be identical across every client, character for
|
||||
* character — a code printed on one device is typed into another. */
|
||||
@Test
|
||||
fun recoveryCodesAgreeWithTheBrowser() {
|
||||
val all = vectors["recovery"]!!.jsonArray.map { it.jsonObject } +
|
||||
listOf(vectors["recoveryWithQ"]!!.jsonObject)
|
||||
for (expected in all) {
|
||||
val entropy = b64(expected["entropy"]!!.jsonPrimitive.content)
|
||||
assertEquals(expected["code"]!!.jsonPrimitive.content, Recovery.encode(entropy))
|
||||
assertArrayEquals(entropy, Recovery.decode(expected["code"]!!.jsonPrimitive.content))
|
||||
}
|
||||
}
|
||||
|
||||
/** PBKDF2 and HKDF come from the platform too, and the platform differs. */
|
||||
@Test
|
||||
fun keyDerivationAgreesWithTheBrowser() {
|
||||
val kdf = cases["kdf"]!!.jsonObject
|
||||
assertArrayEquals(
|
||||
b64(kdf["authSecret"]!!.jsonPrimitive.content),
|
||||
Kdf.authSecret(
|
||||
kdf["passphrase"]!!.jsonPrimitive.content,
|
||||
b64(kdf["salt"]!!.jsonPrimitive.content),
|
||||
Kdf.Parameters(1, kdf["iterations"]!!.jsonPrimitive.int),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
/** The whole hierarchy, on device: label key to node key to content key,
|
||||
* plus the chunked content format and a share link. */
|
||||
@Test
|
||||
fun theKeyHierarchyRoundTripsOnDevice() {
|
||||
val label = Label(2, setOf(0, 1))
|
||||
val pair = X25519.generate()
|
||||
val labelKey = ByteArray(32) { it.toByte() }
|
||||
|
||||
val granted = Keys.grantLabelKey(labelKey, label, pair.public)
|
||||
assertArrayEquals(labelKey, Keys.acceptLabelKey(granted, label, pair.private, pair.public))
|
||||
|
||||
val nodeKey = ByteArray(32) { (it * 7).toByte() }
|
||||
val contentKey = ByteArray(32) { (it * 13).toByte() }
|
||||
assertArrayEquals(
|
||||
nodeKey,
|
||||
Keys.unwrapNodeKey(Keys.wrapNodeKey(nodeKey, labelKey, label), labelKey, label),
|
||||
)
|
||||
assertArrayEquals(
|
||||
contentKey,
|
||||
Keys.unwrapContentKey(
|
||||
Keys.wrapContentKey(contentKey, nodeKey, label), nodeKey, label,
|
||||
),
|
||||
)
|
||||
|
||||
// Larger than one chunk, so framing and the last-chunk flag are covered.
|
||||
val plaintext = ByteArray(200_000) { (it % 251).toByte() }
|
||||
assertArrayEquals(
|
||||
plaintext,
|
||||
Content.decrypt(Content.encrypt(plaintext, contentKey, label), contentKey, label),
|
||||
)
|
||||
|
||||
val named = Names.encrypt(labelKey, "quarterly report.pdf", label)
|
||||
assertEquals(
|
||||
"quarterly report.pdf",
|
||||
Names.decrypt(labelKey, named.second, named.first, label),
|
||||
)
|
||||
|
||||
val secret = Shares.createSecret()
|
||||
val sealed = Shares.seal(labelKey, label, secret, contentKey, "report.pdf", "hunter2")
|
||||
val opened = Shares.open(
|
||||
labelKey, label, secret, sealed.wrappedContentKey, sealed.wrappedName,
|
||||
"hunter2", sealed.passwordSalt, sealed.passwordIterations!!,
|
||||
)
|
||||
assertArrayEquals(contentKey, opened.contentKey)
|
||||
assertEquals("report.pdf", opened.name)
|
||||
|
||||
// And the third factor is actually a factor.
|
||||
assertTrue(
|
||||
runCatching {
|
||||
Shares.open(
|
||||
labelKey, label, secret, sealed.wrappedContentKey, sealed.wrappedName,
|
||||
"wrong", sealed.passwordSalt, sealed.passwordIterations!!,
|
||||
)
|
||||
}.isFailure,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@
|
||||
android:allowBackup="false"
|
||||
android:label="@string/app_name"
|
||||
android:supportsRtl="true"
|
||||
android:networkSecurityConfig="@xml/network_security_config"
|
||||
android:theme="@style/Theme.FlamenetFiles">
|
||||
|
||||
<!--
|
||||
|
||||
@@ -9,10 +9,8 @@ import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material.icons.filled.Description
|
||||
import androidx.compose.material.icons.filled.Folder
|
||||
import androidx.compose.material.icons.filled.MoreVert
|
||||
import androidx.compose.material.icons.filled.Shield
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
@@ -26,6 +24,7 @@ import androidx.compose.ui.text.font.FontStyle
|
||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.content.FileProvider
|
||||
import io.flamenet.files.R
|
||||
import io.flamenet.files.client.FilesSession
|
||||
import kotlinx.coroutines.launch
|
||||
import java.io.File
|
||||
@@ -66,7 +65,7 @@ fun Browse(model: FilesViewModel, state: UiState) {
|
||||
}
|
||||
} else {
|
||||
IconButton(onClick = { showingAreas = true }) {
|
||||
Icon(Icons.Default.Shield, contentDescription = "Area")
|
||||
Icon(painterResource(R.drawable.ic_shield), contentDescription = "Area")
|
||||
}
|
||||
// Only labels the clearance permits are offered, so
|
||||
// nobody discovers the limit by being refused.
|
||||
@@ -185,7 +184,7 @@ private fun Row(entry: FilesSession.Entry, model: FilesViewModel, onShare: () ->
|
||||
ListItem(
|
||||
leadingContent = {
|
||||
Icon(
|
||||
if (entry.isFolder) Icons.Default.Folder else Icons.Default.Description,
|
||||
painterResource(if (entry.isFolder) R.drawable.ic_folder else R.drawable.ic_file),
|
||||
contentDescription = null,
|
||||
)
|
||||
},
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="24dp" android:height="24dp"
|
||||
android:viewportWidth="24" android:viewportHeight="24">
|
||||
<path android:fillColor="@android:color/white"
|
||||
android:pathData="M14,2H6c-1.1,0 -1.99,0.9 -1.99,2L4,20c0,1.1 0.89,2 1.99,2H18c1.1,0 2,-0.9 2,-2V8l-6,-6zM16,18H8v-2h8v2zM16,14H8v-2h8v2zM13,9V3.5L18.5,9H13z"/>
|
||||
</vector>
|
||||
@@ -0,0 +1,11 @@
|
||||
<!--
|
||||
Three drawables instead of material-icons-extended.
|
||||
That library generates a class per icon and added 44 MB of dex to a debug
|
||||
build for the five glyphs this app uses. Five paths cost nothing.
|
||||
-->
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="24dp" android:height="24dp"
|
||||
android:viewportWidth="24" android:viewportHeight="24">
|
||||
<path android:fillColor="@android:color/white"
|
||||
android:pathData="M10,4H4c-1.1,0 -1.99,0.9 -1.99,2L2,18c0,1.1 0.9,2 2,2h16c1.1,0 2,-0.9 2,-2L22,8c0,-1.1 -0.9,-2 -2,-2h-8l-2,-2z"/>
|
||||
</vector>
|
||||
@@ -0,0 +1,6 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="24dp" android:height="24dp"
|
||||
android:viewportWidth="24" android:viewportHeight="24">
|
||||
<path android:fillColor="@android:color/white"
|
||||
android:pathData="M12,1L3,5v6c0,5.55 3.84,10.74 9,12 5.16,-1.26 9,-6.45 9,-12L21,5l-9,-4z"/>
|
||||
</vector>
|
||||
@@ -0,0 +1,18 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
Cleartext is off everywhere except loopback and the emulator's host alias.
|
||||
Bearer tokens travel on every request, so a plain-http server would put an
|
||||
account on the wire — the client refuses those with a reason before it gets
|
||||
this far, and this is the belt to that braces.
|
||||
|
||||
A self-hoster therefore needs TLS. That is the correct requirement for this
|
||||
app and it is not an oversight.
|
||||
-->
|
||||
<network-security-config>
|
||||
<base-config cleartextTrafficPermitted="false" />
|
||||
<domain-config cleartextTrafficPermitted="true">
|
||||
<domain includeSubdomains="false">localhost</domain>
|
||||
<domain includeSubdomains="false">127.0.0.1</domain>
|
||||
<domain includeSubdomains="false">10.0.2.2</domain>
|
||||
</domain-config>
|
||||
</network-security-config>
|
||||
@@ -39,9 +39,21 @@ internal class Http {
|
||||
} catch (error: Exception) {
|
||||
throw ClientException.BadServer("That doesn't look like a server address.")
|
||||
}
|
||||
if (uri.scheme?.lowercase() !in setOf("http", "https")) {
|
||||
val scheme = uri.scheme?.lowercase()
|
||||
if (scheme !in setOf("http", "https")) {
|
||||
throw ClientException.BadServer("That doesn't look like a server address.")
|
||||
}
|
||||
// Android blocks cleartext by default and this app does not turn
|
||||
// that off. Bearer tokens travel on every request, and a token in
|
||||
// clear on a café network is an account, so a plain-http server is
|
||||
// refused here with a reason rather than failing later as an
|
||||
// unexplained connection error.
|
||||
if (scheme == "http" && uri.host !in setOf("localhost", "127.0.0.1", "10.0.2.2")) {
|
||||
throw ClientException.BadServer(
|
||||
"This app needs https. Your server is reachable over plain http, " +
|
||||
"which would put your sign-in token on the wire in clear.",
|
||||
)
|
||||
}
|
||||
return uri.toURL()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,69 +1,89 @@
|
||||
package io.flamenet.files.engine
|
||||
|
||||
import java.math.BigInteger
|
||||
import java.security.KeyFactory
|
||||
import java.security.KeyPairGenerator
|
||||
import java.security.PrivateKey
|
||||
import java.security.PublicKey
|
||||
import java.security.spec.NamedParameterSpec
|
||||
import java.security.spec.XECPrivateKeySpec
|
||||
import java.security.spec.XECPublicKeySpec
|
||||
import java.security.interfaces.XECPrivateKey
|
||||
import java.security.interfaces.XECPublicKey
|
||||
import java.security.spec.PKCS8EncodedKeySpec
|
||||
import java.security.spec.X509EncodedKeySpec
|
||||
import javax.crypto.KeyAgreement
|
||||
|
||||
/**
|
||||
* X25519 through JCA, with the raw-format conversions spelled out.
|
||||
* X25519 through JCA, in encoded form throughout.
|
||||
*
|
||||
* The wire format is the RFC 7748 32-byte **little-endian** u-coordinate, while
|
||||
* Java models a public key as a BigInteger. Getting the byte order or the
|
||||
* high-bit mask wrong produces keys that look plausible and agree with nothing,
|
||||
* so both directions are covered by the interop vectors.
|
||||
* ⚠️ **Written this way because of Android.** The obvious implementation uses
|
||||
* `NamedParameterSpec`, `XECPublicKeySpec` and the `XECPublicKey` interface —
|
||||
* and that works perfectly on the JVM and fails on a phone. Android's provider
|
||||
* is Conscrypt, whose XDH key-pair generator rejects every `AlgorithmParameterSpec`
|
||||
* outright ("No AlgorithmParameterSpec classes are supported") and whose key
|
||||
* factory does not speak the `XEC*` specs at all.
|
||||
*
|
||||
* ⚠️ Android exposes the "XDH" algorithm from API 33. Below that, register a
|
||||
* provider such as BouncyCastle at startup — the code here is provider-agnostic
|
||||
* and needs no change for it.
|
||||
* DER is the common language both providers already speak. For X25519 the
|
||||
* wrappers are fixed-length prefixes around the raw key, so the conversions are
|
||||
* exact, and this drops the RFC 7748 little-endian/BigInteger dance entirely —
|
||||
* a byte-order bug that produced plausible keys agreeing with nothing.
|
||||
*
|
||||
* The JVM interop vectors still cover it, and an instrumented test runs the same
|
||||
* vectors on a device, because this is precisely the difference a JVM-only suite
|
||||
* cannot see.
|
||||
*/
|
||||
object X25519 {
|
||||
private val spec = NamedParameterSpec.X25519
|
||||
/** RFC 8410 PrivateKeyInfo: version, algorithm id, OCTET STRING wrapper. */
|
||||
private val PKCS8_PREFIX = byteArrayOf(
|
||||
0x30, 0x2E, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06,
|
||||
0x03, 0x2B, 0x65, 0x6E, 0x04, 0x22, 0x04, 0x20,
|
||||
)
|
||||
|
||||
fun generate() = KeyPairGenerator.getInstance("XDH").apply { initialize(spec) }.generateKeyPair()
|
||||
/** RFC 8410 SubjectPublicKeyInfo: algorithm id, then a BIT STRING of 32 bytes. */
|
||||
private val X509_PREFIX = byteArrayOf(
|
||||
0x30, 0x2A, 0x30, 0x05, 0x06, 0x03, 0x2B, 0x65,
|
||||
0x6E, 0x03, 0x21, 0x00,
|
||||
)
|
||||
|
||||
private fun factory() = KeyFactory.getInstance("XDH")
|
||||
|
||||
/**
|
||||
* No `initialize` call. XDH defaults to X25519 on the JVM, and on Android
|
||||
* passing a parameter spec is not merely unnecessary but refused.
|
||||
*/
|
||||
fun generate() = KeyPairGenerator.getInstance("XDH").generateKeyPair()
|
||||
|
||||
fun publicFromRaw(raw: ByteArray): PublicKey {
|
||||
require(raw.size == 32) { "X25519 public key must be 32 bytes" }
|
||||
val littleEndian = raw.copyOf()
|
||||
// RFC 7748: the most significant bit of the final byte is ignored.
|
||||
littleEndian[31] = (littleEndian[31].toInt() and 0x7F).toByte()
|
||||
val u = BigInteger(1, littleEndian.reversedArray())
|
||||
return KeyFactory.getInstance("XDH").generatePublic(XECPublicKeySpec(spec, u))
|
||||
return factory().generatePublic(X509EncodedKeySpec(X509_PREFIX + raw))
|
||||
}
|
||||
|
||||
fun rawFromPublic(key: PublicKey): ByteArray {
|
||||
val u = (key as XECPublicKey).u
|
||||
val bigEndian = u.toByteArray()
|
||||
// BigInteger may prepend a zero sign byte, or omit leading zeroes.
|
||||
val trimmed = bigEndian.dropWhile { it == 0.toByte() }.toByteArray()
|
||||
val padded = ByteArray(32)
|
||||
trimmed.copyInto(padded, 32 - trimmed.size)
|
||||
return padded.reversedArray()
|
||||
val encoded = key.encoded
|
||||
?: throw EngineException("public key is not extractable")
|
||||
if (encoded.size != X509_PREFIX.size + 32) {
|
||||
throw EngineException("unexpected X25519 public key encoding")
|
||||
}
|
||||
return encoded.copyOfRange(encoded.size - 32, encoded.size)
|
||||
}
|
||||
|
||||
fun privateFromRaw(scalar: ByteArray): PrivateKey {
|
||||
require(scalar.size == 32) { "X25519 private key must be 32 bytes" }
|
||||
return KeyFactory.getInstance("XDH").generatePrivate(XECPrivateKeySpec(spec, scalar))
|
||||
return factory().generatePrivate(PKCS8EncodedKeySpec(PKCS8_PREFIX + scalar))
|
||||
}
|
||||
|
||||
fun rawFromPrivate(key: PrivateKey): ByteArray =
|
||||
(key as XECPrivateKey).scalar.orElseThrow { EngineException("private key is not extractable") }
|
||||
fun rawFromPrivate(key: PrivateKey): ByteArray {
|
||||
val encoded = key.encoded
|
||||
?: throw EngineException("private key is not extractable")
|
||||
if (encoded.size != PKCS8_PREFIX.size + 32) {
|
||||
throw EngineException("unexpected X25519 private key encoding")
|
||||
}
|
||||
return encoded.copyOfRange(encoded.size - 32, encoded.size)
|
||||
}
|
||||
|
||||
/**
|
||||
* Derive the public half from a private key.
|
||||
*
|
||||
* JCA hands back a public key only from a freshly generated KeyPair, and a
|
||||
* JCA hands back a public key only from a freshly generated pair, and a
|
||||
* session that unlocked a stored record has just the scalar. Scalar
|
||||
* multiplication against the generator is exactly what agreement does, so
|
||||
* agreeing with the basepoint recovers it — no second stored copy, and no
|
||||
* chance of the two disagreeing.
|
||||
* agreeing with the basepoint recovers it — no second stored copy, and
|
||||
* nothing that can disagree with itself.
|
||||
*/
|
||||
fun publicFromPrivate(privateKey: PrivateKey): PublicKey {
|
||||
val basepoint = ByteArray(32).also { it[0] = 9 }
|
||||
|
||||
Reference in New Issue
Block a user