Skip to content
Open
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
4 changes: 2 additions & 2 deletions app.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,8 @@ export default ({ config }: ConfigContext) =>
"@bacons/apple-targets",
["./scripts/fdroid/configureFdroid.ts"],
[
"./scripts/detox/configureDetox.ts",
{ subdomains: "*" }, // uncomment to debug app
"./scripts/detox/configureDetox.ts",
{ subdomains: "*" }, // uncomment to debug app
],
["./scripts/trustUserCAs.ts"],
["./scripts/increaseGradleMemory.ts"],
Expand Down
133 changes: 132 additions & 1 deletion components/ServerForm.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
import React, { useRef, useState } from "react";
import { Platform } from "react-native";
import { Text, Button, Input, CheckBox } from "@ui-kitten/components";
import { cleanServerUrl, sameServer, verifyEvccServer } from "../utils/server";
import LoadingIndicator from "./animations/LoadingIndicator";
import { useTranslation } from "react-i18next";
import { BasicAuth, Server } from "types";
import { useAppContext } from "./AppContext";
import ScanQRCodeButton from "./ScanQRCodeButton";
import * as DocumentPicker from "expo-document-picker";
import * as FileSystem from "expo-file-system/legacy";
import { storeCert } from "../utils/certStorage";
import NativeClientCertModule from "../modules/client-cert/src/ClientCertModule";

interface ServerFormProps {
server: Server | undefined;
Expand Down Expand Up @@ -44,16 +49,64 @@ export default function ServerForm({
title: internalServer?.title,
url,
basicAuth: internalServer?.basicAuth || {},
clientCert: internalServer?.clientCert,
});
};
const setInternalAuth = (basicAuth: BasicAuth) => {
setInternalServer({
title: internalServer?.title,
url: internalServer?.url || "",
basicAuth,
clientCert: internalServer?.clientCert,
});
};

const [certPassword, setCertPassword] = useState("");
const [certBase64, setCertBase64] = useState<string | undefined>();
const [certLabel, setCertLabel] = useState<string | undefined>();

const toggleClientCert = (enabled: boolean) => {
if (!enabled) {
setCertBase64(undefined);
setCertPassword("");
setCertLabel(undefined);
setInternalServer({
...internalServer,
url: internalServer?.url || "",
basicAuth: internalServer?.basicAuth || {},
clientCert: undefined,
});
} else {
setInternalServer({
...internalServer,
url: internalServer?.url || "",
basicAuth: internalServer?.basicAuth || {},
clientCert: { label: "", secureStoreKey: "" },
});
}
};

const pickCertificate = async () => {
try {
const result = await DocumentPicker.getDocumentAsync({
type: ["application/x-pkcs12", "application/pkcs12", "application/octet-stream"],
copyToCacheDirectory: true,
});

if (result.canceled) return;

const file = result.assets[0];
const base64 = await FileSystem.readAsStringAsync(file.uri, {
encoding: FileSystem.EncodingType.Base64,
});

setCertBase64(base64);
setCertLabel(file.name);
} catch (e) {
console.log("Error picking certificate", e);
}
};

const validateAndSaveURL = async () => {
if (inProgress) return;
if (!internalServer?.title?.trim()) return;
Expand All @@ -68,14 +121,32 @@ export default function ServerForm({
const finalUrl = await verifyEvccServer({
url: cleanUrl,
basicAuth: internalServer?.basicAuth || {},
clientCert: internalServer?.clientCert,
});

const server = {
const server: Server = {
title: internalServer?.title,
url: finalUrl,
basicAuth: internalServer?.basicAuth || {},
};

if (internalServer?.clientCert && certBase64) {
try {
NativeClientCertModule.setCertificate(certBase64, certPassword);
} catch {
throw new Error(t("servers.manually.clientCertNote") + " (Password invalid?)");
}
const key = "cert_" + Date.now();
await storeCert(key, certBase64, certPassword);
server.clientCert = {
label: certLabel || "Certificate",
secureStoreKey: key,
};
} else if (internalServer?.clientCert?.secureStoreKey) {
// keep existing cert during update
server.clientCert = internalServer.clientCert;
}

const sameServerCount = servers.filter((s) =>
sameServer(server, s),
).length;
Expand Down Expand Up @@ -183,6 +254,66 @@ export default function ServerForm({
</>
)}

{Platform.OS === "android" && (
<>
<CheckBox
style={{ marginTop: 8, marginBottom: 16 }}
checked={!!internalServer?.clientCert}
onChange={toggleClientCert}
testID="serverFormClientCert"
>
{t("servers.manually.clientCertRequired")}
</CheckBox>

{!!internalServer?.clientCert && (
<>
<Button
style={{ marginTop: 8, marginBottom: certLabel ? 4 : 16 }}
appearance={certLabel ? "filled" : "outline"}
status={certLabel ? "success" : "basic"}
onPress={pickCertificate}
>
{certLabel
? `✓ ${certLabel}`
: internalServer?.clientCert?.label
? `✓ ${internalServer.clientCert.label}`
: t("servers.manually.clientCertSelect")}
</Button>

{certLabel && (
<Text style={{ marginBottom: 12 }} category="c1" appearance="hint">
{t("servers.manually.clientCertNote")}
</Text>
)}

{!!certBase64 && (
<Input
style={{ marginTop: 4, marginBottom: 16 }}
size="large"
status="basic"
onChangeText={setCertPassword}
value={certPassword}
inputMode="text"
keyboardType="default"
autoCapitalize="none"
returnKeyType="go"
autoCorrect={false}
placeholder={t("servers.manually.clientCertPassword")}
secureTextEntry
onSubmitEditing={validateAndSaveURL}
/>
)}

{!certLabel && !!internalServer?.clientCert && (
<Text style={{ marginTop: 4, marginBottom: 16 }} category="c1" appearance="hint">
{t("servers.manually.clientCertNote")}
</Text>
)}
</>
)}
</>
)}

<Button
style={{ marginTop: 16, marginBottom: 16 }}
appearance="filled"
Expand Down
6 changes: 5 additions & 1 deletion i18n/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,11 @@
"scanning": "erkennen..."
},
"title": "Titel",
"serverExistsAlready": "Dieser Server existiert bereits."
"serverExistsAlready": "Dieser Server existiert bereits.",
"clientCertRequired": "Client-Zertifikat verwenden",
"clientCertSelect": "Zertifikat auswählen (.p12)",
"clientCertPassword": "Zertifikat-Passwort",
"clientCertNote": "Das Zertifikat wird beim Verbindungsaufbau verwendet. Die Prüfung beim Speichern wird übersprungen."
},
"removeServer": "Server entfernen",
"search": {
Expand Down
6 changes: 5 additions & 1 deletion i18n/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,11 @@
"scanning": "detecting..."
},
"title": "Title",
"serverExistsAlready": "This server already exists."
"serverExistsAlready": "This server already exists.",
"clientCertRequired": "Use client certificate",
"clientCertSelect": "Select certificate (.p12)",
"clientCertPassword": "Certificate password",
"clientCertNote": "The certificate will be used when connecting to the server. Verification is skipped."
},
"removeServer": "Remove server",
"search": {
Expand Down
21 changes: 21 additions & 0 deletions modules/client-cert/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2015-present 650 Industries, Inc. (aka Expo)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
18 changes: 18 additions & 0 deletions modules/client-cert/android/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
plugins {
id 'com.android.library'
id 'expo-module-gradle-plugin'
}

group = 'expo.modules.clientcert'
version = '0.1.0'

android {
namespace "expo.modules.clientcert"
defaultConfig {
versionCode 1
versionName "0.1.0"
}
lintOptions {
abortOnError false
}
}
2 changes: 2 additions & 0 deletions modules/client-cert/android/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
<manifest>
</manifest>
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
package expo.modules.clientcert

import android.webkit.ClientCertRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import expo.modules.kotlin.modules.Module
import expo.modules.kotlin.modules.ModuleDefinition

class ClientCertModule : Module() {
override fun definition() = ModuleDefinition {
Name("ClientCert")

Function("setCertificate") { p12Base64: String, pass: String ->
ClientCertStore.setCert(p12Base64, pass)
installClientCertHandlerIfNeeded()
}

Function("clearCertificate") {
ClientCertStore.clear()
}
}

private fun installClientCertHandlerIfNeeded() {
val activity = appContext.currentActivity ?: return
activity.runOnUiThread {
// Walk the view hierarchy and patch every WebView we find
val rootView = activity.window.decorView
patchWebViews(rootView)
}
}

private fun patchWebViews(view: android.view.View) {
if (view is WebView) {
// Only install once – check the current client type
val existing = view.tag as? Boolean
if (existing != true) {
view.tag = true
val originalClient = view.webViewClient
view.webViewClient = object : WebViewClient() {
override fun onReceivedClientCertRequest(
view: WebView,
request: ClientCertRequest
) {
val key = ClientCertStore.getPrivateKey()
val chain = ClientCertStore.getCertificateChain()
if (key != null && chain != null) {
request.proceed(key, chain)
} else {
request.cancel()
}
}

// Forward all other methods to original client
override fun shouldOverrideUrlLoading(
view: WebView,
url: String
) = originalClient.shouldOverrideUrlLoading(view, url)

override fun onPageStarted(
view: WebView,
url: String,
favicon: android.graphics.Bitmap?
) = originalClient.onPageStarted(view, url, favicon)

override fun onPageFinished(view: WebView, url: String) =
originalClient.onPageFinished(view, url)

override fun onReceivedError(
view: WebView,
request: android.webkit.WebResourceRequest,
error: android.webkit.WebResourceError
) = originalClient.onReceivedError(view, request, error)

override fun onReceivedHttpError(
view: WebView,
request: android.webkit.WebResourceRequest,
errorResponse: android.webkit.WebResourceResponse
) = originalClient.onReceivedHttpError(view, request, errorResponse)

override fun onReceivedSslError(
view: WebView,
handler: android.webkit.SslErrorHandler,
error: android.net.http.SslError
) = originalClient.onReceivedSslError(view, handler, error)
}
}
}
if (view is android.view.ViewGroup) {
for (i in 0 until view.childCount) {
patchWebViews(view.getChildAt(i))
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package expo.modules.clientcert

import java.security.KeyStore
import java.security.PrivateKey
import java.security.cert.X509Certificate

object ClientCertStore {
private var privateKey: PrivateKey? = null
private var certificateChain: Array<X509Certificate>? = null

@JvmStatic
fun getPrivateKey(): PrivateKey? = privateKey

@JvmStatic
fun getCertificateChain(): Array<X509Certificate>? = certificateChain

fun setCert(p12Base64: String, pass: String) {
try {
val bytes = android.util.Base64.decode(p12Base64, android.util.Base64.DEFAULT)
val ks = KeyStore.getInstance("PKCS12")
ks.load(java.io.ByteArrayInputStream(bytes), pass.toCharArray())
val aliases = ks.aliases()
if (aliases.hasMoreElements()) {
val alias = aliases.nextElement()
privateKey = ks.getKey(alias, pass.toCharArray()) as PrivateKey
val certs = ks.getCertificateChain(alias)
certificateChain = certs?.map { it as X509Certificate }?.toTypedArray()
}
} catch (e: Exception) {
e.printStackTrace()
clear()
throw e
}
}

fun clear() {
privateKey = null
certificateChain = null
}
}
Loading
Loading