Release 0.9.0-SNAPSHOT with concealed KMP transports

This commit is contained in:
sergeych committed 2026-10-22 02:41:08 +04:00
1 parent 009d62a155
commit 73a785d45c
55 files changed
+6051 -25

No files matched your search

@@ -0,0 +1,174 @@
@file:OptIn(ExperimentalUnsignedTypes::class, ExperimentalConcealedProtocol::class)
package net.sergeych.kiloparsec.concealed
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.test.runTest
import net.sergeych.crypto2.*
import net.sergeych.kiloparsec.*
import kotlin.test.*
import kotlin.time.Duration.Companion.seconds
class ConcealedClientTest {
private class Credentials {
val encryption = DecryptingSecretKey.new()
val server = SigningSecretKey.new()
val client = SigningSecretKey.new()
}
private val options = ConcealedOptions(
handshake = ConcealedOptions.Handshake(timeoutMillis = 15_000, maxAttempts = 3, retryDelayMillis = 0),
padding = ConcealedOptions.Padding(0),
)
private class MemoryCarrier(
private val input: Channel<UByteArray>,
private val output: Channel<UByteArray>,
) : ConcealedCarrier {
override val kind = ConcealedCarrier.Kind.STREAM
var closed = false
override suspend fun receive() = input.receiveCatching().getOrNull()
override suspend fun send(bytes: UByteArray) { output.send(bytes.copyOf()) }
override suspend fun close() { closed = true; input.close(); output.close() }
}
private fun carriers(): Pair<MemoryCarrier, MemoryCarrier> {
val a = Channel<UByteArray>(16)
val b = Channel<UByteArray>(16)
return MemoryCarrier(a, b) to MemoryCarrier(b, a)
}
private fun client(credentials: Credentials, local: KiloInterface<Unit> = KiloInterface(),
options: ConcealedOptions = this.options, connect: suspend () -> ConcealedCarrier) =
ConcealedClient(local, Unit, credentials.encryption.publicKey, credentials.server.verifyingKey,
credentials.client, options, connect)
@Test fun finiteConnectorFailuresReleaseEarlyRpc() = runTest(timeout = 60.seconds) {
initCrypto()
val credentials = Credentials()
var attempts = 0
val failure = IllegalStateException("Connector failed")
val client = client(credentials) { attempts++; throw failure }
val echo by command<Int, Int>()
val early = async { runCatching { client.call(echo, 1) } }
val result = runCatching { client.run() }
// Coroutine stack-trace recovery may copy ordinary JVM exception instances.
val runFailure = result.exceptionOrNull()
val queuedFailure = early.await().exceptionOrNull()
assertIs<IllegalStateException>(runFailure, runFailure?.stackTraceToString())
assertIs<IllegalStateException>(queuedFailure, queuedFailure?.stackTraceToString())
assertEquals(failure.message, runFailure.message)
assertEquals(failure.message, queuedFailure.message)
assertEquals(3, attempts)
client.close()
}
@Test fun timedOutAttemptsUseFreshCarriersAndFreshHellos() = runTest(timeout = 60.seconds) {
initCrypto()
val credentials = Credentials()
val hellos = mutableListOf<UByteArray>()
var closed = 0
var attempts = 0
val client = client(credentials, options = options.copy(handshake = options.handshake.copy(timeoutMillis = 100))) {
attempts++
object : ConcealedCarrier {
override val kind = ConcealedCarrier.Kind.STREAM
private var isClosed = false
override suspend fun receive(): UByteArray? = awaitCancellation()
override suspend fun send(bytes: UByteArray) { hellos += bytes.copyOf() }
override suspend fun close() { if (!isClosed) { isClosed = true; closed++ } }
}
}
assertTrue(runCatching { client.run() }.isFailure)
assertEquals(3, attempts)
assertEquals(3, closed)
assertEquals(3, hellos.size)
for (i in hellos.indices) for (j in 0 until i) {
assertFalse(hellos[i].contentEquals(hellos[j]))
assertFalse(hellos[i].copyOfRange(0, 32).contentEquals(hellos[j].copyOfRange(0, 32)))
}
client.close()
}
@Test fun authenticatedPolicyAndSignatureFailuresAreNotRetried() = runTest(timeout = 60.seconds) {
initCrypto()
for (badSignature in listOf(false, true)) {
val credentials = Credentials()
val jobs = mutableListOf<Job>()
var attempts = 0
val policyFailure = LocalInterface.BreakConnectionException("Reject authenticated peer")
val local = KiloInterface<Unit>().apply {
if (!badSignature) onConnected { throw policyFailure }
}
val signer = if (!badSignature) credentials.server else object : SigningKey by credentials.server {
override fun sign(message: UByteArray) = credentials.server.sign(message).also {
it[0] = (it[0].toInt() xor 1).toUByte()
}
}
val client = client(credentials, local) {
attempts++
val (a, b) = carriers()
val server = ConcealedConnection.server(KiloInterface<Unit>(), b, Unit,
ConcealedServerIdentity(credentials.encryption, signer), options)
jobs += launch { runCatching { server.run() } }
a
}
try {
val failure = runCatching { client.run() }.exceptionOrNull()
assertNotNull(failure)
if (!badSignature) assertSame(policyFailure, failure)
assertEquals(1, attempts)
} finally { client.close(); jobs.forEach { it.cancelAndJoin() } }
}
}
@Test fun closeDuringBlockedConnectorCancelsRunAndReleasesWaiters() = runTest(timeout = 60.seconds) {
initCrypto()
val credentials = Credentials()
val entered = CompletableDeferred<Unit>()
val exited = CompletableDeferred<Unit>()
val client = client(credentials) {
entered.complete(Unit)
try { awaitCancellation() } finally { exited.complete(Unit) }
}
val echo by command<Int, Int>()
val early = async { runCatching { client.call(echo, 1) } }
val running = async { runCatching { client.run() } }
entered.await()
client.close()
exited.await()
assertTrue(running.await().isFailure)
assertTrue(early.await().isFailure)
}
@Test fun reconnectBeforeEstablishmentDoesNotReplayUncertainApplicationCall() = runTest(timeout = 60.seconds) {
initCrypto()
val credentials = Credentials()
val commit by command<Int, Int>()
val enteredCommand = CompletableDeferred<Unit>()
var executions = 0
var attempts = 0
lateinit var server: ConcealedConnection<Unit>
var serverRun: Job? = null
val client = client(credentials) {
attempts++
if (attempts == 1) throw IllegalStateException("First endpoint unavailable")
val (a, b) = carriers()
val local = KiloInterface<Unit>().apply {
on(commit) { executions++; enteredCommand.complete(Unit); awaitCancellation() }
}
server = ConcealedConnection.server(local, b, Unit,
ConcealedServerIdentity(credentials.encryption, credentials.server), options)
serverRun = launch { runCatching { server.run() } }
a
}
val running = async { runCatching { client.run() } }
val call = async { runCatching { client.call(commit, 9) } }
try {
client.awaitReady()
enteredCommand.await()
server.close()
assertTrue(call.await().isFailure)
running.await()
assertEquals(2, attempts)
assertEquals(1, executions)
} finally { client.close(); serverRun?.cancelAndJoin(); running.cancelAndJoin(); call.cancelAndJoin() }
}
}
@@ -0,0 +1,263 @@
@file:OptIn(ExperimentalUnsignedTypes::class, ExperimentalConcealedProtocol::class)
package net.sergeych.kiloparsec.concealed
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.test.runTest
import net.sergeych.crypto2.DecryptingSecretKey
import net.sergeych.crypto2.SigningSecretKey
import net.sergeych.crypto2.initCrypto
import net.sergeych.kiloparsec.*
import kotlin.test.*
import kotlin.time.Duration.Companion.seconds
class ConcealedConnectionTest {
private class MemoryCarrier(
override val kind: ConcealedCarrier.Kind,
private val incoming: Channel<UByteArray>,
private val outgoing: Channel<UByteArray>,
) : ConcealedCarrier {
var sent = 0
var dropFlight = -1
var duplicate = false
var noiseBeforeFlights: Set<Int> = emptySet()
var trickleData = false
var trickleBytesSent = 0
override suspend fun send(bytes: UByteArray) {
sent++
if (sent == dropFlight) return
if (kind == ConcealedCarrier.Kind.DATAGRAM) {
if (sent in noiseBeforeFlights) {
// Short junk cannot supply a header; the second packet keeps an authentic
// header but corrupts the separately authenticated body.
outgoing.send(ubyteArrayOf(9u, 8u, 7u))
outgoing.send(bytes.copyOf().also { it[it.lastIndex] = (it.last().toInt() xor 1).toUByte() })
}
outgoing.send(bytes.copyOf())
if (duplicate) outgoing.send(bytes.copyOf())
} else {
if (trickleData) {
// Twenty fragments at 100 ms intervals outlast a 1 s whole-record
// deadline, while each individual read remains within that deadline.
repeat(minOf(20, bytes.size)) { i ->
if (i != 0) delay(100)
outgoing.send(bytes.copyOfRange(i, i + 1))
trickleBytesSent++
}
awaitCancellation()
}
var position = 0
var step = 0
val sizes = intArrayOf(1, 3, 7, 64, 2, 127)
while (position < bytes.size) {
val end = minOf(bytes.size, position + sizes[step++ % sizes.size])
outgoing.send(bytes.copyOfRange(position, end))
position = end
}
}
}
override suspend fun receive(): UByteArray? = incoming.receiveCatching().getOrNull()
override suspend fun close() { incoming.close(); outgoing.close() }
}
private fun carriers(kind: ConcealedCarrier.Kind): Pair<MemoryCarrier, MemoryCarrier> {
val a = Channel<UByteArray>(64)
val b = Channel<UByteArray>(64)
return MemoryCarrier(kind, a, b) to MemoryCarrier(kind, b, a)
}
private class Credentials {
val serverEncryption = DecryptingSecretKey.new()
val serverSigning = SigningSecretKey.new()
val clientSigning = SigningSecretKey.new()
val serverIdentity = ConcealedServerIdentity(serverEncryption, serverSigning)
}
private val options = ConcealedOptions(padding = ConcealedOptions.Padding(0))
@Test fun segmentedStreamSupportsDeferredInitializationDuplexPushAndErrors() = runTest(timeout = 60.seconds) {
initCrypto()
val credentials = Credentials()
val (a, b) = carriers(ConcealedCarrier.Kind.STREAM)
val echo by command<Int, Int>()
val notify by command<Int, Unit>()
val fail by command<Int, Int>()
val notifications = Channel<Int>(16)
val initializedCall = CompletableDeferred<Int>()
val clientLocal = KiloInterface<Unit>().apply {
on(echo) { it + 100 }
on(notify) { notifications.send(it) }
onConnected {
assertEquals(credentials.serverSigning.verifyingKey, remoteIdentity)
val r = remote
launch { initializedCall.complete(r.call(echo, 12)) }
}
}
val serverLocal = KiloInterface<Unit>().apply {
on(echo) { it * 2 }
on(notify) { notifications.send(it) }
on(fail) { throw IllegalArgumentException("Expected remote failure") }
onConnected { assertEquals(credentials.clientSigning.verifyingKey, remoteIdentity) }
}
val client = ConcealedConnection.client(clientLocal, a, Unit, credentials.serverEncryption.publicKey,
credentials.serverSigning.verifyingKey, credentials.clientSigning, options)
val server = ConcealedConnection.server(serverLocal, b, Unit, credentials.serverIdentity, options)
val clientState = CompletableDeferred<Unit>()
val clientRun = async { runCatching { client.run { if (it) clientState.complete(Unit) } } }
val serverRun = async { runCatching { server.run() } }
val early = async { client.call(echo, 7) }
try {
clientState.await(); server.awaitReady()
assertEquals(14, early.await())
assertEquals(24, initializedCall.await())
assertContentEquals(client.token(), server.token())
assertEquals(credentials.clientSigning.verifyingKey, server.remoteId())
coroutineScope {
val requests = (0 until 8).map { i -> async { assertEquals(i * 2, client.call(echo, i)) } } +
(0 until 8).map { i -> async { assertEquals(i + 100, server.call(echo, i)) } }
requests.awaitAll()
}
client.push(notify, 31); server.push(notify, 47)
assertEquals(setOf(31, 47), setOf(notifications.receive(), notifications.receive()))
assertFailsWith<RemoteInterface.RemoteException> { client.call(fail, 1) }
assertEquals(18, client.call(echo, 9))
client.close()
withTimeout(2_000) { clientRun.await(); serverRun.await() }
} finally { client.close(); server.close(); clientRun.cancelAndJoin(); serverRun.cancelAndJoin() }
}
@Test fun udpLostAckAndAcceptanceRecoverAndDuplicatesDoNotRepeatRpc() = runTest(timeout = 60.seconds) {
initCrypto()
val credentials = Credentials()
val (a, b) = carriers(ConcealedCarrier.Kind.DATAGRAM)
// HELO/send1, ACK/send2; first client ACK and server acceptance are lost.
a.dropFlight = 2
b.dropFlight = 2
val echo by command<Int, Int>()
var executions = 0
val serverLocal = KiloInterface<Unit>().apply { on(echo) { executions++; it + 1 } }
val client = ConcealedConnection.client(KiloInterface<Unit>(), a, Unit, credentials.serverEncryption.publicKey,
credentials.serverSigning.verifyingKey, credentials.clientSigning, options)
val server = ConcealedConnection.server(serverLocal, b, Unit, credentials.serverIdentity, options)
val clientRun = async { runCatching { client.run() } }
val serverRun = async { runCatching { server.run() } }
try {
client.awaitReady(); server.awaitReady()
assertTrue(a.sent >= 4, "Lost ACK and lost acceptance each require an ACK retry")
a.duplicate = true; b.duplicate = true
assertEquals(43, client.call(echo, 42))
assertEquals(8, client.call(echo, 7))
assertEquals(2, executions)
assertTrue(clientRun.isActive); assertTrue(serverRun.isActive)
} finally { client.close(); server.close(); clientRun.cancelAndJoin(); serverRun.cancelAndJoin() }
}
@Test fun udpIgnoresUnauthenticatedNoiseAcrossAllReplyFlights() = runTest(timeout = 60.seconds) {
initCrypto()
val credentials = Credentials()
val (a, b) = carriers(ConcealedCarrier.Kind.DATAGRAM)
a.noiseBeforeFlights = setOf(2) // ACK
b.noiseBeforeFlights = setOf(1, 2) // server hello and acceptance
val echo by command<Int, Int>()
var executions = 0
val client = ConcealedConnection.client(KiloInterface<Unit>(), a, Unit, credentials.serverEncryption.publicKey,
credentials.serverSigning.verifyingKey, credentials.clientSigning, options)
val server = ConcealedConnection.server(KiloInterface<Unit>().apply { on(echo) { executions++; it } },
b, Unit, credentials.serverIdentity, options)
val clientRun = async { runCatching { client.run() } }
val serverRun = async { runCatching { server.run() } }
try {
client.awaitReady(); server.awaitReady()
assertEquals(51, client.call(echo, 51))
assertEquals(1, executions)
assertTrue(clientRun.isActive); assertTrue(serverRun.isActive)
assertNull(client.terminalFailure); assertNull(server.terminalFailure)
} finally { client.close(); server.close(); clientRun.cancelAndJoin(); serverRun.cancelAndJoin() }
}
@Test fun negotiatedStreamLimitRejectsOversizeLocallyAndKeepsConnectionUsable() = runTest(timeout = 60.seconds) {
initCrypto()
val credentials = Credentials()
val (a, b) = carriers(ConcealedCarrier.Kind.STREAM)
val echo by command<String, String>()
var executed = 0
val client = ConcealedConnection.client(KiloInterface<Unit>(), a, Unit, credentials.serverEncryption.publicKey,
credentials.serverSigning.verifyingKey, credentials.clientSigning, options)
val server = ConcealedConnection.server(KiloInterface<Unit>().apply { on(echo) { executed++; it } },
b, Unit, credentials.serverIdentity,
options.copy(limits = ConcealedOptions.Limits(maxBodyBytes = 256)))
val clientRun = async { runCatching { client.run() } }
val serverRun = async { runCatching { server.run() } }
try {
client.awaitReady(); server.awaitReady()
assertFailsWith<IllegalArgumentException> { client.call(echo, "x".repeat(1024)) }
assertEquals("small", client.call(echo, "small"))
assertEquals(1, executed)
assertTrue(clientRun.isActive); assertTrue(serverRun.isActive)
} finally { client.close(); server.close(); clientRun.cancelAndJoin(); serverRun.cancelAndJoin() }
}
@Test fun slowTrickleDoesNotRestartAbsolutePartialRecordDeadline() = runTest(timeout = 60.seconds) {
initCrypto()
val credentials = Credentials()
val (a, b) = carriers(ConcealedCarrier.Kind.STREAM)
val echo by command<Int, Int>()
var executed = 0
val client = ConcealedConnection.client(KiloInterface<Unit>(), a, Unit, credentials.serverEncryption.publicKey,
credentials.serverSigning.verifyingKey, credentials.clientSigning, options)
val server = ConcealedConnection.server(KiloInterface<Unit>().apply { on(echo) { executed++; it } },
b, Unit, credentials.serverIdentity,
options.copy(limits = ConcealedOptions.Limits(partialRecordTimeoutMillis = 1_000)))
// Connection jobs use real timers because production measures Monotonic elapsed time;
// virtual test-scheduler time cannot advance that clock. Count progress, not a tight
// wall-clock duration, so the test distinguishes a reset-on-every-read implementation.
val clientRun = async(Dispatchers.Default) { runCatching { client.run() } }
val serverRun = async(Dispatchers.Default) { runCatching { server.run() } }
var call: Deferred<Result<Int>>? = null
try {
client.awaitReady(); server.awaitReady()
a.trickleData = true
val pendingCall = async(Dispatchers.Default) { runCatching { client.call(echo, 1) } }
call = pendingCall
withContext(Dispatchers.Default) {
withTimeout(5_000) {
serverRun.await()
clientRun.await()
assertTrue(pendingCall.await().isFailure)
}
}
assertEquals(0, executed, "Unauthenticated partial objects must not reach dispatch")
assertTrue(a.trickleBytesSent in 1 until 20,
"Whole-record deadline must expire while fragments continue arriving; sent ${a.trickleBytesSent}")
} finally {
client.close(); server.close()
call?.cancelAndJoin(); clientRun.cancelAndJoin(); serverRun.cancelAndJoin()
}
}
@Test fun policyRejectionOnEitherEndFailsQueuedCallsWithoutDispatch() = runTest(timeout = 60.seconds) {
initCrypto()
for (rejectServer in listOf(true, false)) {
val credentials = Credentials()
val (a, b) = carriers(ConcealedCarrier.Kind.STREAM)
val echo by command<Int, Int>()
var executed = 0
var announced = false
val rejection = LocalInterface.BreakConnectionException("Policy rejected")
val clientLocal = KiloInterface<Unit>()
val serverLocal = KiloInterface<Unit>().apply { on(echo) { executed++; it } }
(if (rejectServer) serverLocal else clientLocal).onConnected { throw rejection }
val client = ConcealedConnection.client(clientLocal, a, Unit, credentials.serverEncryption.publicKey,
credentials.serverSigning.verifyingKey, credentials.clientSigning, options)
val server = ConcealedConnection.server(serverLocal, b, Unit, credentials.serverIdentity, options)
val queued = async { runCatching { client.call(echo, 5) } }
val clientRun = async { runCatching { client.run { if (it) announced = true } } }
val serverRun = async { runCatching { server.run() } }
try {
assertTrue(queued.await().isFailure)
withTimeout(2_000) { clientRun.await(); serverRun.await() }
assertFalse(announced)
assertEquals(0, executed)
if (!rejectServer) assertSame(rejection, clientRun.await().exceptionOrNull())
} finally { client.close(); server.close(); clientRun.cancelAndJoin(); serverRun.cancelAndJoin() }
}
}
}
@@ -0,0 +1,125 @@
@file:OptIn(ExperimentalUnsignedTypes::class, ExperimentalConcealedProtocol::class)
package net.sergeych.kiloparsec.concealed
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.test.runTest
import net.sergeych.crypto2.DecryptingSecretKey
import net.sergeych.crypto2.SigningSecretKey
import net.sergeych.crypto2.initCrypto
import net.sergeych.kiloparsec.concealed.handshake.*
import kotlin.test.*
class HelloFailureNoiseTest {
private val seed get() = UByteArray(32) { (it + 11).toUByte() }
private fun noise() = HelloFailureNoise(seed) { UByteArray(it) { 255u } }
@Test fun onlyEnvelopeAuthenticationFailureTriggersExactlyOneDiscardedAttempt() {
val noise = noise()
var calls = 0
assertEquals(42, noise.run({ 42 }) { calls++ })
assertEquals(0, calls)
val malformed = HandshakeFailure("Invalid length or low-order DH")
assertSame(malformed, assertFailsWith<HandshakeFailure> { noise.run({ throw malformed }) { calls++ } })
assertEquals(0, calls)
val original = UnauthenticatedFlight()
assertSame(original, assertFailsWith<UnauthenticatedFlight> { noise.run({ throw original }) { calls++ } })
assertEquals(1, calls) // A successful dummy result never becomes a real accepted result.
}
@Test fun mutatesOnlyEffectiveDistinctBitsAndErasesTemporaryCopy() {
val originalSeed = seed
val snapshot = originalSeed.copyOf()
val noise = HelloFailureNoise(originalSeed) { UByteArray(it) { 255u } }
var retained: UByteArray? = null
var mutated: UByteArray? = null
assertFailsWith<UnauthenticatedFlight> {
noise.run({ throw UnauthenticatedFlight() }) { retained = it; mutated = it.copyOf() }
}
val changed = (0..255).filter { bit ->
((snapshot[bit / 8].toInt() xor mutated!![bit / 8].toInt()) and (1 shl (bit % 8))) != 0
}
assertEquals(8, changed.size)
assertTrue(changed.all { it in 3..253 })
assertContentEquals(snapshot, originalSeed)
assertTrue(retained!!.all { it == 0u.toUByte() })
}
@Test fun expectedDummyFailurePreservesOriginalButCancellationAndRuntimeErrorsPropagate() {
val noise = noise()
val original = UnauthenticatedFlight()
assertSame(original, assertFailsWith<UnauthenticatedFlight> {
noise.run({ throw original }) { throw HandshakeFailure("Dummy rejected") }
})
val cancelled = CancellationException("Cancelled")
assertSame(cancelled, assertFailsWith<CancellationException> {
noise.run({ throw original }) { throw cancelled }
})
val bug = IllegalStateException("Unexpected failure")
assertSame(bug, assertFailsWith<IllegalStateException> {
noise.run({ throw original }) { throw bug }
})
val fatal = object : Error("Fatal") {}
assertSame(fatal, assertFailsWith<Error> { noise.run({ throw original }) { throw fatal } })
}
@Test fun concurrentFailuresKeepSeedImmutableAndCopiesIndependent() = runTest {
val noise = noise()
val mutations = (0 until 24).map {
async(Dispatchers.Default) {
var mutation: UByteArray? = null
var retained: UByteArray? = null
assertFailsWith<UnauthenticatedFlight> {
noise.run({ throw UnauthenticatedFlight() }) { key ->
mutation = key.copyOf(); retained = key
}
}
assertTrue(retained!!.all { it == 0u.toUByte() })
mutation!!
}
}.awaitAll()
mutations.forEach { assertContentEquals(mutations.first(), it) }
assertFalse(mutations.first().contentEquals(seed))
}
@Test fun actualHeaderAndBodyFailuresUseDecoyWithoutMutatingRealKeyOrAccepting() = runTest {
initCrypto()
val encryption = DecryptingSecretKey.new()
val signing = SigningSecretKey.new()
val identity = ConcealedServerIdentity(encryption, signing)
val options = ConcealedOptions(padding = ConcealedOptions.Padding(0))
val client = ClientHandshake(encryption.publicKey.keyBytes, signing.verifyingKey,
SigningSecretKey.new(), ConcealedCarrier.Kind.STREAM, options)
val hello = client.hello
val realKey = encryption.keyBytes.copyOf()
val maximum = options.limits.maxBootstrapBytes
val prefix = hello.copyOfRange(0, 76)
assertEquals(hello.size, identity.helloAuthentication(prefix, maximum, true, true) {
ServerHandshake.helloSize(prefix, encryption.keyBytes, maximum)
})
for (enabled in listOf(false, true)) {
val badHeader = prefix.copyOf().also { it[75] = (it[75].toInt() xor 1).toUByte() }
assertFailsWith<UnauthenticatedFlight> {
identity.helloAuthentication(badHeader, maximum, true, enabled) {
ServerHandshake.helloSize(badHeader, encryption.keyBytes, maximum)
}
}
val badBody = hello.copyOf().also { it[it.lastIndex] = (it.last().toInt() xor 1).toUByte() }
assertFailsWith<UnauthenticatedFlight> {
identity.helloAuthentication(badBody, maximum, false, enabled) {
ServerHandshake(encryption.keyBytes, signing, ConcealedCarrier.Kind.STREAM, options, badBody)
}
}
}
assertContentEquals(realKey, encryption.keyBytes)
// Original unmodified HELO still establishes the usual authenticated server response.
val server = identity.helloAuthentication(hello, maximum, false, true) {
ServerHandshake(encryption.keyBytes, signing, ConcealedCarrier.Kind.STREAM, options, hello)
}
try { assertTrue(client.receiveServerHello(server.response).isNotEmpty()) }
finally { client.destroy(); server.destroy() }
}
}
@@ -0,0 +1,84 @@
package net.sergeych.kiloparsec.concealed.elligator
// Independent reference vectors, retrieved 2026-10-22 from https://elligator.org/vectors/.
// Direct vectors retain r and u (v is not used by X25519); failed inverse vectors use an empty result.
internal object ElligatorReferenceVectors {
val direct = listOf(
Pair("0000000000000000000000000000000000000000000000000000000000000000", "0000000000000000000000000000000000000000000000000000000000000000"),
Pair("66665895c5bc6e44ba8d65fd9307092e3244bf2c18877832bd568cb3a2d38a12", "04d44290d13100b2c25290c9343d70c12ed4813487a07ac1176daa5925e7975e"),
Pair("673a505e107189ee54ca93310ac42e4545e9e59050aaac6f8b5f64295c8ec02f", "242ae39ef158ed60f20b89396d7d7eef5374aba15dc312a6aea6d1e57cacf85e"),
Pair("990b30e04e1c3620b4162b91a33429bddb9f1b70f1da6e5f76385ed3f98ab131", "998e98021eb4ee653effaa992f3fae4b834de777a953271baaa1fa3fef6b776e"),
Pair("341a60725b482dd0de2e25a585b208433044bc0a1ba762442df3a0e888ca063c", "683a71d7fca4fc6ad3d4690108be808c2e50a5af3174486741d0a83af52aeb01"),
Pair("922688fa428d42bc1fa8806998fbc5959ae801817e85a42a45e8ec25a0d7541a", "696f341266c64bcfa7afa834f8c34b2730be11c932e08474d1a22f26ed82410b"),
Pair("0d3b0eb88b74ed13d5f6a130e03c4ad607817057dc227152827c0506a538bb3a", "0b00df174d9fb0b6ee584d2cf05613130bad18875268c38b377e86dfefef177f"),
Pair("01a3ea5658f4e00622eeacf724e0bd82068992fae66ed2b04a8599be16662e35", "7ae4c58bc647b5646c9f5ae4c2554ccbf7c6e428e7b242a574a5a9c293c21f7e"),
Pair("1d991dff82a84afe97874c0f03a60a56616a15212fbe10d6c099aa3afcfabe35", "f81f235696f81df90ac2fc861ceee517bff611a394b5be5faaee45584642fb0a"),
Pair("185435d2b005a3b63f3187e64a1ef3582533e1958d30e4e4747b4d1d3376c728", "f938b1b320abb0635930bd5d7ced45ae97fa8b5f71cc21d87b4c60905c125d34"),
Pair("b98d026c2a247fd113596f4317d8ff9f89f172c4be46320a5e82f579b953b633", "19f98122afbd38dd5b97afc07fe89c00d9d45834a25ae851e527e34a5e763c07"),
Pair("69599ab5a829c3e9515128d368da7354a8b69fcee4e34d0a668b783b6cae550f", "09024abaaef243e3b69366397e8dfc1fdc14a0ecc7cf497cbe4f328839acce69"),
Pair("409f76202dcc3280d14a9bc87b5f474349bbb6325e92733e0feee571a7f2462a", "16235355f04bef29019ec6903788b9ee56214d1fdb60ddcc9f9bdc2816a3b132"),
Pair("9172922f96d2fa41ea0daf961857056f1656ab8406db80eaeae76af58f8c9f10", "beab745a2a4b4e7f1a7335c3ffcdbd85139f3a72b667a01ee3e3ae0e530b3372"),
Pair("6850a20ac5b6d2fa7af7042ad5be234d3311b9fb303753dd2b610bd566983201", "1287388eb2beeff706edb9cf4fcfdd35757f22541b61528570b86e8915be1530"),
Pair("84417826c0e80af7cb25a73af1ba87594ff7048a26248b5757e52f2824e06831", "51acd2e8910e7d28b4993db7e97e2b995005f26736f60dcdde94bdf8cb542251"),
)
val inverse = listOf(
Triple("0000000000000000000000000000000000000000000000000000000000000000", "0", "0000000000000000000000000000000000000000000000000000000000000000"),
Triple("01a3ea5658f4e00622eeacf724e0bd82068992fae66ed2b04a8599be16662e35", "0", ""),
Triple("01a3ea5658f4e00622eeacf724e0bd82068992fae66ed2b04a8599be16662e35", "1", ""),
Triple("f569bb6b6ac92fecbd0ed9f37055c08c7eb49b3325eb415d4cc5d3c44a27d854", "0", ""),
Triple("f569bb6b6ac92fecbd0ed9f37055c08c7eb49b3325eb415d4cc5d3c44a27d854", "1", ""),
Triple("2af3d4b274cb8f1eafe97a8e78155026b0e97d14844fb17e67463a2a159a3d72", "0", ""),
Triple("2af3d4b274cb8f1eafe97a8e78155026b0e97d14844fb17e67463a2a159a3d72", "1", ""),
Triple("94268b1888c4a743c5a25281a68701c01fabf8676002ed1079255bcad7b42f60", "0", ""),
Triple("94268b1888c4a743c5a25281a68701c01fabf8676002ed1079255bcad7b42f60", "1", ""),
Triple("808afb062244775fe768995402c10b2dcffb0f65b8ba872dc659902da89d2b49", "0", ""),
Triple("808afb062244775fe768995402c10b2dcffb0f65b8ba872dc659902da89d2b49", "1", ""),
Triple("727b81b1455f79c59077c6abeb4b38e4b98b63cce8e5270f1b2d8b42789b7b63", "0", ""),
Triple("727b81b1455f79c59077c6abeb4b38e4b98b63cce8e5270f1b2d8b42789b7b63", "1", ""),
Triple("97350b0977d06146bd7609bfadc8af713d3c97af2929625e44ccdb66791c5427", "0", ""),
Triple("97350b0977d06146bd7609bfadc8af713d3c97af2929625e44ccdb66791c5427", "1", ""),
Triple("f85393caffdd45ff11884d57a11d636497d2c051bfddd1dd2daa720a3ad0e41e", "0", ""),
Triple("f85393caffdd45ff11884d57a11d636497d2c051bfddd1dd2daa720a3ad0e41e", "1", ""),
Triple("0d281e20ec2e3561a20ebc908c1c5e9ffb1f850e597ffc91c8861d1c57ef3a3e", "0", ""),
Triple("0d281e20ec2e3561a20ebc908c1c5e9ffb1f850e597ffc91c8861d1c57ef3a3e", "1", ""),
Triple("c68d4ceead9a188d00ddcda391c5c036ecd5cd281f243aacaa327bbbf3384c3a", "0", ""),
Triple("c68d4ceead9a188d00ddcda391c5c036ecd5cd281f243aacaa327bbbf3384c3a", "1", ""),
Triple("120d71dd9fc64bd6e2fcf8e96a9d22817f2dc31b314ba484f87cb6073af5a541", "0", ""),
Triple("120d71dd9fc64bd6e2fcf8e96a9d22817f2dc31b314ba484f87cb6073af5a541", "1", ""),
Triple("621744f808a1b0eb252c85628e06214319260092f1d17ce1c509e1a250308063", "0", ""),
Triple("621744f808a1b0eb252c85628e06214319260092f1d17ce1c509e1a250308063", "1", ""),
Triple("918348cc15950e2d21940da1f6f26e0111ac3a84af976fbb85d872b8d3375d23", "0", ""),
Triple("918348cc15950e2d21940da1f6f26e0111ac3a84af976fbb85d872b8d3375d23", "1", ""),
Triple("ca4e9d3319c955caf99827a0dce25d4d3d21330740c024bab3a1cf65dda8fa2e", "0", ""),
Triple("ca4e9d3319c955caf99827a0dce25d4d3d21330740c024bab3a1cf65dda8fa2e", "1", ""),
Triple("230eca35f689c16da6bcb0641863eaebcf05a5aeba5abf94c88ccb66f7953e65", "0", ""),
Triple("230eca35f689c16da6bcb0641863eaebcf05a5aeba5abf94c88ccb66f7953e65", "1", ""),
Triple("7a6685fd00c9ac478ae4878017ef4f4816dc8489f5fbb8122af687a8c7fc173d", "0", ""),
Triple("7a6685fd00c9ac478ae4878017ef4f4816dc8489f5fbb8122af687a8c7fc173d", "1", ""),
Triple("fd6fa7f8d40e82d9cdcbb2b3d137887b639db5eaeb1e20a6651e9e288c6b1d73", "0", "bdf0babcc57bfce100e81ddc84f92d5021c4065e2457a4adaa2916bffa16ca16"),
Triple("fd6fa7f8d40e82d9cdcbb2b3d137887b639db5eaeb1e20a6651e9e288c6b1d73", "1", "b0986f7934908cec837208e9cb94182b1ea5cd24875c02c409e9892ea48ecf0b"),
Triple("230030447df3d9a9634091503eb94ee39737a8690c3f61bb122c7264bc00083d", "0", "905c2d8787d2c9ab775aac1ab7e0c51e5363e0d7b5915a899dfff5d889b5c410"),
Triple("230030447df3d9a9634091503eb94ee39737a8690c3f61bb122c7264bc00083d", "1", "161db55c3b12ac9087d3c3c94e598896dc9ed792900172aac450b41d5177ab3f"),
Triple("d298c05fd81f21dd1c27a2b0d75089d50ed25a91d42a7cd3a4b86de6f5f43a26", "0", "d1f6409bda55a0851c23085de23054af757fb89955da242b1a1e96c27180653d"),
Triple("d298c05fd81f21dd1c27a2b0d75089d50ed25a91d42a7cd3a4b86de6f5f43a26", "1", "ce9e93b505f84992fe84a0b171bc9b4e4ec876221b807811f343784478d76b19"),
Triple("9b9e4dc144e41a5e0ff2123b6601d26828b301fa70afc778c49fb5399d44f04e", "0", "c16580d060e3856894abf4c7a166e0812ab79e6df00e53662182febd37901704"),
)
val scalar = listOf(
Pair("8099a76a3a4391bb45729a026cf8f6d1cdbb40d3e77887cd42a9734cba58eada", "d39fbbfc405a199815f9fe0b9746e5486197058b4cfafde734be3194686d8c0f"),
Pair("49e9d46e5ccbd6422460e48f0e2591a089c7a12c0cea9c9cb9e59f8da4b7d22f", "d053808acf4da6f20220b6b863e321b66ec0c43e35b41a359fdcf35cd8059653"),
Pair("9ae801817e85a42a45e8ec2541afa9340d3b0eb88b74ed13d5f6a130e03c4ad6", "609ba8ccc80db0270cc27ab1e45e36c316f72864e9ae2e8b8642ec0f714f4f48"),
Pair("ab29c3e9515128d368da7354a8b69fcee4e34d0a668b783bd85cab1ead6089df", "cda87a924c2ddc705f6b7a7149437d635357912f9e78c66fc10d68720d56c131"),
Pair("1c57056f1656ab8406db80eaeae76af51f193f216850a20ac5b6d2fa7af7042a", "85f6bfaa7cebf45110460a49f4780483b7dd30fac0c0a1c0a66731386e369d38"),
Pair("25248b5757e52f2849c0d162b0fbe152849f49034d2fa00ccc7b960fad7b30b6", "9f122d2a60ff9e6f0535c795c1f4b49896ff3790e479ee3a81bdbbdfe5406c25"),
Pair("161bc00f4e8f8903225948a02d00e67dc70f65536dffa0c516cc2e9cecd94ff7", "70c74173fc142fab7964ae7f7745a19941f5866efef44a65ce9db90f14e3e61b"),
Pair("6fc92fecbd0ed9f37055c08c7eb49b3325eb415d4cc5d3c4954eb0a92af3d4b2", "f48c70397977d0497db6a5743824264ee1b7297bc277b34b6c1d52d08c0fa124"),
Pair("a8e97a8e78155026b0e97d14844fb17e67463a2a2b347be4a0ca9ff75afae655", "aacd264dc444edcf628ea4292761934eabcd758a1fedcb23bcf3d9076ad5b355"),
Pair("711c0eefb61268cc99aac1d994268b1888c4a743c5a25281a68701c01fabf867", "68a6ae56f0c632089760076681c98bd9f4feb6f6510507aa8b22f40e1cc9c501"),
Pair("92560e9f24733c921b06af336543c8bf370c9122ba24ed87e7a2dae487a2b53b", "012969335b29c682b6de162ba7e86154512c7aeeb828b776bb2fc6e3d3578d5a"),
Pair("cb7164b5fabb82a297350b0977d06146bd7609bfadc8af713d3c97af2929625e", "e44c139d516b3874c289f83d513b33d267c8d03d9c0990ff19fd9ca4e84ced53"),
Pair("f438a84e4de3fc72e672419c49d5ab43c350d54f1b85babc2efe147ebed9fb7a", "634fa5f71b3573833ec9721c435b9f8558cc933acd4afeb309387e75fbd31518"),
Pair("758ad64ce74eb3b940dab7502492a6d8813466639de65213b5fee99d5f12044d", "ebe1131ab10943be9938973314ca29e37f65102a908c8d76907af64c72e2a234"),
Pair("564295833f191208f85393caffdd45ff11884d57a11d636497d2c051bfddd1dd", "e1dae044dada772b295c2fab6826c78acfba49f6956b48b165f91d8e1888cb31"),
Pair("a770e05be3fb8b289b524cfa730bc2bd3a6ebb487036bb097e2235db4f6b17df", "9f135038101b6d809fbd4fb047362049189089d5ace38a0243175d5b5aabde1b"),
)
}
@@ -0,0 +1,105 @@
@file:OptIn(ExperimentalUnsignedTypes::class)
package net.sergeych.kiloparsec.concealed.elligator
import com.ionspin.kotlin.crypto.util.LibsodiumRandom
import kotlin.math.ceil
import kotlin.math.sqrt
import kotlin.random.Random
import kotlin.time.TimeSource
/** Opt-in diagnostic, not a statistical proof of constant-time execution. No key bytes are emitted. */
internal object ElligatorTimingProbe {
private var sink = 0
private data class Sample(val group: String, val nanos: Long, val attempts: Int = 0)
fun run(count: Int, warmup: Int, metadata: String): String {
require(count in 16..100_000 && warmup in 0..10_000)
val rng = Random(237404)
val samples = mutableListOf<Sample>()
val publicRandom = List(count.coerceAtLeast(warmup).coerceAtLeast(16)) {
UByteArray(32) { rng.nextInt(256).toUByte() }
}
fun measured(group: String, record: Boolean, action: () -> Unit) {
val start = TimeSource.Monotonic.markNow()
action()
val ns = start.elapsedNow().inWholeNanoseconds
if (record) samples += Sample(group, ns)
}
fun consume(value: UByteArray?) { if (value != null) sink = sink xor value[0].toInt() }
val valid = ElligatorReferenceVectors.inverse.filter { it.third.isNotEmpty() && !it.first.all { c -> c == '0' } }
val invalid = ElligatorReferenceVectors.inverse.filter { it.third.isEmpty() }
fun hex(s: String) = s.chunked(2).map { it.toInt(16).toUByte() }.toUByteArray()
val validInputs = valid.map { hex(it.first) to it.second.toInt() }
val invalidInputs = invalid.map { hex(it.first) to it.second.toInt() }
// Interleave randomized class order each round to reduce monotonic JIT/thermal drift.
repeat(warmup + count) { round ->
val record = round >= warmup
val index = round % publicRandom.size
val secret = publicRandom[index].copyOf()
val torsionInputs = (0..7).map { low -> secret.copyOf().also { it[0] = ((it[0].toInt() and 248) or low).toUByte() } }
val randomRep = publicRandom[index]
val paddedRep = randomRep.copyOf().also { it[31] = (it[31].toInt() or 192).toUByte() }
val jobs = mutableListOf<Pair<String, () -> Unit>>()
jobs += "decode.zero" to { consume(ExperimentalElligator25519.decode(UByteArray(32))) }
jobs += "decode.random" to { consume(ExperimentalElligator25519.decode(randomRep)) }
jobs += "decode.same-random-high-bits" to { consume(ExperimentalElligator25519.decode(paddedRep)) }
for (low in 0..7) jobs += "special.torsion-$low" to { consume(ExperimentalElligator25519.specialPublicKey(torsionInputs[low])) }
val good = validInputs[round % validInputs.size]
val bad = invalidInputs[round % invalidInputs.size]
jobs += "encode.representable" to { consume(ExperimentalElligator25519.encode(good.first, good.second)) }
jobs += "encode.unrepresentable" to { consume(ExperimentalElligator25519.encode(bad.first, bad.second)) }
jobs += "generate.actual" to {
val pair = ExperimentalElligator25519.generateKeyPair()
consume(pair.representative)
pair.destroy()
}
for ((name, job) in jobs.shuffled(rng)) measured(name, record, job)
torsionInputs.forEach { it.fill(0u) }
secret.fill(0u)
}
// Instrumented equivalent loop exposes rejection counts without changing production code.
repeat(count) {
var attempts = 0
val start = TimeSource.Monotonic.markNow()
while (true) {
attempts++
val secret = LibsodiumRandom.buf(32)
val encoded = try {
ExperimentalElligator25519.encode(ExperimentalElligator25519.specialPublicKey(secret), LibsodiumRandom.buf(1)[0].toInt())
} finally { secret.fill(0u) }
if (encoded != null) { consume(encoded); break }
}
samples += Sample("generate.instrumented", start.elapsedNow().inWholeNanoseconds, attempts)
}
publicRandom.forEach { it.fill(0u) }
val groups = samples.groupBy { it.group }
fun mean(values: List<Sample>) = values.map { it.nanos.toDouble() }.average()
fun variance(values: List<Sample>): Double {
val m = mean(values)
return values.sumOf { (it.nanos - m) * (it.nanos - m) } / (values.size - 1)
}
fun welch(a: List<Sample>, b: List<Sample>): Double =
(mean(a) - mean(b)) / sqrt(variance(a) / a.size + variance(b) / b.size)
return buildString {
appendLine("Elligator timing diagnostic; $metadata")
appendLine("seed=237404 samples-per-class=$count warmup-rounds=$warmup clock=TimeSource.Monotonic units=ns sink=$sink")
appendLine("Classes: decode inputs are PUBLIC (zero is pathological); paired high-bit inputs decode identically. special classes share the same clamped scalar each round and differ only in low 3 secret torsion bits. encode classes intentionally compare observable success/failure control flow. generate includes fresh synthetic randomness and rejection tails.")
appendLine("Interpretation: exploratory Welch t only, no p-value/constant-time claim; unequal inputs, autocorrelation, GC/JIT, scheduler noise and multiple comparisons remain. Synthetic keys only; key bytes omitted.")
appendLine("group,n,mean_ns,median_ns,p95_ns,p99_ns,max_ns")
groups.forEach { (name, data) ->
val ordered = data.map { it.nanos }.sorted()
fun q(f: Double) = ordered[(ceil(f * ordered.size).toInt() - 1).coerceIn(0, ordered.lastIndex)]
appendLine("$name,${data.size},${mean(data)},${q(0.5)},${q(0.95)},${q(0.99)},${ordered.last()}")
}
appendLine("welch_group_a,welch_group_b,t")
for (i in 1..7) appendLine("special.torsion-0,special.torsion-$i,${welch(groups.getValue("special.torsion-0"), groups.getValue("special.torsion-$i"))}")
appendLine("encode.representable,encode.unrepresentable,${welch(groups.getValue("encode.representable"), groups.getValue("encode.unrepresentable"))}")
appendLine("decode.random,decode.same-random-high-bits,${welch(groups.getValue("decode.random"), groups.getValue("decode.same-random-high-bits"))}")
appendLine("attempts,count")
groups.getValue("generate.instrumented").groupingBy { it.attempts }.eachCount().entries.sortedBy { it.key }.forEach { (a, n) -> appendLine("$a,$n") }
appendLine("raw_group,nanos,attempts")
samples.forEach { appendLine("${it.group},${it.nanos},${it.attempts}") }
}
}
}
@@ -0,0 +1,84 @@
@file:OptIn(ExperimentalUnsignedTypes::class)
package net.sergeych.kiloparsec.concealed.elligator
import com.ionspin.kotlin.crypto.scalarmult.ScalarMultiplication
import com.ionspin.kotlin.crypto.util.LibsodiumRandom
import kotlinx.coroutines.test.runTest
import net.sergeych.crypto2.initCrypto
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.time.Duration.Companion.seconds
class ExperimentalElligator25519Test {
@Test fun independentDirectVectors() {
ElligatorReferenceVectors.direct.forEach { (representative, expected) ->
val bytes = hex(representative)
for (padding in listOf(0, 64, 128, 192)) {
bytes[31] = ((bytes[31].toInt() and 63) or padding).toUByte()
assertContentEquals(hex(expected), ExperimentalElligator25519.decode(bytes))
}
}
}
@Test fun independentInverseVectors() {
ElligatorReferenceVectors.inverse.forEach { (publicKey, sign, expected) ->
val encoded = ExperimentalElligator25519.encode(hex(publicKey), sign.toInt())
if (expected.isEmpty()) assertNull(encoded) else {
assertContentEquals(hex(expected), encoded)
assertContentEquals(hex(publicKey), ExperimentalElligator25519.decode(assertNotNull(encoded)))
}
}
}
@Test fun independentFullCurveMultiplicationVectors() = runTest(timeout = 60.seconds) {
initCrypto()
ElligatorReferenceVectors.scalar.forEach { (secret, expected) ->
assertContentEquals(hex(expected), ExperimentalElligator25519.specialPublicKey(hex(secret)))
}
}
@Test fun agreementWithUnmodifiedLibsodiumAndAllTorsionComponents() = runTest(timeout = 60.seconds) {
initCrypto()
val serverSecret = LibsodiumRandom.buf(32)
val serverPublic = ScalarMultiplication.scalarMultiplicationBase(serverSecret)
val secret = LibsodiumRandom.buf(32)
val normalPublic = ScalarMultiplication.scalarMultiplicationBase(secret)
val expected = ScalarMultiplication.scalarMultiplication(serverSecret, normalPublic)
for (lowBits in 0..7) {
secret[0] = ((secret[0].toInt() and 248) or lowBits).toUByte()
val fullPublic = ExperimentalElligator25519.specialPublicKey(secret)
assertContentEquals(expected, ScalarMultiplication.scalarMultiplication(serverSecret, fullPublic))
assertContentEquals(expected, ScalarMultiplication.scalarMultiplication(secret, serverPublic))
}
repeat(8) {
val pair = ExperimentalElligator25519.generateKeyPair()
val decoded = ExperimentalElligator25519.decode(pair.representative)
assertContentEquals(
ScalarMultiplication.scalarMultiplication(serverSecret, decoded),
ScalarMultiplication.scalarMultiplication(pair.secretKey, serverPublic)
)
pair.destroy()
assertEquals(true, pair.secretKey.all { it == 0.toUByte() })
}
}
@Test fun lengthsAndLowOrderRepresentative() = runTest {
initCrypto()
for (length in listOf(0, 31, 33)) {
assertFailsWith<IllegalArgumentException> { ExperimentalElligator25519.decode(UByteArray(length)) }
assertFailsWith<IllegalArgumentException> { ExperimentalElligator25519.encode(UByteArray(length), 0) }
assertFailsWith<IllegalArgumentException> { ExperimentalElligator25519.specialPublicKey(UByteArray(length)) }
}
val zero = ExperimentalElligator25519.decode(UByteArray(32))
assertContentEquals(UByteArray(32), zero)
// Mapping is total; agreement must reject low-order points, not silently derive a key.
kotlin.test.assertFails { ScalarMultiplication.scalarMultiplication(LibsodiumRandom.buf(32), zero) }
}
private fun hex(value: String) = value.chunked(2).map { it.toInt(16).toUByte() }.toUByteArray()
}
@@ -0,0 +1,150 @@
@file:OptIn(ExperimentalUnsignedTypes::class, net.sergeych.kiloparsec.concealed.ExperimentalConcealedProtocol::class)
package net.sergeych.kiloparsec.concealed.handshake
import com.ionspin.kotlin.crypto.scalarmult.ScalarMultiplication
import com.ionspin.kotlin.crypto.util.LibsodiumRandom
import kotlinx.coroutines.test.runTest
import net.sergeych.crypto2.SigningKey
import net.sergeych.crypto2.SigningSecretKey
import net.sergeych.crypto2.initCrypto
import net.sergeych.kiloparsec.concealed.ConcealedCarrier
import net.sergeych.kiloparsec.concealed.ConcealedOptions
import kotlin.test.*
import kotlin.time.Duration.Companion.seconds
class ConcealedHandshakeTest {
private val options = ConcealedOptions(padding = ConcealedOptions.Padding(0))
private class Credentials {
val secret = LibsodiumRandom.buf(32)
val public = ScalarMultiplication.scalarMultiplicationBase(secret)
val server = SigningSecretKey.new()
val client = SigningSecretKey.new()
}
private fun Credentials.attempt(kind: ConcealedCarrier.Kind = ConcealedCarrier.Kind.STREAM): Pair<ClientHandshake, ServerHandshake> {
val c = ClientHandshake(public, server.verifyingKey, client, kind, options)
val s = ServerHandshake(secret, server, kind, options, c.hello)
return c to s
}
@Test fun allFourFlightsKeysTokenAndPeerIdentities() = runTest(timeout = 60.seconds) {
initCrypto()
val creds = Credentials()
for (kind in ConcealedCarrier.Kind.entries) {
val (client, server) = creds.attempt(kind)
assertEquals(176, client.hello.size)
assertEquals(client.hello.size, ServerHandshake.helloSize(client.hello.copyOfRange(0, 76), creds.secret))
assertEquals(240, server.response.size)
assertEquals(server.response.size, client.serverHelloSize(server.response.copyOfRange(0, 44)))
assertFails { server.accept() }
val ack = client.receiveServerHello(server.response)
assertEquals(197, ack.size)
assertEquals(ack.size, server.ackSize(ack.copyOfRange(0, 44)))
assertEquals(creds.client.verifyingKey, server.verifyAck(ack))
val acceptance = server.accept()
assertEquals(101, acceptance.size)
assertEquals(acceptance.size, client.acceptanceSize(acceptance.copyOfRange(0, 44)))
val session = client.receiveAcceptance(acceptance)
assertEquals(creds.server.verifyingKey, session.peerIdentity)
assertEquals(creds.client.verifyingKey, server.session.peerIdentity)
assertContentEquals(session.token, server.session.token)
assertContentEquals(session.sending.streamKey, server.session.receiving.streamKey)
assertContentEquals(session.sending.streamSalt, server.session.receiving.streamSalt)
assertContentEquals(session.sending.macKey, server.session.receiving.macKey)
assertContentEquals(session.sending.udpKey, server.session.receiving.udpKey)
assertContentEquals(session.receiving.udpKey, server.session.sending.udpKey)
assertFalse(session.receiving.udpKey.contentEquals(session.sending.udpKey))
assertFails { server.verifyAck(ack) }
assertFails { client.receiveAcceptance(acceptance) }
}
}
@Test fun eachAttemptIsFreshAndOldAckCannotAuthenticateNewAttempt() = runTest(timeout = 60.seconds) {
initCrypto()
val creds = Credentials()
val (c1, s1) = creds.attempt()
val ack1 = c1.receiveServerHello(s1.response)
s1.verifyAck(ack1)
val session1 = c1.receiveAcceptance(s1.accept())
val (c2, s2) = creds.attempt()
assertFalse(c1.hello.contentEquals(c2.hello))
val ack2 = c2.receiveServerHello(s2.response)
assertFailsWith<UnauthenticatedFlight> { s2.verifyAck(ack1) }
// Unauthenticated injection/replay cannot consume a valid pending UDP attempt.
s2.verifyAck(ack2)
c2.receiveAcceptance(s2.accept())
val (c3, s3) = creds.attempt()
s3.verifyAck(c3.receiveServerHello(s3.response))
val session3 = c3.receiveAcceptance(s3.accept())
assertFalse(session1.token.contentEquals(session3.token))
assertFalse(session1.sending.udpKey.contentEquals(session3.sending.udpKey))
}
@Test fun alteredRepresentativeAliasAndWrongStaticServerKeyFail() = runTest(timeout = 60.seconds) {
initCrypto()
val creds = Credentials()
val (c, _) = creds.attempt()
val alias = c.hello.copyOf()
alias[31] = (alias[31].toInt() xor 128).toUByte()
assertFails { ServerHandshake(creds.secret, creds.server, ConcealedCarrier.Kind.STREAM, options, alias) }
assertFails { ServerHandshake(LibsodiumRandom.buf(32), creds.server, ConcealedCarrier.Kind.STREAM, options, c.hello) }
assertFails { ServerHandshake(creds.secret, SigningSecretKey.new(), ConcealedCarrier.Kind.STREAM, options, c.hello) }
assertFails { ServerHandshake(creds.secret, creds.server, ConcealedCarrier.Kind.DATAGRAM, options, c.hello) }
}
@Test fun corruptServerSignatureAndCorruptClientSignatureAreRejected() = runTest(timeout = 60.seconds) {
initCrypto()
val creds = Credentials()
val badServer = corruptSigner(creds.server)
val client = ClientHandshake(creds.public, creds.server.verifyingKey, creds.client, ConcealedCarrier.Kind.STREAM, options)
val server = ServerHandshake(creds.secret, badServer, ConcealedCarrier.Kind.STREAM, options, client.hello)
assertFails { client.receiveServerHello(server.response) }
val badClient = ClientHandshake(creds.public, creds.server.verifyingKey, corruptSigner(creds.client), ConcealedCarrier.Kind.STREAM, options)
val goodServer = ServerHandshake(creds.secret, creds.server, ConcealedCarrier.Kind.STREAM, options, badClient.hello)
assertFails { goodServer.verifyAck(badClient.receiveServerHello(goodServer.response)) }
assertFails { goodServer.accept() }
}
@Test fun mutationOfEachProtectedFlightFails() = runTest(timeout = 60.seconds) {
initCrypto()
val creds = Credentials()
fun corrupt(frame: UByteArray) = frame.copyOf().also { it[it.lastIndex] = (it.last().toInt() xor 1).toUByte() }
val (c1, s1) = creds.attempt()
assertFailsWith<UnauthenticatedFlight> { c1.receiveServerHello(corrupt(s1.response)) }
s1.verifyAck(c1.receiveServerHello(s1.response))
c1.receiveAcceptance(s1.accept())
val (c2, s2) = creds.attempt()
val ack2 = c2.receiveServerHello(s2.response)
assertFailsWith<UnauthenticatedFlight> { s2.verifyAck(corrupt(ack2)) }
s2.verifyAck(ack2)
c2.receiveAcceptance(s2.accept())
val (c3, s3) = creds.attempt()
s3.verifyAck(c3.receiveServerHello(s3.response))
val acceptance = s3.accept()
assertFailsWith<UnauthenticatedFlight> { c3.receiveAcceptance(corrupt(acceptance)) }
c3.receiveAcceptance(acceptance)
}
@Test fun largePaddingPolicyShrinksToDatagramBudget() = runTest(timeout = 60.seconds) {
initCrypto()
val creds = Credentials()
val clientOptions = ConcealedOptions(padding = ConcealedOptions.Padding(10000))
val serverOptions = ConcealedOptions(padding = ConcealedOptions.Padding(10000), udp = ConcealedOptions.Udp(maxDatagramBytes = 512))
val kind = ConcealedCarrier.Kind.DATAGRAM
val fittingClient = ClientHandshake(creds.public, creds.server.verifyingKey, creds.client, kind,
clientOptions.copy(udp = ConcealedOptions.Udp(maxDatagramBytes = 512)))
val server = ServerHandshake(creds.secret, creds.server, kind, serverOptions, fittingClient.hello)
assertTrue(fittingClient.hello.size <= 512)
assertTrue(server.response.size <= 512)
val ack = fittingClient.receiveServerHello(server.response)
assertTrue(ack.size <= 512)
server.verifyAck(ack)
val accept = server.accept()
assertTrue(accept.size <= 512)
fittingClient.receiveAcceptance(accept)
}
private fun corruptSigner(key: SigningKey): SigningKey = object : SigningKey by key {
override fun sign(message: UByteArray) = key.sign(message).also { it[0] = (it[0].toInt() xor 1).toUByte() }
}
}
@@ -0,0 +1,43 @@
@file:OptIn(ExperimentalUnsignedTypes::class)
package net.sergeych.kiloparsec.concealed.handshake
import com.ionspin.kotlin.crypto.secretbox.SecretBox
import kotlinx.coroutines.test.runTest
import net.sergeych.crypto2.initCrypto
import kotlin.test.*
class FlightEnvelopeTest {
@Test fun independentKdfVectors() = runTest {
initCrypto()
val secret = UByteArray(32) { it.toUByte() }
val context = ubyteArrayOf(0xa0u, 0xa1u, 0xa2u, 0xa3u)
assertContentEquals(hex("595859a9e444bb24d1df7c118eeef70fea86720249bd9292eba6e32744da6f19"), derive(32, secret, "vector", context))
assertContentEquals(hex("46d4b4de3827562b5654864913c2c46cb9802a6a71322599"), derive(24, secret, "vector", context))
}
@Test fun headerAuthenticationLengthBoundsAndRepeatedLengthBinding() = runTest {
initCrypto()
val root = UByteArray(32) { it.toUByte() }
val context = UByteArray(32) { (it + 40).toUByte() }
val envelope = FlightEnvelope(root, context, 128)
val payload = ubyteArrayOf(10u, 20u, 30u)
val frame = envelope.seal(payload)
assertEquals(43, frame.size)
assertEquals(frame.size, envelope.size(frame.copyOfRange(0, 20)))
assertContentEquals(payload, envelope.open(frame))
val modifiedHeader = frame.copyOfRange(0, 20).also { it[0] = (it[0].toInt() xor 1).toUByte() }
assertFailsWith<HandshakeFailure> { envelope.size(modifiedHeader) }
assertFailsWith<HandshakeFailure> { envelope.open(frame.copyOf(frame.size - 1)) }
assertFailsWith<HandshakeFailure> { envelope.open(frame + ubyteArrayOf(0u)) }
fun encryptHeader(length: Int) = SecretBox.easy(int32(length),
derive(24, root, "flight/header-iv", context), derive(32, root, "flight/header-key", context))
// Correct authentication does not allow the peer to force an oversized allocation.
assertFailsWith<HandshakeFailure> { envelope.size(encryptHeader(89)) }
val differentBody = SecretBox.easy(int32(4) + payload,
derive(24, root, "flight/body-iv", context), derive(32, root, "flight/body-key", context))
assertFailsWith<HandshakeFailure> { envelope.open(encryptHeader(3) + differentBody) }
}
private fun hex(value: String) = value.chunked(2).map { it.toInt(16).toUByte() }.toUByteArray()
}
@@ -0,0 +1,61 @@
@file:OptIn(ExperimentalUnsignedTypes::class)
package net.sergeych.kiloparsec.concealed.handshake
// Generated by tools/concealed-vectors/reference.py; synthetic secrets ONLY.
internal object IndependentWireFixtures {
fun bytes(name: String): UByteArray = values.getValue(name).chunked(2).map { it.toUByte(16) }.toUByteArray()
private val values = mapOf(
"serverSecret" to "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f",
"serverPublic" to "8f40c5adb68f25624ae5b214ea767a6ec94d829d3d7b5e1ad1ba6f3e2138285f",
"clientDhSecret" to "202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f",
"clientDhPublic" to "358072d6365880d1aeea329adf9121383851ed21a28e3b75e965d0d2cd166254",
"serverDhSecret" to "404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f",
"serverDhPublic" to "79a631eede1bf9c98f12032cdeadd0e7a079398fc786b88cc846ec89af85a51a",
"serverSigningSeed" to "606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f",
"serverIdentity" to "174553b456dddfc6908ecab1c101fe6ab21e2baa0617795b7d43a63482993fd5",
"clientSigningSeed" to "808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f",
"clientIdentity" to "cd14b37f956e953194ff7fb73b3d81dcc561d61a7538094b7c3e1a643ee5f3aa",
"representative" to "a0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebf",
"heloIv" to "c0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7",
"bootstrapShared" to "900702f8b7a7dd869cf98f17dce31515a39e8043636352e8bf7be99043b83101",
"bootstrapRoot" to "f0cce9735754e6985895bbf2ad73a16a1ad5732399df991a598f17e71f3b2d04",
"heloCore" to "0101358072d6365880d1aeea329adf9121383851ed21a28e3b75e965d0d2cd166254174553b456dddfc6908ecab1c101fe6ab21e2baa0617795b7d43a63482993fd500100000000000000000",
"f1" to "a0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d77e7c60745d6ff2d29cb31ea1ee07d57dcbf42a3b1ac4341763a6f7baaa5766561e2fd98b7e4a69846548854a72be3b036eac464732b81a97afd4ef73c75f0a45703fd77c5ee8d29188ea452d9125e0bd8b798c212fccb1a65b4b617c1ebffd3c10256bc31f2949c6095f8cbc241d43b12f1591d01df46548",
"h1" to "602f30edcbbd47efaeaf6c79e30d0a418ac5dd0f18f03148dc55d6f1115ac6c1",
"replyIv" to "000102030405060708090a0b0c0d0e0f1011121314151617",
"replyRoot" to "7b747b6d95ad2bbb29d75ffd307291a1fbe9ac30e29fd8723ad859c7edd9cd50",
"serverCore" to "010179a631eede1bf9c98f12032cdeadd0e7a079398fc786b88cc846ec89af85a51a56a735db2bdb65b5240a7c7265917a909c1515ca682dcce740c9f00ac91eabcd174553b456dddfc6908ecab1c101fe6ab21e2baa0617795b7d43a63482993fd500100000000000000000",
"serverSignature" to "c9449226a851142979083bb1c633005c6323be2c868b2c188db04e63c9dd8952f1bfb549b4a43fa485cf456fe139206f92adf8a738e1ca4d95f03b0378d22906",
"f2" to "000102030405060708090a0b0c0d0e0f10111213141516179e23f0972e103c06d5b5a374b83490d3746d51aeb4efb24829822dc8a6826e417734a39ad43437e12d7e379cf633d2397a9ede00b477308a59f262f12c0804f79b7b00b86f04426c7349d53d4935601dad6eb81a95e0bbdab3d73607a6187e2bd18a83d90c93858f17dee1753cfb56395c505a004fc1cbcc2ca6c3820c81b3128c8f69138e7435dfba773b8a05cfa7a328d4bc76dd0db0aba878718c48798ee60a95cb46d24d87003a688e0eb3761871f33621b245f70d1152358cbc41e7b073de23d41579f81883725035a46248c1c17a59644e43ac9e6a",
"h2" to "ccb3ed241a73bd60911c36356a70651e8ab884ed5958514122f35d382d0d2533",
"sessionShared" to "04c304fb1ca83cee75e206344231f33797e07d9929db670994b7c6fbeb1dc255",
"s2c" to "46d6c3a94b432fab260e6252e53b488c6ce8b5dca9d17499facac2e402f1ccb1",
"c2s" to "2839576c1187d37c4e4d330ce4331c305c9ebf1ac599110fd1e9c44c1f64a5f3",
"token" to "b6e3c9512701a9edea03d60c5f50ac894bf652c776e3636f642a319357148481",
"finishedC2s" to "4e6ed04a46d1f01c64873c0050afb167b110de66ae8ab97344e79d0c527bd8ad",
"finishedS2c" to "f6de33390f63d704bf2fa82dac7aa1e21a08da48351326047d68c6dd6c9d280e",
"clientSignature" to "dc405b92ddf7499d47f3a32e837bed640d4565632e4f332ccbc7b6159a0afd1e1272bd36531a6b5d8a40c60e4a307b8a8e8aca62ba4d635ba278b19e5c448004",
"ackCore" to "03ccb3ed241a73bd60911c36356a70651e8ab884ed5958514122f35d382d0d2533cd14b37f956e953194ff7fb73b3d81dcc561d61a7538094b7c3e1a643ee5f3aadc405b92ddf7499d47f3a32e837bed640d4565632e4f332ccbc7b6159a0afd1e1272bd36531a6b5d8a40c60e4a307b8a8e8aca62ba4d635ba278b19e5c448004",
"ackIv" to "18191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f",
"f3" to "18191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f13d609bbf798a1056e5bca20eb89872e2160808864b58cf718c89dabe170b453ccfff09a287502ab1167011f79bbcdabdd673a8e26b22f4f7e7d91ec802dc1b8917820d93a24faaa86abfd0c04ec6c670a5938ac8e003aa7378e6a995b3039e7d5d1a0dd233c8589feb771ee1a6df8d8e43a6ace5ce146ca440eaaa0c3ff0cfe190be2dd60a9c129ae4cb5e3802fd306e1086a180605c59c01e1a17ffb943e517a6516f409159b1b6a9ce95079",
"h3" to "4f21ca3091f37bf39d78fea6cb5ea6dca91f0fd78442beb6874fc6a9097be5c0",
"acceptCore" to "044f21ca3091f37bf39d78fea6cb5ea6dca91f0fd78442beb6874fc6a9097be5c0",
"acceptIv" to "303132333435363738393a3b3c3d3e3f4041424344454647",
"f4" to "303132333435363738393a3b3c3d3e3f40414243444546479c1359d7f05d126e96c469773c8a586c711742c1547137a75fed8f3e29c2bb51cf8e86698471e4e4ab58e325efe7c451c6183ae167602430d9a9773baec43dccd6d4d4c067b012838fabaf7624",
"c2sStreamKey" to "3849e6ec55adeb429a2f1152fe1d6499f3c331d0c20f961ffb07d37d0a1f6ba6",
"c2sStreamSalt" to "124c709383f7fec219af21b040cafa2c28ee23b58bdbd36e",
"c2sMacKey" to "098146c2016cc5d4799e804784c424746b75b4f0dfe5ad6772147f48424cfafe",
"c2sUdpKey" to "e39c67192f6668ff5e3fe2b3155d161c30327d855d1ad7584337ee0eed3d2d85",
"s2cStreamKey" to "7d859e27ebf54f5117dc173919f4952ca4a79d449b39ca4cb66dc982ad6df43c",
"s2cStreamSalt" to "98f157f145f68670eafcc2a1e114ae269d5efe1fbc89d806",
"s2cMacKey" to "902cce94c7e7335027c3ed5ac695e6ba9ebfef8a2d8dd94bd7bf522b2f78a185",
"s2cUdpKey" to "fb470d7c6dd2980c070303660e7d11726a3b92fab057b5d6a2f63a75fc1b9453",
"object0" to "000102",
"udp0" to "000102030405060708090a0b0c0d0e0f101112131415161752519f6c14b9af07c4ff6e4506bded91385f473d499ae7a1bd77ff90835751",
"object1" to "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445",
"udp1" to "18191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f27e785c70cb414797285f7ece74d227f7c8773bafdc1fc59c19631825e48b1352adee3f0c8a9a61c1d49c40f6207fde77ccc279982109f22b1b33ce02f71ffe3565d6c5aa656d58caa8aded51d35c6cef5aefd5b8c08b7c892901bfbfad7c503f7ec",
"object2" to "010000",
"udp2" to "303132333435363738393a3b3c3d3e3f4041424344454647781578e7e4cdfc68bec534773c724439f04787b1f981d09987320ac7637f21",
"tcp" to "7076dc0a75456996a85759de0c9e1ddc7f19e4f42f8d21b9c67909f4e106a0388494a18df501d78b8e51bf3affa6cd10bff8307afc5b4c45494a0e89d2d11a823a7257f7d52c0379d3333e33753933630e270d5fa61f11106d80095feff564231280114d47d12d9af30825d86bb1bbf6339c0047f65976ec0c370230fab18a2f7d79ea93d848b069f0a99b42dc6bf2b6ef96f498",
)
}
@@ -0,0 +1,111 @@
@file:OptIn(ExperimentalUnsignedTypes::class, net.sergeych.kiloparsec.concealed.ExperimentalConcealedProtocol::class)
package net.sergeych.kiloparsec.concealed.handshake
import com.ionspin.kotlin.crypto.keyexchange.KeyExchange
import com.ionspin.kotlin.crypto.scalarmult.ScalarMultiplication
import kotlinx.coroutines.test.runTest
import net.sergeych.crypto2.SigningSecretKey
import net.sergeych.crypto2.VerifyingPublicKey
import net.sergeych.crypto2.initCrypto
import net.sergeych.kiloparsec.concealed.ConcealedCarrier
import net.sergeych.kiloparsec.concealed.ConcealedOptions
import net.sergeych.kiloparsec.concealed.elligator.ExperimentalElligator25519
import net.sergeych.kiloparsec.concealed.record.*
import kotlin.test.*
/** All expected bytes originate in the standalone Python composition reference. */
class IndependentWireVectorsTest {
private fun f(name: String) = IndependentWireFixtures.bytes(name)
private fun eq(name: String, actual: UByteArray) = assertContentEquals(f(name), actual, name)
private fun envelope(root: UByteArray, context: UByteArray, core: UByteArray, tail: UByteArray = ubyteArrayOf()) =
FlightEnvelope(root, context, 16384).seal(vector(core) + tail)
@Test fun independentFourFlightEncodingSignaturesAndSessionMaterial() = runTest {
initCrypto()
val vs = SigningSecretKey.fromSeed(f("serverSigningSeed"))
val vc = SigningSecretKey.fromSeed(f("clientSigningSeed"))
eq("serverIdentity", vs.verifyingKey.keyBytes)
eq("clientIdentity", vc.verifyingKey.keyBytes)
val bootstrap = ScalarMultiplication.scalarMultiplication(f("serverSecret"), ExperimentalElligator25519.decode(f("representative")))
eq("bootstrapShared", bootstrap)
val context = f("representative") + f("heloIv") + f("serverPublic")
val root = derive(32, bootstrap, "bootstrap", context)
eq("bootstrapRoot", root)
val f1 = f("representative") + f("heloIv") + envelope(root, hash(context), f("heloCore"))
eq("f1", f1)
eq("h1", hash(label("helo") + vector(f1)))
val replyRoot = derive(32, f("clientDhPublic"), "server-reply", f("h1") + f("serverPublic") + vs.verifyingKey.keyBytes)
eq("replyRoot", replyRoot)
val signedServer = label("kiloparsec/concealed/1/server-auth") + f("h1") + vector(f("serverCore"))
eq("serverSignature", vs.sign(signedServer))
assertTrue(vs.verifyingKey.verify(f("serverSignature"), signedServer))
val f2 = f("replyIv") + envelope(replyRoot, hash(label("server-flight") + f("h1") + f("replyIv")), f("serverCore"), f("serverSignature"))
eq("f2", f2)
eq("h2", hash(label("handshake") + vector(f1) + vector(f2)))
val keys = KeyExchange.clientSessionKeys(f("clientDhPublic"), f("clientDhSecret"), f("serverDhPublic"))
val serverKeys = KeyExchange.serverSessionKeys(f("serverDhPublic"), f("serverDhSecret"), f("clientDhPublic"))
eq("c2s", keys.sendKey); eq("s2c", keys.receiveKey)
eq("c2s", serverKeys.receiveKey); eq("s2c", serverKeys.sendKey)
val token = derive(32, keys.sendKey + keys.receiveKey, "connection-token", f("h2"))
eq("token", token)
val finishC = derive(32, keys.sendKey, "finished/c2s", f("h2"))
val finishS = derive(32, keys.receiveKey, "finished/s2c", f("h2"))
eq("finishedC2s", finishC); eq("finishedS2c", finishS)
val signedClient = label("kiloparsec/concealed/1/client-auth") + token + f("h2") + vc.verifyingKey.keyBytes
eq("clientSignature", vc.sign(signedClient))
assertTrue(vc.verifyingKey.verify(f("clientSignature"), signedClient))
val f3 = f("ackIv") + envelope(finishC, hash(label("ack") + f("h2") + f("ackIv")), f("ackCore"))
eq("f3", f3)
eq("h3", hash(label("authenticated-handshake") + f("h2") + vector(f3)))
eq("f4", f("acceptIv") + envelope(finishS, hash(label("accept") + f("h2") + f("acceptIv")), f("acceptCore")))
val bounds = PeerBounds(1048576, 0, 0)
val session = makeSession(keys, true, f("h2"), f("h3"), vs.verifyingKey, bounds, bounds)
eq("token", session.token)
for ((prefix, direction) in listOf("c2s" to session.sending, "s2c" to session.receiving)) {
eq(prefix + "StreamKey", direction.streamKey); eq(prefix + "StreamSalt", direction.streamSalt)
eq(prefix + "MacKey", direction.macKey); eq(prefix + "UdpKey", direction.udpKey)
}
}
@Test fun realServerAcceptsIndependentHelloAndBindsRepresentativeAlias() = runTest {
initCrypto()
val options = ConcealedOptions(padding = ConcealedOptions.Padding(0))
val identity = SigningSecretKey.fromSeed(f("serverSigningSeed"))
val frame = f("f1")
assertEquals(frame.size, ServerHandshake.helloSize(frame.copyOfRange(0, 76), f("serverSecret")))
val server = ServerHandshake(f("serverSecret"), identity, ConcealedCarrier.Kind.STREAM, options, frame)
eq("clientDhPublic", server.clientDhPublicKey)
assertEquals(240, server.response.size)
server.destroy()
for (bit in listOf(64, 128)) {
val alias = frame.copyOf().also { it[31] = (it[31].toInt() xor bit).toUByte() }
assertFailsWith<UnauthenticatedFlight> { ServerHandshake(f("serverSecret"), identity, ConcealedCarrier.Kind.STREAM, options, alias) }
}
}
@Test fun independentContinuousStreamAndReorderedDatagrams() = runTest {
initCrypto()
val limits = RecordLimits(maxPaddingBytes = 0)
val encoder = TcpRecordEncoder(f("c2sStreamKey"), f("c2sMacKey"), f("c2sStreamSalt"), limits)
val wire = (0..2).map { encoder.encode(f("object$it")) }.fold(ubyteArrayOf()) { a, b -> a + b }
// Object record boundaries are 27, 121, 148: all deliberately nonaligned to 64 bytes.
eq("tcp", wire)
for (step in listOf(1, 3, 63, 64, 65, wire.size)) {
val decoder = TcpRecordDecoder(f("c2sStreamKey"), f("c2sMacKey"), f("c2sStreamSalt"), limits)
val actual = mutableListOf<UByteArray>()
var cursor = 0
while (cursor < wire.size) {
val end = minOf(cursor + step, wire.size)
actual += decoder.feed(wire.copyOfRange(cursor, end)); cursor = end
}
decoder.finish()
assertEquals(3, actual.size)
actual.forEachIndexed { i, value -> eq("object$i", value) }
}
val udp = UdpRecordDecoder(f("c2sUdpKey"), limits)
for (q in listOf(2, 0, 1)) eq("object$q", assertNotNull(udp.decode(f("udp$q"))))
for (q in 0..2) assertNull(udp.decode(f("udp$q")))
val damaged = f("udp0").also { it[it.lastIndex] = (it.last().toInt() xor 1).toUByte() }
assertFailsWith<UnauthenticatedDatagram> { udp.decode(damaged) }
}
}
@@ -0,0 +1,191 @@
@file:OptIn(ExperimentalUnsignedTypes::class)
package net.sergeych.kiloparsec.concealed.record
import com.ionspin.kotlin.crypto.generichash.GenericHash
import com.ionspin.kotlin.crypto.secretbox.SecretBox
import com.ionspin.kotlin.crypto.stream.Stream
import kotlinx.coroutines.test.runTest
import net.sergeych.crypto2.initCrypto
import kotlin.random.Random
import kotlin.test.*
class ProtectedRecordsTest {
private val key = UByteArray(32) { it.toUByte() }
private val mac = UByteArray(32) { (it + 32).toUByte() }
private val nonce = UByteArray(24) { (it + 64).toUByte() }
private val unpadded = RecordLimits(maxPaddingBytes = 0)
@Test fun destructionPermanentlyRejectsEncoderDecoderAndCipherReuse() = runTest {
initCrypto()
val streamEncoder = TcpRecordEncoder(key, mac, nonce, unpadded)
val stream = streamEncoder.encode(ubyteArrayOf(1u))
val streamDecoder = TcpRecordDecoder(key, mac, nonce, unpadded)
assertTrue(streamDecoder.feed(stream.copyOfRange(0, 7)).isEmpty())
assertTrue(streamDecoder.hasPartialRecord)
streamEncoder.destroy(); streamDecoder.destroy()
streamEncoder.destroy(); streamDecoder.destroy() // Idempotent cleanup.
assertFalse(streamDecoder.hasPartialRecord)
assertFailsWith<IllegalStateException> { streamEncoder.encode(ubyteArrayOf()) }
assertFailsWith<IllegalStateException> { streamDecoder.feed(ubyteArrayOf()) }
assertFailsWith<IllegalStateException> { streamDecoder.finish() }
val datagramEncoder = UdpRecordEncoder(key, unpadded)
val datagram = datagramEncoder.encode(ubyteArrayOf(2u)).bytes
val datagramDecoder = UdpRecordDecoder(key, unpadded)
datagramEncoder.destroy(); datagramDecoder.destroy()
datagramEncoder.destroy(); datagramDecoder.destroy()
assertFailsWith<IllegalStateException> { datagramEncoder.encode(ubyteArrayOf()) }
assertFailsWith<IllegalStateException> { datagramDecoder.decode(datagram) }
val cipher = ContinuousCipher(key, nonce)
cipher.apply(ubyteArrayOf(1u)) // Leaves a partially used secret mask.
cipher.destroy(); cipher.destroy()
assertFailsWith<IllegalStateException> { cipher.apply(ubyteArrayOf()) }
}
@Test fun macMatchesIndependentBlake2bVector() = runTest {
initCrypto()
val body = ubyteArrayOf(0u, 0u, 0u, 3u, 1u, 0x61u, 0x62u, 0u, 0u)
val expected = "d0809fec300f48fb92d8eacd48284a8f".chunked(2).map { it.toUByte(16) }.toUByteArray()
assertContentEquals(expected, recordMac(key, 7uL, u32(body.size), body))
}
@Test fun usageCeilingsRejectBeforeRecordOrReplayMutation() = runTest {
initCrypto()
val one = RecordLimits(maxPaddingBytes = 0, maxRecords = 1uL)
val encoder = TcpRecordEncoder(key, mac, nonce, one)
val first = encoder.encode(ubyteArrayOf(1u))
assertFails { encoder.encode(ubyteArrayOf(2u)) }
val decoder = TcpRecordDecoder(key, mac, nonce, one)
assertContentEquals(ubyteArrayOf(1u), decoder.feed(first).single())
assertFailsWith<InvalidRecord> { decoder.feed(ubyteArrayOf(0u)) }
val tiny = RecordLimits(maxPaddingBytes = 0, maxStreamBytes = 24uL)
val smallEncoder = TcpRecordEncoder(key, mac, nonce, tiny)
assertFails { smallEncoder.encode(ubyteArrayOf(1u)) }
val exact = smallEncoder.encode(ubyteArrayOf())
assertContentEquals(ubyteArrayOf(), TcpRecordDecoder(key, mac, nonce, tiny).feed(exact).single())
assertFailsWith<InvalidRecord> { TcpRecordDecoder(key, mac, nonce, tiny).feed(first) }
val udp = UdpRecordEncoder(key, one)
val datagram = udp.encode(ubyteArrayOf(1u))
assertFails { udp.encode(ubyteArrayOf(2u)) }
val receiver = UdpRecordDecoder(key, one)
assertContentEquals(ubyteArrayOf(1u), receiver.decode(datagram.bytes))
assertNull(receiver.decode(datagram.bytes))
}
@Test fun streamMatchesSingleSodiumCallAcrossEveryMaskBoundary() = runTest {
initCrypto()
val input = UByteArray(4099) { (it * 7).toUByte() }
val derivedKey = GenericHash.genericHash(
"kiloparsec/concealed/stream-key/v1".encodeToByteArray().asUByteArray() + nonce, 32, key)
val derivedNonce = GenericHash.genericHash(
"kiloparsec/concealed/stream-nonce/v1".encodeToByteArray().asUByteArray() + nonce, 16, key).copyOf(8)
val expected = Stream.chacha20XorIc(input, derivedNonce, 0uL, derivedKey)
for (step in listOf(1, 3, 63, 64, 65, 127, 256)) {
val cipher = ContinuousCipher(key, nonce)
val actual = UByteArray(input.size)
var offset = 0
while (offset < input.size) {
val end = minOf(input.size, offset + step)
cipher.apply(input.copyOfRange(offset, end)).copyInto(actual, offset)
offset = end
}
assertContentEquals(expected, actual, "segmentation size $step")
}
}
@Test fun tcpSegmentationCoalescingAndVariablePadding() = runTest {
initCrypto()
val encoder = TcpRecordEncoder(key, mac, nonce)
val objects = listOf(ubyteArrayOf(), ubyteArrayOf(1u), UByteArray(511) { it.toUByte() }, UByteArray(10000))
val encoded = objects.map(encoder::encode).fold(ubyteArrayOf()) { a, b -> a + b }
for (step in listOf(1, 17, 64, 8192, encoded.size)) {
val decoder = TcpRecordDecoder(key, mac, nonce)
val actual = mutableListOf<UByteArray>()
var offset = 0
while (offset < encoded.size) {
val end = minOf(offset + step, encoded.size)
actual += decoder.feed(encoded.copyOfRange(offset, end))
offset = end
}
decoder.finish()
assertEquals(objects.size, actual.size)
objects.zip(actual).forEach { (a, b) -> assertContentEquals(a, b) }
}
}
@Test fun tcpRejectsEveryModifiedByteAndNeverPublishesUnauthenticatedBody() = runTest {
initCrypto()
val bytes = TcpRecordEncoder(key, mac, nonce, unpadded).encode(UByteArray(70) { it.toUByte() })
for (position in bytes.indices) {
val tampered = bytes.copyOf()
tampered[position] = (tampered[position].toInt() xor 1).toUByte()
val decoder = TcpRecordDecoder(key, mac, nonce, unpadded)
val result = runCatching { decoder.feed(tampered) }
// A manipulated length may leave a bounded partial read, but never yield an object.
if (result.isSuccess) {
assertTrue(result.getOrThrow().isEmpty())
assertFailsWith<InvalidRecord> { decoder.finish() }
}
assertFails { decoder.feed(ubyteArrayOf(0u)) }
}
}
@Test fun tcpRejectsReorderedRecordsAndTruncation() = runTest {
initCrypto()
val encoder = TcpRecordEncoder(key, mac, nonce, unpadded)
val first = encoder.encode(ubyteArrayOf(1u))
val second = encoder.encode(ubyteArrayOf(2u))
assertFails { TcpRecordDecoder(key, mac, nonce, unpadded).feed(second + first) }
for (n in 1 until first.size) {
val decoder = TcpRecordDecoder(key, mac, nonce, unpadded)
assertTrue(decoder.feed(first.copyOf(n)).isEmpty())
assertFailsWith<InvalidRecord> { decoder.finish() }
}
}
@Test fun authenticatedMalformedInnerLengthFailsBeforeObjectDelivery() = runTest {
initCrypto()
val body = u32(100) + ubyteArrayOf(1u)
val length = u32(body.size)
val cipher = ContinuousCipher(key, nonce)
val malformed = cipher.apply(length + body + recordMac(mac, 0uL, length, body))
assertFailsWith<InvalidRecord> { TcpRecordDecoder(key, mac, nonce).feed(malformed) }
}
@Test fun udpReordersDropsDuplicatesAndPreservesWindowOnForgery() = runTest {
initCrypto()
val encoder = UdpRecordEncoder(key, unpadded)
val packets = (0..4100).map { encoder.encode(u32(it)) }
val decoder = UdpRecordDecoder(key, unpadded)
assertContentEquals(u32(4100), decoder.decode(packets[4100].bytes))
assertNull(decoder.decode(packets[0].bytes))
assertContentEquals(u32(4099), decoder.decode(packets[4099].bytes))
assertNull(decoder.decode(packets[4099].bytes))
val forged = packets[4098].bytes.copyOf()
forged[forged.lastIndex] = (forged.last().toInt() xor 1).toUByte()
assertFailsWith<InvalidRecord> { decoder.decode(forged) }
assertContentEquals(u32(4098), decoder.decode(packets[4098].bytes))
}
@Test fun udpRandomReorderingRoundTripAndBudget() = runTest {
initCrypto()
val limits = RecordLimits(maxDatagramBytes = 200)
val encoder = UdpRecordEncoder(key, limits)
val decoder = UdpRecordDecoder(key, limits)
val packets = (0..100).map { encoder.encode(u32(it)) }
assertTrue(packets.all { it.bytes.size <= 200 })
packets.shuffled(Random(73)).forEach { assertContentEquals(u32(it.sequence.toInt()), decoder.decode(it.bytes)) }
assertEquals(200, encoder.encode(UByteArray(148)).bytes.size)
assertFailsWith<IllegalArgumentException> { encoder.encode(UByteArray(149)) }
}
@Test fun udpTamperedSequenceDoesNotPoisonReplayState() = runTest {
initCrypto()
val nonce = UByteArray(24)
val malformed = nonce + SecretBox.easy(u64(123uL) + u32(999), nonce, key)
val decoder = UdpRecordDecoder(key)
assertFailsWith<InvalidRecord> { decoder.decode(malformed) }
val good = nonce + SecretBox.easy(u64(123uL) + u32(1) + ubyteArrayOf(7u), nonce, key)
assertContentEquals(ubyteArrayOf(7u), decoder.decode(good))
}
}