generated from ali/HarmonyTemplate
提交 Haven Android 仓库源码 v5.87.79
This commit is contained in:
@@ -0,0 +1,39 @@
|
||||
plugins {
|
||||
alias(libs.plugins.android.library)
|
||||
alias(libs.plugins.hilt)
|
||||
alias(libs.plugins.ksp)
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "sh.haven.core.spa"
|
||||
compileSdk = 37
|
||||
|
||||
defaultConfig {
|
||||
minSdk = 26
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
}
|
||||
|
||||
testOptions {
|
||||
unitTests.isReturnDefaultValues = true
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(libs.coroutines.core)
|
||||
implementation(libs.coroutines.android)
|
||||
implementation(libs.hilt.android)
|
||||
ksp(libs.hilt.compiler)
|
||||
|
||||
testImplementation(libs.junit)
|
||||
testImplementation(libs.coroutines.test)
|
||||
}
|
||||
|
||||
kotlin {
|
||||
compilerOptions {
|
||||
jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package sh.haven.core.spa
|
||||
|
||||
import java.security.MessageDigest
|
||||
import java.security.SecureRandom
|
||||
import java.util.Base64
|
||||
import javax.crypto.Cipher
|
||||
import javax.crypto.Mac
|
||||
import javax.crypto.spec.IvParameterSpec
|
||||
import javax.crypto.spec.SecretKeySpec
|
||||
|
||||
/**
|
||||
* Builds an fwknop SPA packet (AES-256-CBC + HMAC-SHA256, the fwknop defaults).
|
||||
*
|
||||
* The wire format is reproduced from libfko (`fko_encode.c`, `cipher_funcs.c`,
|
||||
* `fko_funcs.c`) and is interoperable with a stock `fwknopd`:
|
||||
*
|
||||
* 1. Plaintext, colon-joined (base64 fields have `=` stripped):
|
||||
* `{rand16}:b64(user):{timestamp}:{version}:{msgType}:b64(accessMsg)`
|
||||
* 2. Append the SHA-256 message digest: `plaintext = encoded + ":" + b64(SHA256(encoded))`
|
||||
* 3. AES-256-CBC encrypt with an OpenSSL `Salted__` header. Key+IV derive from the
|
||||
* key bytes and an 8-byte random salt via EVP_BytesToKey (MD5, 1 iteration).
|
||||
* `raw = "Salted__" + salt + ciphertext`; `b64ct = base64(raw)` with `=` stripped.
|
||||
* 4. HMAC-SHA256 over the **full** `b64ct` (including the constant `U2FsdGVkX1`
|
||||
* prefix); base64 it (`=` stripped) and append directly, no separator.
|
||||
* 5. Transmit `b64ct` with the constant 10-char salt prefix removed, then the HMAC:
|
||||
* `packet = b64ct.substring(10) + hmac`.
|
||||
*
|
||||
* Everything is deterministic given [now], [salt] and [rand], so the builder is
|
||||
* unit-testable against fwknop reference vectors.
|
||||
*/
|
||||
object FwknopPacket {
|
||||
|
||||
/** FKO protocol version advertised in the message (fwknopd is lenient; ≤ 8 chars). */
|
||||
const val VERSION = "3.0.0"
|
||||
|
||||
/** `FKO_ACCESS_MSG` — "open these ports". */
|
||||
const val MSG_TYPE_ACCESS = 1
|
||||
|
||||
/** Client username field; fwknopd does not check it in AES mode. */
|
||||
const val DEFAULT_USER = "haven"
|
||||
|
||||
/** `FKO_RAND_VAL_SIZE` — the leading random field is 16 decimal digits. */
|
||||
private const val RAND_DIGITS = 16
|
||||
|
||||
private const val SALT_LEN = 8
|
||||
private const val AES_KEY_LEN = 32
|
||||
private const val AES_IV_LEN = 16
|
||||
|
||||
/** `B64_RIJNDAEL_SALT` — base64("Salted__"…) always starts with these 10 chars. */
|
||||
private const val B64_SALT_PREFIX = "U2FsdGVkX1"
|
||||
|
||||
private val rng = SecureRandom()
|
||||
|
||||
/**
|
||||
* Build the ASCII SPA packet for [config]. [resolvedIp] supplies the egress IP
|
||||
* for [SpaConfig.AllowMode.RESOLVE]. [now], [salt] and [rand] are injectable
|
||||
* for testing; production callers omit them.
|
||||
*/
|
||||
fun build(
|
||||
config: SpaConfig,
|
||||
resolvedIp: String? = null,
|
||||
username: String = DEFAULT_USER,
|
||||
now: Long = System.currentTimeMillis(),
|
||||
salt: ByteArray = randomSalt(),
|
||||
rand: String = randomRand(),
|
||||
): String {
|
||||
val accessMsg = config.accessMessage(resolvedIp)
|
||||
val plaintext = buildPlaintext(rand, username, now / 1000, accessMsg)
|
||||
val b64ct = encrypt(plaintext.toByteArray(Charsets.US_ASCII), config.keyBytes, salt)
|
||||
val hmac = config.hmacKeyBytes?.let { hmacSha256(b64ct, it) } ?: ""
|
||||
check(b64ct.startsWith(B64_SALT_PREFIX)) { "unexpected ciphertext encoding" }
|
||||
return b64ct.substring(B64_SALT_PREFIX.length) + hmac
|
||||
}
|
||||
|
||||
/** The colon-joined message with its trailing SHA-256 digest appended. */
|
||||
internal fun buildPlaintext(rand: String, username: String, epochSeconds: Long, accessMsg: String): String {
|
||||
val encoded = buildString {
|
||||
append(rand); append(':')
|
||||
append(b64(username.toByteArray(Charsets.US_ASCII))); append(':')
|
||||
append(epochSeconds); append(':')
|
||||
append(VERSION); append(':')
|
||||
append(MSG_TYPE_ACCESS); append(':')
|
||||
append(b64(accessMsg.toByteArray(Charsets.US_ASCII)))
|
||||
}
|
||||
val digest = b64(sha256(encoded.toByteArray(Charsets.US_ASCII)))
|
||||
return "$encoded:$digest"
|
||||
}
|
||||
|
||||
/** AES-256-CBC encrypt with OpenSSL Salted__ framing; returns base64 (`=` stripped). */
|
||||
internal fun encrypt(plaintext: ByteArray, keyBytes: ByteArray, salt: ByteArray): String {
|
||||
val (key, iv) = evpBytesToKey(keyBytes, salt)
|
||||
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
|
||||
cipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(key, "AES"), IvParameterSpec(iv))
|
||||
val ct = cipher.doFinal(plaintext)
|
||||
val raw = ByteArray(SALT_LEN + SALT_LEN + ct.size)
|
||||
SALTED_MAGIC.copyInto(raw, 0)
|
||||
salt.copyInto(raw, SALT_LEN)
|
||||
ct.copyInto(raw, SALT_LEN + SALT_LEN)
|
||||
return b64(raw)
|
||||
}
|
||||
|
||||
/**
|
||||
* OpenSSL EVP_BytesToKey, MD5, count = 1 — matches libfko `rij_salt_and_iv`.
|
||||
* `D1 = MD5(pw‖salt)`, `Dn = MD5(D(n-1)‖pw‖salt)`; key = first 32 bytes, IV = next 16.
|
||||
*/
|
||||
internal fun evpBytesToKey(password: ByteArray, salt: ByteArray): Pair<ByteArray, ByteArray> {
|
||||
val md5 = MessageDigest.getInstance("MD5")
|
||||
val out = ByteArray(AES_KEY_LEN + AES_IV_LEN)
|
||||
var generated = 0
|
||||
var prev = ByteArray(0)
|
||||
while (generated < out.size) {
|
||||
md5.reset()
|
||||
md5.update(prev)
|
||||
md5.update(password)
|
||||
md5.update(salt)
|
||||
prev = md5.digest()
|
||||
val n = minOf(prev.size, out.size - generated)
|
||||
prev.copyInto(out, generated, 0, n)
|
||||
generated += n
|
||||
}
|
||||
return out.copyOfRange(0, AES_KEY_LEN) to out.copyOfRange(AES_KEY_LEN, AES_KEY_LEN + AES_IV_LEN)
|
||||
}
|
||||
|
||||
private fun hmacSha256(b64ct: String, hmacKey: ByteArray): String {
|
||||
val mac = Mac.getInstance("HmacSHA256")
|
||||
mac.init(SecretKeySpec(hmacKey, "HmacSHA256"))
|
||||
return b64(mac.doFinal(b64ct.toByteArray(Charsets.US_ASCII)))
|
||||
}
|
||||
|
||||
private fun sha256(data: ByteArray): ByteArray =
|
||||
MessageDigest.getInstance("SHA-256").digest(data)
|
||||
|
||||
/** Standard base64 with trailing `=` stripped, matching libfko's `strip_b64_eq`. */
|
||||
private fun b64(data: ByteArray): String =
|
||||
Base64.getEncoder().withoutPadding().encodeToString(data)
|
||||
|
||||
private fun randomSalt(): ByteArray = ByteArray(SALT_LEN).also { rng.nextBytes(it) }
|
||||
|
||||
private fun randomRand(): String = buildString(RAND_DIGITS) {
|
||||
repeat(RAND_DIGITS) { append(rng.nextInt(10)) }
|
||||
}
|
||||
|
||||
private val SALTED_MAGIC = "Salted__".toByteArray(Charsets.US_ASCII)
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
package sh.haven.core.spa
|
||||
|
||||
import java.util.Base64
|
||||
|
||||
/**
|
||||
* Per-connection-profile configuration for fwknop Single Packet Authorization.
|
||||
*
|
||||
* SPA is the cryptographic successor to port knocking ([sh.haven.core.knock]):
|
||||
* instead of an observable sequence of SYNs, the client sends one AES-encrypted,
|
||||
* HMAC-authenticated UDP packet that a passive observer can neither read nor
|
||||
* replay. Haven builds and sends this packet itself, just before the real
|
||||
* connect, via the same `preConnect` hook the knock uses.
|
||||
*
|
||||
* A blank [key] or [accessSpec] means "SPA disabled for this profile" — see
|
||||
* [parse], which returns `null` in that case.
|
||||
*/
|
||||
data class SpaConfig(
|
||||
/** Rijndael/AES key. Used as the OpenSSL passphrase (or base64-decoded when [keyIsBase64]). */
|
||||
val key: String,
|
||||
val keyIsBase64: Boolean = false,
|
||||
/** Optional HMAC-SHA256 key (encrypt-then-MAC). Blank/null = legacy no-HMAC mode. */
|
||||
val hmacKey: String? = null,
|
||||
val hmacKeyIsBase64: Boolean = false,
|
||||
/**
|
||||
* Access request, everything after the allow-IP: `proto/port` token(s),
|
||||
* comma-separated, e.g. `"tcp/22"` or `"tcp/22,tcp/80"`.
|
||||
*/
|
||||
val accessSpec: String,
|
||||
/** How the allow-IP embedded in the SPA message is chosen. */
|
||||
val allowMode: AllowMode = AllowMode.SOURCE,
|
||||
/** Allow-IP/CIDR for [AllowMode.EXPLICIT]. */
|
||||
val explicitIp: String? = null,
|
||||
/** Destination UDP port for the SPA packet (fwknopd's `PCAP_FILTER`, default 62201). */
|
||||
val spaPort: Int = DEFAULT_SPA_PORT,
|
||||
) {
|
||||
enum class AllowMode {
|
||||
/** Send `0.0.0.0`; fwknopd opens for the SPA packet's observed source IP. */
|
||||
SOURCE,
|
||||
|
||||
/** Resolve our public egress IP (like `fwknop -R`) and embed it. */
|
||||
RESOLVE,
|
||||
|
||||
/** Embed a fixed [explicitIp]. */
|
||||
EXPLICIT,
|
||||
}
|
||||
|
||||
init {
|
||||
require(key.isNotEmpty()) { "SPA key is required" }
|
||||
require(accessSpec.isNotBlank()) { "SPA access spec is required" }
|
||||
require(spaPort in 1..65535) { "SPA port out of range: $spaPort" }
|
||||
if (allowMode == AllowMode.EXPLICIT) {
|
||||
require(!explicitIp.isNullOrBlank()) { "explicit allow-IP required for EXPLICIT mode" }
|
||||
}
|
||||
if (keyIsBase64) decodeB64(key) { "SPA key is not valid base64" }
|
||||
hmacKey?.takeIf { it.isNotEmpty() }?.let {
|
||||
if (hmacKeyIsBase64) decodeB64(it) { "HMAC key is not valid base64" }
|
||||
}
|
||||
}
|
||||
|
||||
/** Raw AES passphrase bytes (base64-decoded when [keyIsBase64]). */
|
||||
val keyBytes: ByteArray
|
||||
get() = if (keyIsBase64) decodeB64(key) { "SPA key" } else key.toByteArray(Charsets.US_ASCII)
|
||||
|
||||
/** Raw HMAC key bytes, or null when no HMAC key is configured. */
|
||||
val hmacKeyBytes: ByteArray?
|
||||
get() = hmacKey?.takeIf { it.isNotEmpty() }?.let {
|
||||
if (hmacKeyIsBase64) decodeB64(it) { "HMAC key" } else it.toByteArray(Charsets.US_ASCII)
|
||||
}
|
||||
|
||||
/**
|
||||
* The fwknop access message — `"{allowIP},{accessSpec}"`. [resolvedIp] is the
|
||||
* egress IP fetched by [SpaSender] for [AllowMode.RESOLVE]; ignored otherwise.
|
||||
*/
|
||||
fun accessMessage(resolvedIp: String? = null): String {
|
||||
val allowIp = when (allowMode) {
|
||||
AllowMode.SOURCE -> "0.0.0.0"
|
||||
AllowMode.EXPLICIT -> explicitIp!!.trim()
|
||||
AllowMode.RESOLVE -> requireNotNull(resolvedIp?.trim()?.ifEmpty { null }) {
|
||||
"RESOLVE mode requires a resolved egress IP"
|
||||
}
|
||||
}
|
||||
return "$allowIp,$accessSpec"
|
||||
}
|
||||
|
||||
companion object {
|
||||
/** fwknopd's default SPA UDP port. */
|
||||
const val DEFAULT_SPA_PORT = 62201
|
||||
|
||||
/**
|
||||
* Build a [SpaConfig] from per-profile fields. Returns:
|
||||
* - `Result.success(null)` when SPA is disabled (blank key or blank access spec),
|
||||
* - `Result.success(config)` for a valid config,
|
||||
* - `Result.failure(IllegalArgumentException)` for malformed input.
|
||||
*/
|
||||
fun parse(
|
||||
key: String?,
|
||||
keyIsBase64: Boolean,
|
||||
hmacKey: String?,
|
||||
hmacKeyIsBase64: Boolean,
|
||||
accessSpec: String?,
|
||||
allowMode: String?,
|
||||
explicitIp: String?,
|
||||
spaPort: Int,
|
||||
): Result<SpaConfig?> {
|
||||
val k = key?.trim().orEmpty()
|
||||
val spec = accessSpec?.trim().orEmpty()
|
||||
if (k.isEmpty() || spec.isEmpty()) return Result.success(null)
|
||||
return runCatching {
|
||||
validateAccessSpec(spec)
|
||||
val mode = parseAllowMode(allowMode)
|
||||
SpaConfig(
|
||||
key = k,
|
||||
keyIsBase64 = keyIsBase64,
|
||||
hmacKey = hmacKey?.trim()?.ifEmpty { null },
|
||||
hmacKeyIsBase64 = hmacKeyIsBase64,
|
||||
accessSpec = spec,
|
||||
allowMode = mode,
|
||||
explicitIp = explicitIp?.trim()?.ifEmpty { null },
|
||||
spaPort = if (spaPort in 1..65535) spaPort else DEFAULT_SPA_PORT,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun parseAllowMode(raw: String?): AllowMode =
|
||||
when (raw?.trim()?.uppercase()) {
|
||||
null, "", "SOURCE" -> AllowMode.SOURCE
|
||||
"RESOLVE" -> AllowMode.RESOLVE
|
||||
"EXPLICIT" -> AllowMode.EXPLICIT
|
||||
else -> throw IllegalArgumentException("unknown allow mode '$raw'")
|
||||
}
|
||||
|
||||
/** Validate `proto/port[,proto/port...]` — each token is tcp|udp and port 1..65535. */
|
||||
private fun validateAccessSpec(spec: String) {
|
||||
val tokens = spec.split(',').map { it.trim() }.filter { it.isNotEmpty() }
|
||||
require(tokens.isNotEmpty()) { "empty access spec" }
|
||||
for (t in tokens) {
|
||||
val parts = t.split('/')
|
||||
require(parts.size == 2) { "access token must be proto/port: '$t'" }
|
||||
val proto = parts[0].lowercase()
|
||||
require(proto == "tcp" || proto == "udp") {
|
||||
"unknown protocol '${parts[0]}' in '$t' (expected tcp or udp)"
|
||||
}
|
||||
val port = parts[1].toIntOrNull()
|
||||
?: throw IllegalArgumentException("not a port: '${parts[1]}' in '$t'")
|
||||
require(port in 1..65535) { "port out of range: $port (token '$t')" }
|
||||
}
|
||||
}
|
||||
|
||||
private inline fun decodeB64(s: String, msg: () -> String): ByteArray =
|
||||
try {
|
||||
Base64.getDecoder().decode(s.trim())
|
||||
} catch (e: IllegalArgumentException) {
|
||||
throw IllegalArgumentException("${msg()}: ${e.message}", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package sh.haven.core.spa
|
||||
|
||||
import dagger.Binds
|
||||
import dagger.Module
|
||||
import dagger.hilt.InstallIn
|
||||
import dagger.hilt.components.SingletonComponent
|
||||
import javax.inject.Singleton
|
||||
|
||||
@Module
|
||||
@InstallIn(SingletonComponent::class)
|
||||
abstract class SpaHiltModule {
|
||||
@Binds
|
||||
@Singleton
|
||||
abstract fun bindSpaSender(impl: DefaultSpaSender): SpaSender
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package sh.haven.core.spa
|
||||
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.IOException
|
||||
import java.net.DatagramPacket
|
||||
import java.net.DatagramSocket
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.InetAddress
|
||||
import java.net.URL
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
/** Outcome of an SPA send. [error] is null on success; the packet length is bytes put on the wire. */
|
||||
data class SpaResult(
|
||||
val packetLen: Int,
|
||||
val totalDurationMs: Long,
|
||||
val error: Throwable? = null,
|
||||
) {
|
||||
val ok: Boolean get() = error == null
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds and sends a single fwknop SPA packet to a host, just before the real
|
||||
* connect. The sibling of [sh.haven.core.knock.PortKnocker]: failures are
|
||||
* returned in [SpaResult.error] rather than thrown, so the caller decides
|
||||
* whether to abort the connect.
|
||||
*/
|
||||
interface SpaSender {
|
||||
suspend fun send(host: String, config: SpaConfig): SpaResult
|
||||
}
|
||||
|
||||
@Singleton
|
||||
class DefaultSpaSender @Inject constructor() : SpaSender {
|
||||
|
||||
/** Give fwknopd a moment to install the firewall rule before we connect. */
|
||||
private val postSendSettleMs = 1_000L
|
||||
|
||||
override suspend fun send(host: String, config: SpaConfig): SpaResult =
|
||||
withContext(Dispatchers.IO) {
|
||||
val started = System.currentTimeMillis()
|
||||
try {
|
||||
val resolvedIp =
|
||||
if (config.allowMode == SpaConfig.AllowMode.RESOLVE) resolvePublicIp() else null
|
||||
val packet = FwknopPacket.build(config, resolvedIp = resolvedIp)
|
||||
val bytes = packet.toByteArray(Charsets.US_ASCII)
|
||||
val addr = InetAddress.getByName(host)
|
||||
sendUdp(addr, config.spaPort, bytes)
|
||||
delay(postSendSettleMs)
|
||||
SpaResult(bytes.size, System.currentTimeMillis() - started)
|
||||
} catch (t: Throwable) {
|
||||
SpaResult(0, System.currentTimeMillis() - started, t)
|
||||
}
|
||||
}
|
||||
|
||||
private fun sendUdp(addr: InetAddress, port: Int, payload: ByteArray) {
|
||||
val socket = DatagramSocket()
|
||||
try {
|
||||
socket.send(DatagramPacket(payload, payload.size, addr, port))
|
||||
} finally {
|
||||
try { socket.close() } catch (_: IOException) { /* ignore */ }
|
||||
}
|
||||
}
|
||||
|
||||
/** Resolve our public egress IP (like `fwknop -R`). Throws if it can't be determined. */
|
||||
private fun resolvePublicIp(): String {
|
||||
val conn = (URL(RESOLVE_URL).openConnection() as HttpURLConnection).apply {
|
||||
connectTimeout = 5_000
|
||||
readTimeout = 5_000
|
||||
requestMethod = "GET"
|
||||
}
|
||||
try {
|
||||
val body = conn.inputStream.bufferedReader().use { it.readText() }.trim()
|
||||
require(body.isNotEmpty()) { "empty response from $RESOLVE_URL" }
|
||||
return body
|
||||
} finally {
|
||||
conn.disconnect()
|
||||
}
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val RESOLVE_URL = "https://api.ipify.org"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
package sh.haven.core.spa
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import java.util.Base64
|
||||
import javax.crypto.Cipher
|
||||
import javax.crypto.spec.IvParameterSpec
|
||||
import javax.crypto.spec.SecretKeySpec
|
||||
|
||||
/**
|
||||
* Validates [FwknopPacket] against a reference vector produced by the real
|
||||
* fwknop client (`fwknop 2.6.11`, FKO protocol 3.0.0):
|
||||
*
|
||||
* ```
|
||||
* fwknop -A tcp/22 -a 0.0.0.0 -D 127.0.0.1 \
|
||||
* --key-base64-rijndael VGyQKiiQC25MzkbuIZvrgQ== \
|
||||
* --key-base64-hmac /q0iwIDKH0RsMmFXKwcvKp5Cq4bGOmfeBc/+pYZtDDQ= \
|
||||
* --use-hmac --test -v -v
|
||||
* ```
|
||||
*/
|
||||
class FwknopPacketTest {
|
||||
|
||||
private val keyB64 = "VGyQKiiQC25MzkbuIZvrgQ=="
|
||||
private val hmacKeyB64 = "/q0iwIDKH0RsMmFXKwcvKp5Cq4bGOmfeBc/+pYZtDDQ="
|
||||
|
||||
// Fields fwknop printed for the captured packet.
|
||||
private val rand = "8003520420295423"
|
||||
private val username = "ian"
|
||||
private val timestamp = 1779533765L
|
||||
private val encodedData = "8003520420295423:aWFu:1779533765:3.0.0:1:MC4wLjAuMCx0Y3AvMjI"
|
||||
private val digest = "qnW9Lq9rdUVuK1uKSwgIp0jvaSaB4G+Vh5svqH5rZ8o"
|
||||
private val refHmac = "bb4coANLBDIaAbQWtQTzBndZdrORdozMoffnXvki5Io"
|
||||
|
||||
// The transmitted ciphertext (salt prefix "U2FsdGVkX1" already stripped).
|
||||
private val ctPart =
|
||||
"/JzAKGM8AnoIUZd+WyEYrqzqAHeFx/Fl6M+49wg0eh+GOsNA7rv2bPNvVslWYWd4pkugOyweoB6tZeZ" +
|
||||
"7DzkrisXWFXT9rCrdylAFtGojgdAXy1ULr0XTfSWP2nsvFNZnp9I7kBgC/b8ZSNqngKZknCLG2Yoiig" +
|
||||
"PsY"
|
||||
|
||||
private val saltPrefix = "U2FsdGVkX1"
|
||||
|
||||
private fun config() = SpaConfig(
|
||||
key = keyB64,
|
||||
keyIsBase64 = true,
|
||||
hmacKey = hmacKeyB64,
|
||||
hmacKeyIsBase64 = true,
|
||||
accessSpec = "tcp/22",
|
||||
allowMode = SpaConfig.AllowMode.SOURCE,
|
||||
spaPort = SpaConfig.DEFAULT_SPA_PORT,
|
||||
)
|
||||
|
||||
/** Lenient base64 decode that tolerates fwknop's stripped padding. */
|
||||
private fun b64decode(s: String): ByteArray {
|
||||
val pad = (4 - s.length % 4) % 4
|
||||
return Base64.getDecoder().decode(s + "=".repeat(pad))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `encoded message and digest match fwknop`() {
|
||||
val plaintext = FwknopPacket.buildPlaintext(rand, username, timestamp, "0.0.0.0,tcp/22")
|
||||
assertEquals("$encodedData:$digest", plaintext)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `byte-exact reproduction of a real fwknop packet`() {
|
||||
// Recover the random salt fwknop used, then feed it back to the builder.
|
||||
val fullB64ct = saltPrefix + ctPart
|
||||
val raw = b64decode(fullB64ct)
|
||||
val salt = raw.copyOfRange(8, 16) // "Salted__"(8) | salt(8) | ciphertext
|
||||
|
||||
val packet = FwknopPacket.build(
|
||||
config(),
|
||||
username = username,
|
||||
now = timestamp * 1000,
|
||||
salt = salt,
|
||||
rand = rand,
|
||||
)
|
||||
assertEquals(ctPart + refHmac, packet)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `decrypting the fwknop packet recovers the plaintext`() {
|
||||
val raw = b64decode(saltPrefix + ctPart)
|
||||
val salt = raw.copyOfRange(8, 16)
|
||||
val cipherBytes = raw.copyOfRange(16, raw.size)
|
||||
val (key, iv) = FwknopPacket.evpBytesToKey(b64decode(keyB64), salt)
|
||||
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
|
||||
cipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(key, "AES"), IvParameterSpec(iv))
|
||||
val recovered = String(cipher.doFinal(cipherBytes), Charsets.US_ASCII)
|
||||
assertEquals("$encodedData:$digest", recovered)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `self round-trip decrypts to the original plaintext`() {
|
||||
val cfg = config()
|
||||
val salt = ByteArray(8) { (it + 1).toByte() }
|
||||
val packet = FwknopPacket.build(cfg, username = username, now = timestamp * 1000, salt = salt, rand = rand)
|
||||
|
||||
// Strip the HMAC (last 43 chars of base64 SHA-256), re-add salt prefix, decrypt.
|
||||
val ctOnly = packet.dropLast(refHmac.length)
|
||||
val raw = b64decode(saltPrefix + ctOnly)
|
||||
val cipherBytes = raw.copyOfRange(16, raw.size)
|
||||
val (key, iv) = FwknopPacket.evpBytesToKey(b64decode(keyB64), salt)
|
||||
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
|
||||
cipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(key, "AES"), IvParameterSpec(iv))
|
||||
val recovered = String(cipher.doFinal(cipherBytes), Charsets.US_ASCII)
|
||||
assertEquals("$encodedData:$digest", recovered)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `no-HMAC mode omits the trailing mac`() {
|
||||
val cfg = config().copy(hmacKey = null)
|
||||
val salt = ByteArray(8) { 7 }
|
||||
val withHmac = FwknopPacket.build(config(), now = timestamp * 1000, salt = salt, rand = rand)
|
||||
val noHmac = FwknopPacket.build(cfg, now = timestamp * 1000, salt = salt, rand = rand)
|
||||
// The HMAC variant is exactly 43 base64 chars longer (SHA-256 digest, stripped).
|
||||
assertEquals(43, withHmac.length - noHmac.length)
|
||||
assertTrue(withHmac.startsWith(noHmac))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `generated random field is 16 decimal digits`() {
|
||||
val cfg = config()
|
||||
repeat(50) {
|
||||
val packet = FwknopPacket.build(cfg)
|
||||
// Decrypt to inspect the rand field is unnecessary; assert the builder's own rand.
|
||||
assertTrue(packet.isNotEmpty())
|
||||
}
|
||||
// Inspect the rand directly via a fixed-salt build + decrypt.
|
||||
val salt = ByteArray(8) { 3 }
|
||||
val packet = FwknopPacket.build(cfg, now = timestamp * 1000, salt = salt)
|
||||
val ctOnly = packet.dropLast(refHmac.length)
|
||||
val raw = b64decode(saltPrefix + ctOnly)
|
||||
val (key, iv) = FwknopPacket.evpBytesToKey(b64decode(keyB64), salt)
|
||||
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
|
||||
cipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(key, "AES"), IvParameterSpec(iv))
|
||||
val recovered = String(cipher.doFinal(raw.copyOfRange(16, raw.size)), Charsets.US_ASCII)
|
||||
val randField = recovered.substringBefore(':')
|
||||
assertEquals(16, randField.length)
|
||||
assertTrue(randField.all { it.isDigit() })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `evpBytesToKey produces 32-byte key and 16-byte iv`() {
|
||||
val (key, iv) = FwknopPacket.evpBytesToKey(b64decode(keyB64), ByteArray(8))
|
||||
assertEquals(32, key.size)
|
||||
assertEquals(16, iv.size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `source mode embeds 0_0_0_0 as the allow ip`() {
|
||||
assertEquals("0.0.0.0,tcp/22", config().accessMessage())
|
||||
assertFalse(config().accessMessage().contains("U2FsdGVkX1"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package sh.haven.core.spa
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class SpaConfigTest {
|
||||
|
||||
private fun parse(
|
||||
key: String? = "secret",
|
||||
keyB64: Boolean = false,
|
||||
hmac: String? = null,
|
||||
hmacB64: Boolean = false,
|
||||
access: String? = "tcp/22",
|
||||
mode: String? = "SOURCE",
|
||||
ip: String? = null,
|
||||
port: Int = SpaConfig.DEFAULT_SPA_PORT,
|
||||
) = SpaConfig.parse(key, keyB64, hmac, hmacB64, access, mode, ip, port)
|
||||
|
||||
@Test
|
||||
fun `blank key disables SPA`() {
|
||||
assertNull(parse(key = "").getOrThrow())
|
||||
assertNull(parse(key = null).getOrThrow())
|
||||
assertNull(parse(key = " ").getOrThrow())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `blank access spec disables SPA`() {
|
||||
assertNull(parse(access = "").getOrThrow())
|
||||
assertNull(parse(access = null).getOrThrow())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `valid minimal config parses`() {
|
||||
val cfg = parse().getOrThrow()!!
|
||||
assertEquals("secret", cfg.key)
|
||||
assertEquals("tcp/22", cfg.accessSpec)
|
||||
assertEquals(SpaConfig.AllowMode.SOURCE, cfg.allowMode)
|
||||
assertEquals(SpaConfig.DEFAULT_SPA_PORT, cfg.spaPort)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `multi-port access spec is accepted`() {
|
||||
val cfg = parse(access = "tcp/22,udp/53").getOrThrow()!!
|
||||
assertEquals("tcp/22,udp/53", cfg.accessSpec)
|
||||
assertEquals("0.0.0.0,tcp/22,udp/53", cfg.accessMessage())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `bad protocol fails`() {
|
||||
assertTrue(parse(access = "sctp/22").isFailure)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `bad port fails`() {
|
||||
assertTrue(parse(access = "tcp/0").isFailure)
|
||||
assertTrue(parse(access = "tcp/70000").isFailure)
|
||||
assertTrue(parse(access = "tcp/abc").isFailure)
|
||||
assertTrue(parse(access = "tcp").isFailure)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `explicit mode requires an ip`() {
|
||||
assertTrue(parse(mode = "EXPLICIT", ip = null).isFailure)
|
||||
val cfg = parse(mode = "EXPLICIT", ip = "203.0.113.7").getOrThrow()!!
|
||||
assertEquals("203.0.113.7,tcp/22", cfg.accessMessage())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `unknown allow mode fails`() {
|
||||
assertTrue(parse(mode = "BOGUS").isFailure)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `invalid base64 key fails`() {
|
||||
assertTrue(parse(key = "not valid base64!!!", keyB64 = true).isFailure)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `out-of-range spa port falls back to default`() {
|
||||
assertEquals(SpaConfig.DEFAULT_SPA_PORT, parse(port = 0).getOrThrow()!!.spaPort)
|
||||
assertEquals(SpaConfig.DEFAULT_SPA_PORT, parse(port = 99999).getOrThrow()!!.spaPort)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `resolve mode needs resolved ip at message time`() {
|
||||
val cfg = parse(mode = "RESOLVE").getOrThrow()!!
|
||||
assertEquals("198.51.100.4,tcp/22", cfg.accessMessage("198.51.100.4"))
|
||||
assertTrue(runCatching { cfg.accessMessage(null) }.isFailure)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user