refactor(network): rework network module, use new bytecodec module and introduce proper packet events
This commit is contained in:
1 parent
8048827121
commit
d27a54f360
340 files changed
+7462
-62719
No files matched your search
@@ -0,0 +1,48 @@
|
||||
package de.fiereu.network
|
||||
|
||||
import io.netty.bootstrap.Bootstrap
|
||||
import io.netty.bootstrap.ServerBootstrap
|
||||
import io.netty.channel.Channel
|
||||
import io.netty.channel.ChannelInitializer
|
||||
|
||||
fun ServerBootstrap.installNetwork(
|
||||
identity: SessionIdentity.ServerRoot,
|
||||
applicationProtocol: Protocol,
|
||||
applicationHandlerFactory: () -> ProtocolHandler,
|
||||
options: PipelineOptions = PipelineOptions(),
|
||||
): ServerBootstrap =
|
||||
childHandler(
|
||||
object : ChannelInitializer<Channel>() {
|
||||
override fun initChannel(ch: Channel) {
|
||||
installPipeline(
|
||||
pipeline = ch.pipeline(),
|
||||
side = Side.SERVER,
|
||||
identity = identity,
|
||||
applicationProtocol = applicationProtocol,
|
||||
applicationHandlerFactory = applicationHandlerFactory,
|
||||
options = options,
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
fun Bootstrap.installNetwork(
|
||||
identity: SessionIdentity.ClientTrust,
|
||||
applicationProtocol: Protocol,
|
||||
applicationHandlerFactory: () -> ProtocolHandler,
|
||||
options: PipelineOptions = PipelineOptions(),
|
||||
): Bootstrap =
|
||||
handler(
|
||||
object : ChannelInitializer<Channel>() {
|
||||
override fun initChannel(ch: Channel) {
|
||||
installPipeline(
|
||||
pipeline = ch.pipeline(),
|
||||
side = Side.CLIENT,
|
||||
identity = identity,
|
||||
applicationProtocol = applicationProtocol,
|
||||
applicationHandlerFactory = applicationHandlerFactory,
|
||||
options = options,
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,14 @@
|
||||
package de.fiereu.network
|
||||
|
||||
enum class Direction {
|
||||
C2S,
|
||||
S2C;
|
||||
|
||||
fun isIncomingFor(side: Side): Boolean =
|
||||
when (this) {
|
||||
C2S -> side == Side.SERVER
|
||||
S2C -> side == Side.CLIENT
|
||||
}
|
||||
|
||||
fun isOutgoingFor(side: Side): Boolean = !isIncomingFor(side)
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package de.fiereu.network
|
||||
|
||||
import kotlin.reflect.KClass
|
||||
|
||||
open class NetworkException(message: String, cause: Throwable? = null) :
|
||||
RuntimeException(message, cause)
|
||||
|
||||
class UnknownOpcodeException(val opcode: UByte, val side: Side) :
|
||||
NetworkException("No incoming codec for opcode 0x${opcode.toString(16)} on $side")
|
||||
|
||||
class UnknownPacketTypeException(val type: KClass<*>, val side: Side) :
|
||||
NetworkException("No outgoing registration for ${type.simpleName} on $side")
|
||||
|
||||
class ChecksumMismatchException : NetworkException("Checksum verification failed")
|
||||
|
||||
class TrailingBytesException(val opcode: UByte, val remaining: Int) :
|
||||
NetworkException(
|
||||
"Codec for opcode 0x${opcode.toString(16)} did not consume $remaining trailing byte(s)")
|
||||
|
||||
class EmptyFrameException : NetworkException("Received empty frame")
|
||||
|
||||
open class HandshakeException(message: String, cause: Throwable? = null) :
|
||||
NetworkException(message, cause)
|
||||
|
||||
class StaleClientHelloException(val skewSeconds: Long) :
|
||||
HandshakeException("ClientHello timestamp drift: ${skewSeconds}s")
|
||||
|
||||
class InvalidServerSignatureException :
|
||||
HandshakeException("ServerHello signature does not match trusted root key")
|
||||
|
||||
class HandlerRegistrationException(message: String) : NetworkException(message)
|
||||
@@ -0,0 +1,29 @@
|
||||
package de.fiereu.network
|
||||
|
||||
import de.fiereu.bytecodec.ReadBuffer
|
||||
import de.fiereu.bytecodec.WriteBuffer
|
||||
import io.netty.buffer.ByteBuf
|
||||
|
||||
class NettyReadBuffer(private val buf: ByteBuf) : ReadBuffer {
|
||||
override fun readByte(): Byte = buf.readByte()
|
||||
|
||||
override fun readBytes(dst: ByteArray, offset: Int, length: Int) {
|
||||
buf.readBytes(dst, offset, length)
|
||||
}
|
||||
|
||||
override fun skip(n: Int) {
|
||||
buf.skipBytes(n)
|
||||
}
|
||||
|
||||
override fun remaining(): Int = buf.readableBytes()
|
||||
}
|
||||
|
||||
class NettyWriteBuffer(private val buf: ByteBuf) : WriteBuffer {
|
||||
override fun writeByte(value: Byte) {
|
||||
buf.writeByte(value.toInt())
|
||||
}
|
||||
|
||||
override fun writeBytes(src: ByteArray, offset: Int, length: Int) {
|
||||
buf.writeBytes(src, offset, length)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package de.fiereu.network
|
||||
|
||||
import io.netty.channel.ChannelFuture
|
||||
|
||||
data class PacketEvent<T : Any>(
|
||||
val packet: T,
|
||||
val session: SessionContext,
|
||||
)
|
||||
|
||||
fun PacketEvent<*>.respond(packet: Any): ChannelFuture = session.send(packet)
|
||||
|
||||
fun PacketEvent<*>.disconnect(reason: () -> String = { "no reason" }) = session.close(reason)
|
||||
@@ -0,0 +1,76 @@
|
||||
package de.fiereu.network
|
||||
|
||||
import de.fiereu.network.checksum.NoOpChecksum
|
||||
import de.fiereu.network.cipher.NoOpSessionCipher
|
||||
import de.fiereu.network.handlers.ChecksumFrameDecoder
|
||||
import de.fiereu.network.handlers.ChecksumFrameEncoder
|
||||
import de.fiereu.network.handlers.CipherDecoder
|
||||
import de.fiereu.network.handlers.CipherEncoder
|
||||
import de.fiereu.network.handlers.PacketFrameDecoder
|
||||
import de.fiereu.network.handlers.PacketFrameEncoder
|
||||
import de.fiereu.network.handshake.ClientSessionHandshakeHandler
|
||||
import de.fiereu.network.handshake.ServerSessionHandshakeHandler
|
||||
import de.fiereu.network.internal.MutableSessionContext
|
||||
import de.fiereu.network.internal.SESSION_KEY
|
||||
import io.netty.channel.ChannelPipeline
|
||||
import io.netty.handler.logging.LogLevel
|
||||
import io.netty.handler.logging.LoggingHandler
|
||||
import io.netty.handler.timeout.WriteTimeoutHandler
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
fun installPipeline(
|
||||
pipeline: ChannelPipeline,
|
||||
side: Side,
|
||||
identity: SessionIdentity,
|
||||
applicationProtocol: Protocol,
|
||||
applicationHandlerFactory: () -> ProtocolHandler,
|
||||
options: PipelineOptions = PipelineOptions(),
|
||||
) {
|
||||
val channel = pipeline.channel()
|
||||
val session = MutableSessionContext(side, channel, applicationProtocol)
|
||||
channel.attr(SESSION_KEY).set(session)
|
||||
|
||||
val handshakeHandler: ProtocolHandler =
|
||||
when (side) {
|
||||
Side.SERVER -> {
|
||||
require(identity is SessionIdentity.ServerRoot) {
|
||||
"Server side requires SessionIdentity.ServerRoot"
|
||||
}
|
||||
ServerSessionHandshakeHandler(
|
||||
rootPrivate = identity.rootPrivate,
|
||||
applicationProtocol = applicationProtocol,
|
||||
applicationHandlerFactory = applicationHandlerFactory,
|
||||
options = options,
|
||||
)
|
||||
}
|
||||
Side.CLIENT -> {
|
||||
require(identity is SessionIdentity.ClientTrust) {
|
||||
"Client side requires SessionIdentity.ClientTrust"
|
||||
}
|
||||
ClientSessionHandshakeHandler(
|
||||
rootPublic = identity.rootPublic,
|
||||
applicationProtocol = applicationProtocol,
|
||||
applicationHandlerFactory = applicationHandlerFactory,
|
||||
options = options,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pipeline.addLast(
|
||||
PipelineNames.WRITE_TIMEOUT,
|
||||
WriteTimeoutHandler(options.writeTimeout.inWholeSeconds, TimeUnit.SECONDS),
|
||||
)
|
||||
if (options.frameLogging) {
|
||||
pipeline.addLast(PipelineNames.FRAME_LOGGER, LoggingHandler(LogLevel.TRACE))
|
||||
}
|
||||
pipeline.addLast(PipelineNames.FRAME_DECODER, PacketFrameDecoder(options.maxFrameLength))
|
||||
pipeline.addLast(PipelineNames.FRAME_ENCODER, PacketFrameEncoder())
|
||||
pipeline.addLast(PipelineNames.CHECKSUM_DECODER, ChecksumFrameDecoder(NoOpChecksum))
|
||||
pipeline.addLast(PipelineNames.CHECKSUM_ENCODER, ChecksumFrameEncoder(NoOpChecksum))
|
||||
pipeline.addLast(PipelineNames.CIPHER_DECODER, CipherDecoder(NoOpSessionCipher))
|
||||
pipeline.addLast(PipelineNames.CIPHER_ENCODER, CipherEncoder(NoOpSessionCipher))
|
||||
if (options.frameLogging) {
|
||||
pipeline.addLast(PipelineNames.PROTOCOL_LOGGER, LoggingHandler(LogLevel.TRACE))
|
||||
}
|
||||
pipeline.addLast(PipelineNames.PROTOCOL_HANDLER, handshakeHandler)
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package de.fiereu.network
|
||||
|
||||
object PipelineNames {
|
||||
const val WRITE_TIMEOUT = "write-timeout"
|
||||
const val FRAME_LOGGER = "frame-logger"
|
||||
const val FRAME_DECODER = "frame-decoder"
|
||||
const val FRAME_ENCODER = "frame-encoder"
|
||||
const val CHECKSUM_DECODER = "checksum-decoder"
|
||||
const val CHECKSUM_ENCODER = "checksum-encoder"
|
||||
const val CIPHER_DECODER = "cipher-decoder"
|
||||
const val CIPHER_ENCODER = "cipher-encoder"
|
||||
const val COMPRESSION_DECODER = "compression-decoder"
|
||||
const val COMPRESSION_ENCODER = "compression-encoder"
|
||||
const val PROTOCOL_LOGGER = "protocol-logger"
|
||||
const val PROTOCOL_HANDLER = "protocol-handler"
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package de.fiereu.network
|
||||
|
||||
import kotlin.time.Duration
|
||||
import kotlin.time.Duration.Companion.minutes
|
||||
import kotlin.time.Duration.Companion.seconds
|
||||
|
||||
data class PipelineOptions(
|
||||
val checksumSize: Int = 16,
|
||||
val writeTimeout: Duration = 25.minutes,
|
||||
val maxFrameLength: Int = 0xFFFF,
|
||||
val compressionThreshold: Int = 256,
|
||||
val maxHelloSkew: Duration = 10.seconds,
|
||||
val frameLogging: Boolean = false,
|
||||
)
|
||||
@@ -0,0 +1,73 @@
|
||||
package de.fiereu.network
|
||||
|
||||
import de.fiereu.bytecodec.Codec
|
||||
import kotlin.reflect.KClass
|
||||
|
||||
abstract class Protocol {
|
||||
|
||||
open val compressed: Boolean = false
|
||||
|
||||
data class Registration<T : Any>(
|
||||
val opcode: UByte,
|
||||
val direction: Direction,
|
||||
val codec: Codec<T>,
|
||||
val type: KClass<T>,
|
||||
)
|
||||
|
||||
private val mutableRegistrations = mutableListOf<Registration<*>>()
|
||||
private val byOpcode = mutableMapOf<Pair<UByte, Direction>, Registration<*>>()
|
||||
private val byType = mutableMapOf<Pair<KClass<*>, Direction>, Registration<*>>()
|
||||
|
||||
val registrations: List<Registration<*>>
|
||||
get() = mutableRegistrations
|
||||
|
||||
fun <T : Any> c2s(opcode: UByte, codec: Codec<T>, type: KClass<T>) {
|
||||
register(Registration(opcode, Direction.C2S, codec, type))
|
||||
}
|
||||
|
||||
fun <T : Any> s2c(opcode: UByte, codec: Codec<T>, type: KClass<T>) {
|
||||
register(Registration(opcode, Direction.S2C, codec, type))
|
||||
}
|
||||
|
||||
fun <T : Any> bidi(opcode: UByte, codec: Codec<T>, type: KClass<T>) {
|
||||
register(Registration(opcode, Direction.C2S, codec, type))
|
||||
register(Registration(opcode, Direction.S2C, codec, type))
|
||||
}
|
||||
|
||||
private fun register(reg: Registration<*>) {
|
||||
val opKey = reg.opcode to reg.direction
|
||||
check(byOpcode.put(opKey, reg) == null) {
|
||||
"Duplicate registration for opcode 0x${reg.opcode.toString(16)} ${reg.direction}"
|
||||
}
|
||||
val typeKey = reg.type to reg.direction
|
||||
check(byType.put(typeKey, reg) == null) {
|
||||
"Duplicate registration for ${reg.type.simpleName} ${reg.direction}"
|
||||
}
|
||||
mutableRegistrations += reg
|
||||
}
|
||||
|
||||
fun incomingCodec(side: Side, opcode: UByte): Codec<*>? =
|
||||
incomingRegistration(side, opcode)?.codec
|
||||
|
||||
fun incomingRegistration(side: Side, opcode: UByte): Registration<*>? {
|
||||
val direction = if (side == Side.SERVER) Direction.C2S else Direction.S2C
|
||||
return byOpcode[opcode to direction]
|
||||
}
|
||||
|
||||
fun outgoingRegistration(side: Side, type: KClass<*>): Registration<*>? {
|
||||
val direction = if (side == Side.SERVER) Direction.S2C else Direction.C2S
|
||||
return byType[type to direction]
|
||||
}
|
||||
}
|
||||
|
||||
inline fun <reified T : Any> Protocol.c2s(opcode: UByte, codec: Codec<T>) {
|
||||
c2s(opcode, codec, T::class)
|
||||
}
|
||||
|
||||
inline fun <reified T : Any> Protocol.s2c(opcode: UByte, codec: Codec<T>) {
|
||||
s2c(opcode, codec, T::class)
|
||||
}
|
||||
|
||||
inline fun <reified T : Any> Protocol.bidi(opcode: UByte, codec: Codec<T>) {
|
||||
bidi(opcode, codec, T::class)
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package de.fiereu.network
|
||||
|
||||
import de.fiereu.bytecodec.Codec
|
||||
import de.fiereu.network.internal.OutgoingPacket
|
||||
import de.fiereu.network.internal.SESSION_KEY
|
||||
import io.github.oshai.kotlinlogging.KotlinLogging
|
||||
import io.netty.buffer.ByteBuf
|
||||
import io.netty.channel.ChannelDuplexHandler
|
||||
import io.netty.channel.ChannelHandlerContext
|
||||
import io.netty.channel.ChannelPromise
|
||||
|
||||
private val log = KotlinLogging.logger {}
|
||||
|
||||
abstract class ProtocolHandler(
|
||||
val protocol: Protocol,
|
||||
val side: Side,
|
||||
) : ChannelDuplexHandler() {
|
||||
|
||||
protected lateinit var session: SessionContext
|
||||
private set
|
||||
|
||||
override fun handlerAdded(ctx: ChannelHandlerContext) {
|
||||
val attached =
|
||||
ctx.channel().attr(SESSION_KEY).get()
|
||||
?: error("No SessionContext attached to channel ${ctx.channel()}")
|
||||
session = attached
|
||||
}
|
||||
|
||||
override fun channelActive(ctx: ChannelHandlerContext) {
|
||||
try {
|
||||
onActive()
|
||||
} catch (t: Throwable) {
|
||||
onErrorInternal(ctx, t)
|
||||
return
|
||||
}
|
||||
ctx.fireChannelActive()
|
||||
}
|
||||
|
||||
override fun channelInactive(ctx: ChannelHandlerContext) {
|
||||
try {
|
||||
onInactive()
|
||||
} finally {
|
||||
ctx.fireChannelInactive()
|
||||
}
|
||||
}
|
||||
|
||||
override fun channelRead(ctx: ChannelHandlerContext, msg: Any) {
|
||||
if (msg !is ByteBuf) {
|
||||
ctx.fireChannelRead(msg)
|
||||
return
|
||||
}
|
||||
try {
|
||||
if (msg.readableBytes() < 1) throw EmptyFrameException()
|
||||
val opcode = (msg.readByte().toInt() and 0xFF).toUByte()
|
||||
val registration = protocol.incomingRegistration(side, opcode)
|
||||
if (registration == null) {
|
||||
log.error { "No incoming codec for opcode 0x${opcode.toString(16)} on $side" }
|
||||
return
|
||||
}
|
||||
val packet = decode(registration.codec, msg)
|
||||
val trailing = msg.readableBytes()
|
||||
if (trailing > 0) throw TrailingBytesException(opcode, trailing)
|
||||
try {
|
||||
onPacket(PacketEvent(packet, session))
|
||||
} catch (t: Throwable) {
|
||||
onErrorInternal(ctx, t)
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
onErrorInternal(ctx, t)
|
||||
} finally {
|
||||
msg.release()
|
||||
}
|
||||
}
|
||||
|
||||
override fun write(ctx: ChannelHandlerContext, msg: Any, promise: ChannelPromise) {
|
||||
val (registration, value) =
|
||||
when (msg) {
|
||||
is OutgoingPacket -> msg.registration to msg.value
|
||||
is ByteBuf -> {
|
||||
ctx.write(msg, promise)
|
||||
return
|
||||
}
|
||||
else -> {
|
||||
val reg =
|
||||
protocol.outgoingRegistration(side, msg::class)
|
||||
?: throw UnknownPacketTypeException(msg::class, side)
|
||||
reg to msg
|
||||
}
|
||||
}
|
||||
val buffer = ctx.alloc().buffer()
|
||||
var success = false
|
||||
try {
|
||||
buffer.writeByte(registration.opcode.toInt())
|
||||
encode(registration.codec, value, buffer)
|
||||
success = true
|
||||
} finally {
|
||||
if (!success) buffer.release()
|
||||
}
|
||||
ctx.write(buffer, promise)
|
||||
}
|
||||
|
||||
override fun exceptionCaught(ctx: ChannelHandlerContext, cause: Throwable) {
|
||||
onErrorInternal(ctx, cause)
|
||||
}
|
||||
|
||||
private fun onErrorInternal(ctx: ChannelHandlerContext, cause: Throwable) {
|
||||
try {
|
||||
onError(cause)
|
||||
} catch (t: Throwable) {
|
||||
log.error(t) { "onError handler threw; closing channel" }
|
||||
ctx.close()
|
||||
}
|
||||
}
|
||||
|
||||
open fun onActive() {}
|
||||
|
||||
abstract fun onPacket(event: PacketEvent<*>)
|
||||
|
||||
open fun onInactive() {}
|
||||
|
||||
open fun onError(cause: Throwable) {
|
||||
log.warn(cause) { "Handler error on ${session.remoteAddress}" }
|
||||
session.close { "Handler error: ${cause.message}" }
|
||||
}
|
||||
|
||||
private fun <T : Any> decode(codec: Codec<T>, buf: ByteBuf): T = codec.read(NettyReadBuffer(buf))
|
||||
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
private fun encode(codec: Codec<*>, value: Any, buf: ByteBuf) {
|
||||
(codec as Codec<Any>).write(NettyWriteBuffer(buf), value)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package de.fiereu.network
|
||||
|
||||
import kotlin.reflect.KClass
|
||||
|
||||
class SessionAttribute<T : Any>(val name: String, val type: KClass<T>) {
|
||||
override fun toString(): String = "SessionAttribute($name)"
|
||||
|
||||
companion object {
|
||||
inline fun <reified T : Any> of(name: String): SessionAttribute<T> =
|
||||
SessionAttribute(name, T::class)
|
||||
}
|
||||
}
|
||||
|
||||
interface SessionAttributes {
|
||||
operator fun <T : Any> get(key: SessionAttribute<T>): T?
|
||||
|
||||
operator fun <T : Any> set(key: SessionAttribute<T>, value: T)
|
||||
|
||||
fun <T : Any> remove(key: SessionAttribute<T>): T?
|
||||
|
||||
fun <T : Any> getOrPut(key: SessionAttribute<T>, default: () -> T): T
|
||||
|
||||
fun contains(key: SessionAttribute<*>): Boolean
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package de.fiereu.network
|
||||
|
||||
import io.netty.channel.Channel
|
||||
import io.netty.channel.ChannelFuture
|
||||
import java.net.SocketAddress
|
||||
import java.time.Instant
|
||||
|
||||
interface SessionContext {
|
||||
val side: Side
|
||||
|
||||
val channel: Channel
|
||||
|
||||
val remoteAddress: SocketAddress
|
||||
|
||||
val phase: SessionPhase
|
||||
|
||||
val handshakeCompletedAt: Instant?
|
||||
|
||||
val attributes: SessionAttributes
|
||||
|
||||
fun send(packet: Any): ChannelFuture
|
||||
|
||||
fun close(reason: () -> String = { "no reason" })
|
||||
|
||||
fun onPhase(phase: SessionPhase, listener: () -> Unit)
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package de.fiereu.network
|
||||
|
||||
import java.security.interfaces.ECPrivateKey
|
||||
import java.security.interfaces.ECPublicKey
|
||||
|
||||
sealed interface SessionIdentity {
|
||||
data class ServerRoot(val rootPrivate: ECPrivateKey) : SessionIdentity
|
||||
|
||||
data class ClientTrust(val rootPublic: ECPublicKey) : SessionIdentity
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package de.fiereu.network
|
||||
|
||||
enum class SessionPhase {
|
||||
HANDSHAKE,
|
||||
ESTABLISHED,
|
||||
CLOSED,
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package de.fiereu.network
|
||||
|
||||
import de.fiereu.network.internal.SESSION_KEY
|
||||
import io.netty.channel.Channel
|
||||
|
||||
/** Look up the [SessionContext] attached by [installPipeline] for this channel. */
|
||||
fun Channel.session(): SessionContext? = attr(SESSION_KEY).get()
|
||||
@@ -0,0 +1,6 @@
|
||||
package de.fiereu.network
|
||||
|
||||
enum class Side {
|
||||
SERVER,
|
||||
CLIENT,
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package de.fiereu.network
|
||||
|
||||
import io.github.oshai.kotlinlogging.KotlinLogging
|
||||
import kotlin.reflect.KClass
|
||||
|
||||
private val log = KotlinLogging.logger {}
|
||||
|
||||
abstract class TypedProtocolHandler<P : Protocol>(
|
||||
protocol: P,
|
||||
side: Side,
|
||||
) : ProtocolHandler(protocol, side) {
|
||||
|
||||
@Volatile private var sealed = false
|
||||
|
||||
private val handlers = mutableMapOf<KClass<*>, (PacketEvent<*>) -> Unit>()
|
||||
|
||||
protected inline fun <reified T : Any> on(noinline handler: (PacketEvent<T>) -> Unit) {
|
||||
register(T::class, handler)
|
||||
}
|
||||
|
||||
@PublishedApi
|
||||
internal fun <T : Any> register(type: KClass<T>, handler: (PacketEvent<T>) -> Unit) {
|
||||
if (sealed) {
|
||||
throw HandlerRegistrationException(
|
||||
"Cannot register handler for ${type.simpleName} after the first packet",
|
||||
)
|
||||
}
|
||||
if (handlers.containsKey(type)) {
|
||||
throw HandlerRegistrationException(
|
||||
"Duplicate handler registration for ${type.simpleName}",
|
||||
)
|
||||
}
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
handlers[type] = handler as (PacketEvent<*>) -> Unit
|
||||
}
|
||||
|
||||
open fun isRegistered(type: KClass<*>): Boolean = handlers.containsKey(type)
|
||||
|
||||
protected open fun onUnhandled(event: PacketEvent<*>) {
|
||||
log.error { "Unhandled packet ${event.packet::class.simpleName} on $side" }
|
||||
}
|
||||
|
||||
final override fun onPacket(event: PacketEvent<*>) {
|
||||
sealed = true
|
||||
val handler = handlers[event.packet::class]
|
||||
if (handler != null) {
|
||||
handler(event)
|
||||
} else if (!tryHandleAlternate(event)) {
|
||||
onUnhandled(event)
|
||||
}
|
||||
}
|
||||
|
||||
protected open fun tryHandleAlternate(event: PacketEvent<*>): Boolean = false
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package de.fiereu.network.checksum
|
||||
|
||||
import io.netty.buffer.ByteBuf
|
||||
|
||||
interface Checksum {
|
||||
val size: Int
|
||||
|
||||
fun calculate(data: ByteBuf): ByteArray
|
||||
|
||||
fun verify(data: ByteBuf, expected: ByteArray): Boolean
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package de.fiereu.network.checksum
|
||||
|
||||
object ChecksumFactory {
|
||||
fun create(size: Int, key: ByteArray = ByteArray(0)): Checksum =
|
||||
when (size) {
|
||||
0 -> NoOpChecksum
|
||||
2 -> Crc16Checksum()
|
||||
in 4..32 -> HmacSha256Checksum(size, key)
|
||||
else -> throw IllegalArgumentException("Unsupported checksum size: $size")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
package de.fiereu.network.checksum
|
||||
|
||||
import io.netty.buffer.ByteBuf
|
||||
|
||||
class Crc16Checksum : Checksum {
|
||||
override val size: Int = 2
|
||||
|
||||
override fun calculate(data: ByteBuf): ByteArray {
|
||||
val sum = hash(data)
|
||||
return byteArrayOf((sum and 0xFF).toByte(), ((sum shr 8) and 0xFF).toByte())
|
||||
}
|
||||
|
||||
override fun verify(data: ByteBuf, expected: ByteArray): Boolean {
|
||||
if (expected.size != size) return false
|
||||
val actual = hash(data)
|
||||
val expectedSum = ((expected[1].toInt() and 0xFF) shl 8) or (expected[0].toInt() and 0xFF)
|
||||
return actual == expectedSum
|
||||
}
|
||||
|
||||
private fun hash(data: ByteBuf): Int {
|
||||
var sum = 0
|
||||
val end = data.writerIndex()
|
||||
var i = data.readerIndex()
|
||||
while (i < end) {
|
||||
val b = data.getByte(i).toInt() and 0xFF
|
||||
sum = (sum ushr 8) xor TABLE[(sum xor b) and 0xFF]
|
||||
i++
|
||||
}
|
||||
return sum and 0xFFFF
|
||||
}
|
||||
|
||||
companion object {
|
||||
private val TABLE =
|
||||
intArrayOf(
|
||||
0x0000,
|
||||
0xc0c1,
|
||||
0xc181,
|
||||
0x0140,
|
||||
0xc301,
|
||||
0x03c0,
|
||||
0x0280,
|
||||
0xc241,
|
||||
0xc601,
|
||||
0x06c0,
|
||||
0x0780,
|
||||
0xc741,
|
||||
0x0500,
|
||||
0xc5c1,
|
||||
0xc481,
|
||||
0x0440,
|
||||
0xcc01,
|
||||
0x0cc0,
|
||||
0x0d80,
|
||||
0xcd41,
|
||||
0x0f00,
|
||||
0xcfc1,
|
||||
0xce81,
|
||||
0x0e40,
|
||||
0x0a00,
|
||||
0xcac1,
|
||||
0xcb81,
|
||||
0x0b40,
|
||||
0xc901,
|
||||
0x09c0,
|
||||
0x0880,
|
||||
0xc841,
|
||||
0xd801,
|
||||
0x18c0,
|
||||
0x1980,
|
||||
0xd941,
|
||||
0x1b00,
|
||||
0xdbc1,
|
||||
0xda81,
|
||||
0x1a40,
|
||||
0x1e00,
|
||||
0xdec1,
|
||||
0xdf81,
|
||||
0x1f40,
|
||||
0xdd01,
|
||||
0x1dc0,
|
||||
0x1c80,
|
||||
0xdc41,
|
||||
0x1400,
|
||||
0xd4c1,
|
||||
0xd581,
|
||||
0x1540,
|
||||
0xd701,
|
||||
0x17c0,
|
||||
0x1680,
|
||||
0xd641,
|
||||
0xd201,
|
||||
0x12c0,
|
||||
0x1380,
|
||||
0xd341,
|
||||
0x1100,
|
||||
0xd1c1,
|
||||
0xd081,
|
||||
0x1040,
|
||||
0xf001,
|
||||
0x30c0,
|
||||
0x3180,
|
||||
0xf141,
|
||||
0x3300,
|
||||
0xf3c1,
|
||||
0xf281,
|
||||
0x3240,
|
||||
0x3600,
|
||||
0xf6c1,
|
||||
0xf781,
|
||||
0x3740,
|
||||
0xf501,
|
||||
0x35c0,
|
||||
0x3480,
|
||||
0xf441,
|
||||
0x3c00,
|
||||
0xfcc1,
|
||||
0xfd81,
|
||||
0x3d40,
|
||||
0xff01,
|
||||
0x3fc0,
|
||||
0x3e80,
|
||||
0xfe41,
|
||||
0xfa01,
|
||||
0x3ac0,
|
||||
0x3b80,
|
||||
0xfb41,
|
||||
0x3900,
|
||||
0xf9c1,
|
||||
0xf881,
|
||||
0x3840,
|
||||
0x2800,
|
||||
0xe8c1,
|
||||
0xe981,
|
||||
0x2940,
|
||||
0xeb01,
|
||||
0x2bc0,
|
||||
0x2a80,
|
||||
0xea41,
|
||||
0xee01,
|
||||
0x2ec0,
|
||||
0x2f80,
|
||||
0xef41,
|
||||
0x2d00,
|
||||
0xedc1,
|
||||
0xec81,
|
||||
0x2c40,
|
||||
0xe401,
|
||||
0x24c0,
|
||||
0x2580,
|
||||
0xe541,
|
||||
0x2700,
|
||||
0xe7c1,
|
||||
0xe681,
|
||||
0x2640,
|
||||
0x2200,
|
||||
0xe2c1,
|
||||
0xe381,
|
||||
0x2340,
|
||||
0xe101,
|
||||
0x21c0,
|
||||
0x2080,
|
||||
0xe041,
|
||||
0xa001,
|
||||
0x60c0,
|
||||
0x6180,
|
||||
0xa141,
|
||||
0x6300,
|
||||
0xa3c1,
|
||||
0xa281,
|
||||
0x6240,
|
||||
0x6600,
|
||||
0xa6c1,
|
||||
0xa781,
|
||||
0x6740,
|
||||
0xa501,
|
||||
0x65c0,
|
||||
0x6480,
|
||||
0xa441,
|
||||
0x6c00,
|
||||
0xacc1,
|
||||
0xad81,
|
||||
0x6d40,
|
||||
0xaf01,
|
||||
0x6fc0,
|
||||
0x6e80,
|
||||
0xae41,
|
||||
0xaa01,
|
||||
0x6ac0,
|
||||
0x6b80,
|
||||
0xab41,
|
||||
0x6900,
|
||||
0xa9c1,
|
||||
0xa881,
|
||||
0x6840,
|
||||
0x7800,
|
||||
0xb8c1,
|
||||
0xb981,
|
||||
0x7940,
|
||||
0xbb01,
|
||||
0x7bc0,
|
||||
0x7a80,
|
||||
0xba41,
|
||||
0xbe01,
|
||||
0x7ec0,
|
||||
0x7f80,
|
||||
0xbf41,
|
||||
0x7d00,
|
||||
0xbdc1,
|
||||
0xbc81,
|
||||
0x7c40,
|
||||
0xb401,
|
||||
0x74c0,
|
||||
0x7580,
|
||||
0xb541,
|
||||
0x7700,
|
||||
0xb7c1,
|
||||
0xb681,
|
||||
0x7640,
|
||||
0x7200,
|
||||
0xb2c1,
|
||||
0xb381,
|
||||
0x7340,
|
||||
0xb101,
|
||||
0x71c0,
|
||||
0x7080,
|
||||
0xb041,
|
||||
0x5000,
|
||||
0x90c1,
|
||||
0x9181,
|
||||
0x5140,
|
||||
0x9301,
|
||||
0x53c0,
|
||||
0x5280,
|
||||
0x9241,
|
||||
0x9601,
|
||||
0x56c0,
|
||||
0x5780,
|
||||
0x9741,
|
||||
0x5500,
|
||||
0x95c1,
|
||||
0x9481,
|
||||
0x5440,
|
||||
0x9c01,
|
||||
0x5cc0,
|
||||
0x5d80,
|
||||
0x9d41,
|
||||
0x5f00,
|
||||
0x9fc1,
|
||||
0x9e81,
|
||||
0x5e40,
|
||||
0x5a00,
|
||||
0x9ac1,
|
||||
0x9b81,
|
||||
0x5b40,
|
||||
0x9901,
|
||||
0x59c0,
|
||||
0x5880,
|
||||
0x9841,
|
||||
0x8801,
|
||||
0x48c0,
|
||||
0x4980,
|
||||
0x8941,
|
||||
0x4b00,
|
||||
0x8bc1,
|
||||
0x8a81,
|
||||
0x4a40,
|
||||
0x4e00,
|
||||
0x8ec1,
|
||||
0x8f81,
|
||||
0x4f40,
|
||||
0x8d01,
|
||||
0x4dc0,
|
||||
0x4c80,
|
||||
0x8c41,
|
||||
0x4400,
|
||||
0x84c1,
|
||||
0x8581,
|
||||
0x4540,
|
||||
0x8701,
|
||||
0x47c0,
|
||||
0x4680,
|
||||
0x8641,
|
||||
0x8201,
|
||||
0x42c0,
|
||||
0x4380,
|
||||
0x8341,
|
||||
0x4100,
|
||||
0x81c1,
|
||||
0x8081,
|
||||
0x4040,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package de.fiereu.network.checksum
|
||||
|
||||
import io.netty.buffer.ByteBuf
|
||||
import java.security.MessageDigest
|
||||
import javax.crypto.Mac
|
||||
import javax.crypto.spec.SecretKeySpec
|
||||
|
||||
class HmacSha256Checksum(
|
||||
override val size: Int,
|
||||
key: ByteArray,
|
||||
) : Checksum {
|
||||
|
||||
init {
|
||||
require(size in 4..32) { "HMAC-SHA256 size must be between 4 and 32 bytes" }
|
||||
}
|
||||
|
||||
private val mac: Mac =
|
||||
Mac.getInstance("HmacSHA256").also { it.init(SecretKeySpec(key, "HmacSHA256")) }
|
||||
|
||||
private var calculateRound = 0
|
||||
private var verifyRound = 0
|
||||
|
||||
override fun calculate(data: ByteBuf): ByteArray {
|
||||
val bytes = ByteArray(data.readableBytes())
|
||||
data.getBytes(data.readerIndex(), bytes)
|
||||
mac.update(bytes)
|
||||
mac.update(roundBytes(calculateRound++))
|
||||
return mac.doFinal().copyOfRange(0, size)
|
||||
}
|
||||
|
||||
override fun verify(data: ByteBuf, expected: ByteArray): Boolean {
|
||||
if (expected.size != size) return false
|
||||
val bytes = ByteArray(data.readableBytes())
|
||||
data.getBytes(data.readerIndex(), bytes)
|
||||
mac.update(bytes)
|
||||
mac.update(roundBytes(verifyRound++))
|
||||
val actual = mac.doFinal().copyOfRange(0, size)
|
||||
return MessageDigest.isEqual(actual, expected)
|
||||
}
|
||||
|
||||
private fun roundBytes(value: Int): ByteArray =
|
||||
byteArrayOf(
|
||||
((value ushr 24) and 0xFF).toByte(),
|
||||
((value ushr 16) and 0xFF).toByte(),
|
||||
((value ushr 8) and 0xFF).toByte(),
|
||||
(value and 0xFF).toByte(),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package de.fiereu.network.checksum
|
||||
|
||||
import io.netty.buffer.ByteBuf
|
||||
|
||||
object NoOpChecksum : Checksum {
|
||||
override val size: Int = 0
|
||||
|
||||
private val EMPTY = ByteArray(0)
|
||||
|
||||
override fun calculate(data: ByteBuf): ByteArray = EMPTY
|
||||
|
||||
override fun verify(data: ByteBuf, expected: ByteArray): Boolean = true
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package de.fiereu.network.cipher
|
||||
|
||||
import io.netty.buffer.ByteBuf
|
||||
import java.security.MessageDigest
|
||||
import java.security.PrivateKey
|
||||
import java.security.PublicKey
|
||||
import javax.crypto.Cipher
|
||||
import javax.crypto.KeyAgreement
|
||||
import javax.crypto.spec.IvParameterSpec
|
||||
import javax.crypto.spec.SecretKeySpec
|
||||
|
||||
class AesCtrSessionCipher
|
||||
private constructor(
|
||||
private val encryptCipher: Cipher,
|
||||
private val decryptCipher: Cipher,
|
||||
) : SessionCipher {
|
||||
|
||||
enum class Role {
|
||||
SERVER,
|
||||
CLIENT
|
||||
}
|
||||
|
||||
override fun encrypt(input: ByteBuf, output: ByteBuf) {
|
||||
apply(encryptCipher, input, output)
|
||||
}
|
||||
|
||||
override fun decrypt(input: ByteBuf, output: ByteBuf) {
|
||||
apply(decryptCipher, input, output)
|
||||
}
|
||||
|
||||
private fun apply(cipher: Cipher, input: ByteBuf, output: ByteBuf) {
|
||||
val len = input.readableBytes()
|
||||
if (len == 0) return
|
||||
val src = ByteArray(len)
|
||||
input.readBytes(src)
|
||||
val dst = cipher.update(src) ?: return
|
||||
if (dst.isNotEmpty()) {
|
||||
output.writeBytes(dst)
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private val IV_SALT = "IVDERIV".toByteArray(Charsets.US_ASCII)
|
||||
private val CLIENT_KEY_SALT = "KeySalt".toByteArray(Charsets.US_ASCII) + byteArrayOf(1)
|
||||
private val SERVER_KEY_SALT = "KeySalt".toByteArray(Charsets.US_ASCII) + byteArrayOf(2)
|
||||
|
||||
fun ecdh(localPrivate: PrivateKey, remotePublic: PublicKey): ByteArray {
|
||||
val agreement = KeyAgreement.getInstance("ECDH")
|
||||
agreement.init(localPrivate)
|
||||
agreement.doPhase(remotePublic, true)
|
||||
return agreement.generateSecret()
|
||||
}
|
||||
|
||||
fun derive(secret: ByteArray, role: Role): AesCtrSessionCipher {
|
||||
val (outSeed, inSeed) = directionalSeeds(secret, role)
|
||||
return AesCtrSessionCipher(
|
||||
encryptCipher = createCipher(Cipher.ENCRYPT_MODE, outSeed),
|
||||
decryptCipher = createCipher(Cipher.DECRYPT_MODE, inSeed),
|
||||
)
|
||||
}
|
||||
|
||||
internal fun directionalSeeds(secret: ByteArray, role: Role): Pair<ByteArray, ByteArray> {
|
||||
val clientSeed = tripleHash(secret, CLIENT_KEY_SALT)
|
||||
val serverSeed = tripleHash(secret, SERVER_KEY_SALT)
|
||||
return when (role) {
|
||||
Role.SERVER -> serverSeed to clientSeed
|
||||
Role.CLIENT -> clientSeed to serverSeed
|
||||
}
|
||||
}
|
||||
|
||||
fun derive(
|
||||
localPrivate: PrivateKey,
|
||||
remotePublic: PublicKey,
|
||||
role: Role,
|
||||
): AesCtrSessionCipher = derive(ecdh(localPrivate, remotePublic), role)
|
||||
|
||||
internal fun tripleHash(secret: ByteArray, salt: ByteArray): ByteArray {
|
||||
val sha = MessageDigest.getInstance("SHA-256")
|
||||
sha.update(salt)
|
||||
sha.update(secret)
|
||||
sha.update(salt)
|
||||
return sha.digest().copyOfRange(0, 16)
|
||||
}
|
||||
|
||||
private fun createCipher(mode: Int, seed: ByteArray): Cipher {
|
||||
val cipher = Cipher.getInstance("AES/CTR/NoPadding")
|
||||
val key = SecretKeySpec(seed, "AES")
|
||||
val iv = IvParameterSpec(tripleHash(seed, IV_SALT))
|
||||
cipher.init(mode, key, iv)
|
||||
return cipher
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package de.fiereu.network.cipher
|
||||
|
||||
import io.netty.buffer.ByteBuf
|
||||
|
||||
interface SessionCipher {
|
||||
fun encrypt(input: ByteBuf, output: ByteBuf)
|
||||
|
||||
fun decrypt(input: ByteBuf, output: ByteBuf)
|
||||
}
|
||||
|
||||
object NoOpSessionCipher : SessionCipher {
|
||||
override fun encrypt(input: ByteBuf, output: ByteBuf) {
|
||||
output.writeBytes(input)
|
||||
}
|
||||
|
||||
override fun decrypt(input: ByteBuf, output: ByteBuf) {
|
||||
output.writeBytes(input)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package de.fiereu.network.coroutines
|
||||
|
||||
import de.fiereu.network.HandlerRegistrationException
|
||||
import de.fiereu.network.PacketEvent
|
||||
import de.fiereu.network.Protocol
|
||||
import de.fiereu.network.Side
|
||||
import de.fiereu.network.TypedProtocolHandler
|
||||
import io.github.oshai.kotlinlogging.KotlinLogging
|
||||
import io.netty.channel.ChannelHandlerContext
|
||||
import kotlin.reflect.KClass
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.channels.Channel
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
private val log = KotlinLogging.logger {}
|
||||
|
||||
abstract class CoroutineProtocolHandler<P : Protocol>(
|
||||
protocol: P,
|
||||
side: Side,
|
||||
private val coroutineScope: CoroutineScope,
|
||||
) : TypedProtocolHandler<P>(protocol, side) {
|
||||
|
||||
private val suspendHandlers = mutableMapOf<KClass<*>, suspend (PacketEvent<*>) -> Unit>()
|
||||
|
||||
private val mailbox: Channel<PacketEvent<*>> = Channel(Channel.UNLIMITED)
|
||||
|
||||
@Volatile private var consumerJob: Job? = null
|
||||
|
||||
protected inline fun <reified T : Any> onSuspend(
|
||||
noinline handler: suspend (PacketEvent<T>) -> Unit,
|
||||
) {
|
||||
registerSuspend(T::class, handler)
|
||||
}
|
||||
|
||||
@PublishedApi
|
||||
internal fun <T : Any> registerSuspend(
|
||||
type: KClass<T>,
|
||||
handler: suspend (PacketEvent<T>) -> Unit,
|
||||
) {
|
||||
if (isRegistered(type) || suspendHandlers.containsKey(type)) {
|
||||
throw HandlerRegistrationException(
|
||||
"Duplicate handler registration for ${type.simpleName}",
|
||||
)
|
||||
}
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
suspendHandlers[type] = handler as suspend (PacketEvent<*>) -> Unit
|
||||
}
|
||||
|
||||
override fun handlerAdded(ctx: ChannelHandlerContext) {
|
||||
super.handlerAdded(ctx)
|
||||
consumerJob =
|
||||
coroutineScope.launch {
|
||||
for (event in mailbox) {
|
||||
val handler = suspendHandlers[event.packet::class] ?: continue
|
||||
try {
|
||||
handler(event)
|
||||
} catch (t: Throwable) {
|
||||
log.warn(t) { "Suspend handler for ${event.packet::class.simpleName} threw" }
|
||||
ctx.executor().execute { onError(t) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun handlerRemoved(ctx: ChannelHandlerContext) {
|
||||
mailbox.close()
|
||||
consumerJob?.cancel()
|
||||
consumerJob = null
|
||||
}
|
||||
|
||||
override fun isRegistered(type: KClass<*>): Boolean =
|
||||
super.isRegistered(type) || suspendHandlers.containsKey(type)
|
||||
|
||||
final override fun tryHandleAlternate(event: PacketEvent<*>): Boolean {
|
||||
if (event.packet::class !in suspendHandlers) return false
|
||||
val result = mailbox.trySend(event)
|
||||
if (!result.isSuccess) {
|
||||
log.warn { "Mailbox rejected packet ${event.packet::class.simpleName}" }
|
||||
onError(IllegalStateException("Coroutine mailbox closed"))
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package de.fiereu.network.handlers
|
||||
|
||||
import de.fiereu.network.ChecksumMismatchException
|
||||
import de.fiereu.network.checksum.Checksum
|
||||
import io.netty.buffer.ByteBuf
|
||||
import io.netty.channel.ChannelHandlerContext
|
||||
import io.netty.handler.codec.ByteToMessageDecoder
|
||||
|
||||
class ChecksumFrameDecoder(@Volatile var checksum: Checksum) : ByteToMessageDecoder() {
|
||||
|
||||
override fun decode(ctx: ChannelHandlerContext, buffer: ByteBuf, out: MutableList<Any>) {
|
||||
val checksum = this.checksum
|
||||
val tagSize = checksum.size
|
||||
val total = buffer.readableBytes()
|
||||
if (tagSize == 0) {
|
||||
out += buffer.readRetainedSlice(total)
|
||||
return
|
||||
}
|
||||
if (total < tagSize) {
|
||||
throw ChecksumMismatchException()
|
||||
}
|
||||
val payloadSize = total - tagSize
|
||||
val expected = ByteArray(tagSize)
|
||||
buffer.getBytes(buffer.readerIndex() + payloadSize, expected)
|
||||
val payload = buffer.slice(buffer.readerIndex(), payloadSize)
|
||||
if (!checksum.verify(payload, expected)) {
|
||||
buffer.skipBytes(total)
|
||||
throw ChecksumMismatchException()
|
||||
}
|
||||
out += payload.retain()
|
||||
buffer.skipBytes(total)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package de.fiereu.network.handlers
|
||||
|
||||
import de.fiereu.network.checksum.Checksum
|
||||
import io.netty.buffer.ByteBuf
|
||||
import io.netty.channel.ChannelHandlerContext
|
||||
import io.netty.handler.codec.MessageToByteEncoder
|
||||
|
||||
class ChecksumFrameEncoder(@Volatile var checksum: Checksum) : MessageToByteEncoder<ByteBuf>() {
|
||||
|
||||
override fun encode(ctx: ChannelHandlerContext, msg: ByteBuf, out: ByteBuf) {
|
||||
val checksum = this.checksum
|
||||
val len = msg.readableBytes()
|
||||
val tag = if (checksum.size > 0) checksum.calculate(msg) else null
|
||||
out.writeBytes(msg, msg.readerIndex(), len)
|
||||
if (tag != null) {
|
||||
out.writeBytes(tag)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package de.fiereu.network.handlers
|
||||
|
||||
import de.fiereu.network.cipher.SessionCipher
|
||||
import io.netty.buffer.ByteBuf
|
||||
import io.netty.channel.ChannelHandlerContext
|
||||
import io.netty.handler.codec.ByteToMessageDecoder
|
||||
|
||||
class CipherDecoder(@Volatile var cipher: SessionCipher) : ByteToMessageDecoder() {
|
||||
|
||||
override fun decode(ctx: ChannelHandlerContext, buffer: ByteBuf, out: MutableList<Any>) {
|
||||
val len = buffer.readableBytes()
|
||||
if (len == 0) return
|
||||
val output = ctx.alloc().buffer(len)
|
||||
try {
|
||||
cipher.decrypt(buffer, output)
|
||||
out += output.retain()
|
||||
} finally {
|
||||
output.release()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package de.fiereu.network.handlers
|
||||
|
||||
import de.fiereu.network.cipher.SessionCipher
|
||||
import io.netty.buffer.ByteBuf
|
||||
import io.netty.channel.ChannelHandlerContext
|
||||
import io.netty.handler.codec.MessageToByteEncoder
|
||||
|
||||
class CipherEncoder(@Volatile var cipher: SessionCipher) : MessageToByteEncoder<ByteBuf>() {
|
||||
|
||||
override fun encode(ctx: ChannelHandlerContext, msg: ByteBuf, out: ByteBuf) {
|
||||
cipher.encrypt(msg, out)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package de.fiereu.network.handlers
|
||||
|
||||
import io.netty.buffer.ByteBuf
|
||||
import io.netty.channel.ChannelHandlerContext
|
||||
import io.netty.handler.codec.ByteToMessageDecoder
|
||||
import java.util.zip.Inflater
|
||||
|
||||
class CompressionDecoder : ByteToMessageDecoder() {
|
||||
|
||||
private val inflater = Inflater(true)
|
||||
|
||||
override fun decode(ctx: ChannelHandlerContext, buffer: ByteBuf, out: MutableList<Any>) {
|
||||
if (buffer.readableBytes() < 2) return
|
||||
val opcode = buffer.readByte()
|
||||
val flag = buffer.readByte().toInt()
|
||||
val payloadLen = buffer.readableBytes()
|
||||
val output = ctx.alloc().buffer(payloadLen * 2 + 1)
|
||||
try {
|
||||
output.writeByte(opcode.toInt())
|
||||
if (flag == 0) {
|
||||
output.writeBytes(buffer, buffer.readerIndex(), payloadLen)
|
||||
buffer.skipBytes(payloadLen)
|
||||
} else {
|
||||
val input = ByteArray(payloadLen)
|
||||
buffer.readBytes(input)
|
||||
inflater.reset()
|
||||
inflater.setInput(input)
|
||||
val chunk = ByteArray(0x4000)
|
||||
while (!inflater.finished() && !inflater.needsInput()) {
|
||||
val written = inflater.inflate(chunk)
|
||||
if (written == 0) break
|
||||
output.writeBytes(chunk, 0, written)
|
||||
}
|
||||
if (output.readableBytes() >= 2) {
|
||||
output.writerIndex(output.writerIndex() - 2)
|
||||
}
|
||||
}
|
||||
out += output.retain()
|
||||
} finally {
|
||||
output.release()
|
||||
}
|
||||
}
|
||||
|
||||
override fun handlerRemoved0(ctx: ChannelHandlerContext) {
|
||||
inflater.end()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package de.fiereu.network.handlers
|
||||
|
||||
import io.netty.buffer.ByteBuf
|
||||
import io.netty.channel.ChannelHandlerContext
|
||||
import io.netty.handler.codec.MessageToByteEncoder
|
||||
import java.util.zip.Deflater
|
||||
|
||||
class CompressionEncoder(private val threshold: Int = 256) : MessageToByteEncoder<ByteBuf>() {
|
||||
|
||||
private val deflater = Deflater(Deflater.DEFAULT_COMPRESSION, true)
|
||||
|
||||
override fun encode(ctx: ChannelHandlerContext, msg: ByteBuf, out: ByteBuf) {
|
||||
if (msg.readableBytes() < 1) return
|
||||
val opcode = msg.readByte()
|
||||
out.writeByte(opcode.toInt())
|
||||
val payloadLen = msg.readableBytes()
|
||||
if (payloadLen < threshold) {
|
||||
out.writeByte(0)
|
||||
out.writeBytes(msg, msg.readerIndex(), payloadLen)
|
||||
msg.skipBytes(payloadLen)
|
||||
return
|
||||
}
|
||||
val input = ByteArray(payloadLen + 2)
|
||||
msg.getBytes(msg.readerIndex(), input, 0, payloadLen)
|
||||
input[payloadLen] = 0xFF.toByte()
|
||||
input[payloadLen + 1] = 0xFF.toByte()
|
||||
msg.skipBytes(payloadLen)
|
||||
out.writeByte(1)
|
||||
deflater.reset()
|
||||
deflater.setInput(input)
|
||||
val chunk = ByteArray(0x4000)
|
||||
while (true) {
|
||||
val written = deflater.deflate(chunk, 0, chunk.size, Deflater.SYNC_FLUSH)
|
||||
if (written == 0) break
|
||||
out.writeBytes(chunk, 0, written)
|
||||
}
|
||||
}
|
||||
|
||||
override fun handlerRemoved(ctx: ChannelHandlerContext) {
|
||||
deflater.end()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package de.fiereu.network.handlers
|
||||
|
||||
import io.netty.handler.codec.LengthFieldBasedFrameDecoder
|
||||
import java.nio.ByteOrder
|
||||
|
||||
class PacketFrameDecoder(maxFrameLength: Int = 0xFFFF) :
|
||||
LengthFieldBasedFrameDecoder(
|
||||
ByteOrder.LITTLE_ENDIAN,
|
||||
maxFrameLength,
|
||||
0,
|
||||
UShort.SIZE_BYTES,
|
||||
-UShort.SIZE_BYTES,
|
||||
UShort.SIZE_BYTES,
|
||||
false,
|
||||
)
|
||||
@@ -0,0 +1,12 @@
|
||||
package de.fiereu.network.handlers
|
||||
|
||||
import io.netty.handler.codec.LengthFieldPrepender
|
||||
import java.nio.ByteOrder
|
||||
|
||||
class PacketFrameEncoder :
|
||||
LengthFieldPrepender(
|
||||
ByteOrder.LITTLE_ENDIAN,
|
||||
UShort.SIZE_BYTES,
|
||||
0,
|
||||
true,
|
||||
)
|
||||
@@ -0,0 +1,76 @@
|
||||
package de.fiereu.network.handshake
|
||||
|
||||
import de.fiereu.network.InvalidServerSignatureException
|
||||
import de.fiereu.network.PipelineNames
|
||||
import de.fiereu.network.PipelineOptions
|
||||
import de.fiereu.network.Protocol
|
||||
import de.fiereu.network.ProtocolHandler
|
||||
import de.fiereu.network.SessionPhase
|
||||
import de.fiereu.network.Side
|
||||
import de.fiereu.network.TypedProtocolHandler
|
||||
import de.fiereu.network.cipher.AesCtrSessionCipher
|
||||
import de.fiereu.network.handlers.ChecksumFrameDecoder
|
||||
import de.fiereu.network.handlers.ChecksumFrameEncoder
|
||||
import de.fiereu.network.handlers.CipherDecoder
|
||||
import de.fiereu.network.handlers.CipherEncoder
|
||||
import de.fiereu.network.handlers.CompressionDecoder
|
||||
import de.fiereu.network.internal.MutableSessionContext
|
||||
import io.github.oshai.kotlinlogging.KotlinLogging
|
||||
import java.security.interfaces.ECPublicKey
|
||||
|
||||
private val log = KotlinLogging.logger {}
|
||||
|
||||
internal class ClientSessionHandshakeHandler(
|
||||
private val rootPublic: ECPublicKey,
|
||||
private val applicationProtocol: Protocol,
|
||||
private val applicationHandlerFactory: () -> ProtocolHandler,
|
||||
private val options: PipelineOptions,
|
||||
) : TypedProtocolHandler<SessionHandshakeProtocol>(SessionHandshakeProtocol, Side.CLIENT) {
|
||||
|
||||
private val ephemeralKeyPair = EcKeys.generateEphemeralKeyPair()
|
||||
|
||||
override fun onActive() {
|
||||
session.send(ClientHelloPacket(timestamp = System.currentTimeMillis()))
|
||||
}
|
||||
|
||||
init {
|
||||
on<ServerHelloPacket> { event ->
|
||||
val publicBytes = EcKeys.toUncompressedPoint(event.packet.ephemeralPublic)
|
||||
if (!EcKeys.verify(rootPublic, publicBytes, event.packet.signature)) {
|
||||
throw InvalidServerSignatureException()
|
||||
}
|
||||
val crypto =
|
||||
SessionCryptoState.derive(
|
||||
localPrivate = ephemeralKeyPair.private,
|
||||
remotePublic = event.packet.ephemeralPublic,
|
||||
role = AesCtrSessionCipher.Role.CLIENT,
|
||||
checksumSize = event.packet.checksumSize,
|
||||
)
|
||||
event.session.send(
|
||||
ClientReadyPacket(ephemeralPublic = ephemeralKeyPair.public as ECPublicKey),
|
||||
)
|
||||
val pipeline = event.session.channel.pipeline()
|
||||
(pipeline.get(PipelineNames.CHECKSUM_DECODER) as ChecksumFrameDecoder).checksum =
|
||||
crypto.incomingChecksum
|
||||
(pipeline.get(PipelineNames.CHECKSUM_ENCODER) as ChecksumFrameEncoder).checksum =
|
||||
crypto.outgoingChecksum
|
||||
(pipeline.get(PipelineNames.CIPHER_DECODER) as CipherDecoder).cipher = crypto.cipher
|
||||
(pipeline.get(PipelineNames.CIPHER_ENCODER) as CipherEncoder).cipher = crypto.cipher
|
||||
if (applicationProtocol.compressed) {
|
||||
pipeline.addBefore(
|
||||
PipelineNames.PROTOCOL_HANDLER,
|
||||
PipelineNames.COMPRESSION_DECODER,
|
||||
CompressionDecoder(),
|
||||
)
|
||||
}
|
||||
val appHandler = applicationHandlerFactory()
|
||||
pipeline.replace(
|
||||
PipelineNames.PROTOCOL_HANDLER,
|
||||
PipelineNames.PROTOCOL_HANDLER,
|
||||
appHandler,
|
||||
)
|
||||
(event.session as MutableSessionContext).transitionTo(SessionPhase.ESTABLISHED)
|
||||
log.debug { "Client handshake complete with ${event.session.remoteAddress}" }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package de.fiereu.network.handshake
|
||||
|
||||
import java.math.BigInteger
|
||||
import java.security.AlgorithmParameters
|
||||
import java.security.KeyFactory
|
||||
import java.security.KeyPair
|
||||
import java.security.KeyPairGenerator
|
||||
import java.security.Signature
|
||||
import java.security.interfaces.ECPrivateKey
|
||||
import java.security.interfaces.ECPublicKey
|
||||
import java.security.spec.ECGenParameterSpec
|
||||
import java.security.spec.ECParameterSpec
|
||||
import java.security.spec.ECPoint
|
||||
import java.security.spec.ECPublicKeySpec
|
||||
|
||||
internal object EcKeys {
|
||||
private const val UNCOMPRESSED_INDICATOR: Byte = 0x04
|
||||
private const val CURVE = "secp256r1"
|
||||
private val keyFactory = KeyFactory.getInstance("EC")
|
||||
private val parameters: ECParameterSpec by lazy {
|
||||
val params = AlgorithmParameters.getInstance("EC")
|
||||
params.init(ECGenParameterSpec(CURVE))
|
||||
params.getParameterSpec(ECParameterSpec::class.java)
|
||||
}
|
||||
private val keyByteLength: Int by lazy {
|
||||
(parameters.order.bitLength() + Byte.SIZE_BITS - 1) / Byte.SIZE_BITS
|
||||
}
|
||||
|
||||
fun generateEphemeralKeyPair(): KeyPair {
|
||||
val gen = KeyPairGenerator.getInstance("EC")
|
||||
gen.initialize(ECGenParameterSpec(CURVE))
|
||||
return gen.generateKeyPair()
|
||||
}
|
||||
|
||||
fun toUncompressedPoint(key: ECPublicKey): ByteArray {
|
||||
val point = key.w
|
||||
val keyLength = keyByteLength
|
||||
val data = ByteArray(1 + 2 * keyLength)
|
||||
data[0] = UNCOMPRESSED_INDICATOR
|
||||
writeFieldInto(data, 1, point.affineX.toByteArray(), keyLength)
|
||||
writeFieldInto(data, 1 + keyLength, point.affineY.toByteArray(), keyLength)
|
||||
return data
|
||||
}
|
||||
|
||||
fun fromUncompressedPoint(bytes: ByteArray): ECPublicKey {
|
||||
require(bytes.isNotEmpty() && bytes[0] == UNCOMPRESSED_INDICATOR) {
|
||||
"Invalid uncompressed point indicator"
|
||||
}
|
||||
val keyLength = keyByteLength
|
||||
require(bytes.size == 1 + 2 * keyLength) { "Invalid EC point length: ${bytes.size}" }
|
||||
val x = BigInteger(1, bytes.copyOfRange(1, 1 + keyLength))
|
||||
val y = BigInteger(1, bytes.copyOfRange(1 + keyLength, 1 + 2 * keyLength))
|
||||
return keyFactory.generatePublic(ECPublicKeySpec(ECPoint(x, y), parameters)) as ECPublicKey
|
||||
}
|
||||
|
||||
private fun writeFieldInto(dst: ByteArray, offset: Int, src: ByteArray, length: Int) {
|
||||
when {
|
||||
src.size <= length -> System.arraycopy(src, 0, dst, offset + length - src.size, src.size)
|
||||
src.size == length + 1 && src[0] == 0.toByte() ->
|
||||
System.arraycopy(src, 1, dst, offset, length)
|
||||
else -> error("EC coordinate too large: ${src.size}")
|
||||
}
|
||||
}
|
||||
|
||||
fun sign(privateKey: ECPrivateKey, data: ByteArray): ByteArray {
|
||||
val sig = Signature.getInstance("SHA256withECDSA")
|
||||
sig.initSign(privateKey)
|
||||
sig.update(data)
|
||||
return sig.sign()
|
||||
}
|
||||
|
||||
fun verify(publicKey: ECPublicKey, data: ByteArray, signature: ByteArray): Boolean {
|
||||
val sig = Signature.getInstance("SHA256withECDSA")
|
||||
sig.initVerify(publicKey)
|
||||
sig.update(data)
|
||||
return sig.verify(signature)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package de.fiereu.network.handshake
|
||||
|
||||
import de.fiereu.bytecodec.CodecScope
|
||||
import de.fiereu.bytecodec.PacketCodec
|
||||
import de.fiereu.bytecodec.S64LE
|
||||
import de.fiereu.bytecodec.U16LE
|
||||
import de.fiereu.bytecodec.U8
|
||||
import de.fiereu.bytecodec.bytesPrefixed
|
||||
import java.security.interfaces.ECPublicKey
|
||||
import kotlin.random.Random
|
||||
|
||||
private const val XOR_KEY_RANDOM = 3214621489648854472L
|
||||
private const val XOR_KEY_TIMESTAMP = -4214651440992349575L
|
||||
|
||||
data class ClientHelloPacket(val timestamp: Long)
|
||||
|
||||
data class ServerHelloPacket(
|
||||
val ephemeralPublic: ECPublicKey,
|
||||
val signature: ByteArray,
|
||||
val checksumSize: Int,
|
||||
) {
|
||||
override fun equals(other: Any?): Boolean =
|
||||
other is ServerHelloPacket &&
|
||||
ephemeralPublic == other.ephemeralPublic &&
|
||||
signature.contentEquals(other.signature) &&
|
||||
checksumSize == other.checksumSize
|
||||
|
||||
override fun hashCode(): Int =
|
||||
(ephemeralPublic.hashCode() * 31 + signature.contentHashCode()) * 31 + checksumSize
|
||||
}
|
||||
|
||||
data class ClientReadyPacket(val ephemeralPublic: ECPublicKey)
|
||||
|
||||
object ClientHelloCodec : PacketCodec<ClientHelloPacket>() {
|
||||
override fun CodecScope<ClientHelloPacket>.body(): ClientHelloPacket {
|
||||
var random = 0L
|
||||
val xoredRandom =
|
||||
field(S64LE) {
|
||||
random = Random.nextLong()
|
||||
random xor XOR_KEY_RANDOM
|
||||
}
|
||||
val xoredTimestamp = field(S64LE) { it.timestamp xor XOR_KEY_TIMESTAMP xor random }
|
||||
val readRandom = xoredRandom xor XOR_KEY_RANDOM
|
||||
val timestamp = xoredTimestamp xor XOR_KEY_TIMESTAMP xor readRandom
|
||||
return ClientHelloPacket(timestamp)
|
||||
}
|
||||
}
|
||||
|
||||
private val LengthPrefixedBytes = bytesPrefixed(U16LE)
|
||||
|
||||
object ServerHelloCodec : PacketCodec<ServerHelloPacket>() {
|
||||
override fun CodecScope<ServerHelloPacket>.body(): ServerHelloPacket {
|
||||
val pubKey = field(LengthPrefixedBytes) { EcKeys.toUncompressedPoint(it.ephemeralPublic) }
|
||||
val signature = field(LengthPrefixedBytes, ServerHelloPacket::signature)
|
||||
val checksumSize = field(U8, ServerHelloPacket::checksumSize)
|
||||
return ServerHelloPacket(
|
||||
ephemeralPublic = EcKeys.fromUncompressedPoint(pubKey),
|
||||
signature = signature,
|
||||
checksumSize = checksumSize,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
object ClientReadyCodec : PacketCodec<ClientReadyPacket>() {
|
||||
override fun CodecScope<ClientReadyPacket>.body(): ClientReadyPacket {
|
||||
val bytes = field(LengthPrefixedBytes) { EcKeys.toUncompressedPoint(it.ephemeralPublic) }
|
||||
return ClientReadyPacket(EcKeys.fromUncompressedPoint(bytes))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package de.fiereu.network.handshake
|
||||
|
||||
import de.fiereu.network.PipelineNames
|
||||
import de.fiereu.network.PipelineOptions
|
||||
import de.fiereu.network.Protocol
|
||||
import de.fiereu.network.ProtocolHandler
|
||||
import de.fiereu.network.SessionPhase
|
||||
import de.fiereu.network.Side
|
||||
import de.fiereu.network.StaleClientHelloException
|
||||
import de.fiereu.network.TypedProtocolHandler
|
||||
import de.fiereu.network.cipher.AesCtrSessionCipher
|
||||
import de.fiereu.network.handlers.ChecksumFrameDecoder
|
||||
import de.fiereu.network.handlers.ChecksumFrameEncoder
|
||||
import de.fiereu.network.handlers.CipherDecoder
|
||||
import de.fiereu.network.handlers.CipherEncoder
|
||||
import de.fiereu.network.handlers.CompressionEncoder
|
||||
import de.fiereu.network.internal.MutableSessionContext
|
||||
import io.github.oshai.kotlinlogging.KotlinLogging
|
||||
import java.security.interfaces.ECPrivateKey
|
||||
import kotlin.math.abs
|
||||
|
||||
private val log = KotlinLogging.logger {}
|
||||
|
||||
internal class ServerSessionHandshakeHandler(
|
||||
private val rootPrivate: ECPrivateKey,
|
||||
private val applicationProtocol: Protocol,
|
||||
private val applicationHandlerFactory: () -> ProtocolHandler,
|
||||
private val options: PipelineOptions,
|
||||
) : TypedProtocolHandler<SessionHandshakeProtocol>(SessionHandshakeProtocol, Side.SERVER) {
|
||||
|
||||
private val ephemeralKeyPair = EcKeys.generateEphemeralKeyPair()
|
||||
|
||||
init {
|
||||
on<ClientHelloPacket> { event ->
|
||||
val skew = abs(System.currentTimeMillis() - event.packet.timestamp)
|
||||
if (skew > options.maxHelloSkew.inWholeMilliseconds) {
|
||||
throw StaleClientHelloException(skew)
|
||||
}
|
||||
val publicBytes =
|
||||
EcKeys.toUncompressedPoint(
|
||||
ephemeralKeyPair.public as java.security.interfaces.ECPublicKey,
|
||||
)
|
||||
val signature = EcKeys.sign(rootPrivate, publicBytes)
|
||||
event.session.send(
|
||||
ServerHelloPacket(
|
||||
ephemeralPublic = ephemeralKeyPair.public as java.security.interfaces.ECPublicKey,
|
||||
signature = signature,
|
||||
checksumSize = options.checksumSize,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
on<ClientReadyPacket> { event ->
|
||||
val crypto =
|
||||
SessionCryptoState.derive(
|
||||
localPrivate = ephemeralKeyPair.private,
|
||||
remotePublic = event.packet.ephemeralPublic,
|
||||
role = AesCtrSessionCipher.Role.SERVER,
|
||||
checksumSize = options.checksumSize,
|
||||
)
|
||||
val pipeline = event.session.channel.pipeline()
|
||||
(pipeline.get(PipelineNames.CHECKSUM_DECODER) as ChecksumFrameDecoder).checksum =
|
||||
crypto.incomingChecksum
|
||||
(pipeline.get(PipelineNames.CHECKSUM_ENCODER) as ChecksumFrameEncoder).checksum =
|
||||
crypto.outgoingChecksum
|
||||
(pipeline.get(PipelineNames.CIPHER_DECODER) as CipherDecoder).cipher = crypto.cipher
|
||||
(pipeline.get(PipelineNames.CIPHER_ENCODER) as CipherEncoder).cipher = crypto.cipher
|
||||
if (applicationProtocol.compressed) {
|
||||
pipeline.addBefore(
|
||||
PipelineNames.PROTOCOL_HANDLER,
|
||||
PipelineNames.COMPRESSION_ENCODER,
|
||||
CompressionEncoder(options.compressionThreshold),
|
||||
)
|
||||
}
|
||||
val appHandler = applicationHandlerFactory()
|
||||
pipeline.replace(
|
||||
PipelineNames.PROTOCOL_HANDLER,
|
||||
PipelineNames.PROTOCOL_HANDLER,
|
||||
appHandler,
|
||||
)
|
||||
(event.session as MutableSessionContext).transitionTo(SessionPhase.ESTABLISHED)
|
||||
log.debug { "Handshake complete for ${event.session.remoteAddress}" }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package de.fiereu.network.handshake
|
||||
|
||||
import de.fiereu.network.checksum.Checksum
|
||||
import de.fiereu.network.checksum.ChecksumFactory
|
||||
import de.fiereu.network.cipher.AesCtrSessionCipher
|
||||
import de.fiereu.network.cipher.SessionCipher
|
||||
import java.security.PrivateKey
|
||||
import java.security.PublicKey
|
||||
|
||||
internal class SessionCryptoState(
|
||||
val cipher: SessionCipher,
|
||||
val incomingChecksum: Checksum,
|
||||
val outgoingChecksum: Checksum,
|
||||
) {
|
||||
companion object {
|
||||
fun derive(
|
||||
localPrivate: PrivateKey,
|
||||
remotePublic: PublicKey,
|
||||
role: AesCtrSessionCipher.Role,
|
||||
checksumSize: Int,
|
||||
): SessionCryptoState {
|
||||
val secret = AesCtrSessionCipher.ecdh(localPrivate, remotePublic)
|
||||
val cipher = AesCtrSessionCipher.derive(secret, role)
|
||||
val (outSeed, inSeed) = AesCtrSessionCipher.directionalSeeds(secret, role)
|
||||
return SessionCryptoState(
|
||||
cipher = cipher,
|
||||
incomingChecksum = ChecksumFactory.create(checksumSize, inSeed),
|
||||
outgoingChecksum = ChecksumFactory.create(checksumSize, outSeed),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package de.fiereu.network.handshake
|
||||
|
||||
import de.fiereu.network.Protocol
|
||||
|
||||
object SessionHandshakeProtocol : Protocol() {
|
||||
init {
|
||||
bidi(0x00u, ClientHelloCodec, ClientHelloPacket::class)
|
||||
bidi(0x01u, ServerHelloCodec, ServerHelloPacket::class)
|
||||
bidi(0x02u, ClientReadyCodec, ClientReadyPacket::class)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package de.fiereu.network.internal
|
||||
|
||||
import de.fiereu.network.Protocol
|
||||
import de.fiereu.network.SessionAttribute
|
||||
import de.fiereu.network.SessionAttributes
|
||||
import de.fiereu.network.SessionContext
|
||||
import de.fiereu.network.SessionPhase
|
||||
import de.fiereu.network.Side
|
||||
import io.github.oshai.kotlinlogging.KotlinLogging
|
||||
import io.netty.channel.Channel
|
||||
import io.netty.channel.ChannelFuture
|
||||
import io.netty.util.AttributeKey
|
||||
import java.net.SocketAddress
|
||||
import java.time.Instant
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
private val log = KotlinLogging.logger {}
|
||||
|
||||
internal val SESSION_KEY: AttributeKey<MutableSessionContext> =
|
||||
AttributeKey.valueOf("de.fiereu.network.session")
|
||||
|
||||
internal class MutableSessionContext(
|
||||
override val side: Side,
|
||||
override val channel: Channel,
|
||||
internal val applicationProtocol: Protocol,
|
||||
) : SessionContext {
|
||||
|
||||
override val remoteAddress: SocketAddress
|
||||
get() = channel.remoteAddress()
|
||||
|
||||
@Volatile
|
||||
override var phase: SessionPhase = SessionPhase.HANDSHAKE
|
||||
private set
|
||||
|
||||
@Volatile
|
||||
override var handshakeCompletedAt: Instant? = null
|
||||
private set
|
||||
|
||||
override val attributes: SessionAttributes = ConcurrentAttributes()
|
||||
|
||||
private val listenersLock = Any()
|
||||
private val listeners = mutableMapOf<SessionPhase, MutableList<() -> Unit>>()
|
||||
|
||||
internal fun transitionTo(next: SessionPhase) {
|
||||
val toFire: List<() -> Unit>
|
||||
synchronized(listenersLock) {
|
||||
if (phase == next) return
|
||||
phase = next
|
||||
if (next == SessionPhase.ESTABLISHED) {
|
||||
handshakeCompletedAt = Instant.now()
|
||||
}
|
||||
toFire = listeners[next]?.toList() ?: emptyList()
|
||||
}
|
||||
for (listener in toFire) {
|
||||
try {
|
||||
listener()
|
||||
} catch (t: Throwable) {
|
||||
log.warn(t) { "Phase listener for $next threw" }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun send(packet: Any): ChannelFuture = channel.writeAndFlush(packet)
|
||||
|
||||
override fun close(reason: () -> String) {
|
||||
val message = reason()
|
||||
log.debug { "Closing session $remoteAddress: $message" }
|
||||
channel.close()
|
||||
}
|
||||
|
||||
override fun onPhase(phase: SessionPhase, listener: () -> Unit) {
|
||||
val fireNow: Boolean
|
||||
synchronized(listenersLock) {
|
||||
if (this.phase == phase) {
|
||||
fireNow = true
|
||||
} else {
|
||||
fireNow = false
|
||||
listeners.getOrPut(phase) { mutableListOf() } += listener
|
||||
}
|
||||
}
|
||||
if (fireNow) {
|
||||
listener()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal data class OutgoingPacket(
|
||||
val registration: Protocol.Registration<*>,
|
||||
val value: Any,
|
||||
)
|
||||
|
||||
private class ConcurrentAttributes : SessionAttributes {
|
||||
private val map = ConcurrentHashMap<SessionAttribute<*>, Any>()
|
||||
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
override fun <T : Any> get(key: SessionAttribute<T>): T? = map[key] as T?
|
||||
|
||||
override fun <T : Any> set(key: SessionAttribute<T>, value: T) {
|
||||
map[key] = value
|
||||
}
|
||||
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
override fun <T : Any> remove(key: SessionAttribute<T>): T? = map.remove(key) as T?
|
||||
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
override fun <T : Any> getOrPut(key: SessionAttribute<T>, default: () -> T): T =
|
||||
map.getOrPut(key) { default() } as T
|
||||
|
||||
override fun contains(key: SessionAttribute<*>): Boolean = map.containsKey(key)
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package de.fiereu.network
|
||||
|
||||
import io.kotest.core.spec.style.FunSpec
|
||||
import io.kotest.matchers.shouldBe
|
||||
import io.netty.buffer.Unpooled
|
||||
|
||||
class NettyBuffersTest :
|
||||
FunSpec({
|
||||
test("NettyReadBuffer matches ByteBuf state") {
|
||||
val buf = Unpooled.wrappedBuffer(byteArrayOf(1, 2, 3, 4))
|
||||
val read = NettyReadBuffer(buf)
|
||||
read.readByte() shouldBe 1
|
||||
read.remaining() shouldBe 3
|
||||
val dst = ByteArray(2)
|
||||
read.readBytes(dst)
|
||||
dst shouldBe byteArrayOf(2, 3)
|
||||
read.skip(1)
|
||||
read.remaining() shouldBe 0
|
||||
}
|
||||
|
||||
test("NettyWriteBuffer writes through to ByteBuf") {
|
||||
val buf = Unpooled.buffer()
|
||||
val write = NettyWriteBuffer(buf)
|
||||
write.writeByte(0xAB.toByte())
|
||||
write.writeBytes(byteArrayOf(0xCD.toByte(), 0xEF.toByte()))
|
||||
val read = ByteArray(3)
|
||||
buf.readBytes(read)
|
||||
read shouldBe byteArrayOf(0xAB.toByte(), 0xCD.toByte(), 0xEF.toByte())
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,73 @@
|
||||
package de.fiereu.network
|
||||
|
||||
import de.fiereu.bytecodec.CodecScope
|
||||
import de.fiereu.bytecodec.PacketCodec
|
||||
import de.fiereu.bytecodec.U16LE
|
||||
import de.fiereu.bytecodec.U8
|
||||
import io.kotest.assertions.throwables.shouldThrow
|
||||
import io.kotest.core.spec.style.FunSpec
|
||||
import io.kotest.matchers.shouldBe
|
||||
|
||||
private data class Hello(val n: Int)
|
||||
|
||||
private data class World(val n: Int)
|
||||
|
||||
private object HelloCodec : PacketCodec<Hello>() {
|
||||
override fun CodecScope<Hello>.body() = Hello(field(U16LE, Hello::n))
|
||||
}
|
||||
|
||||
private object WorldCodec : PacketCodec<World>() {
|
||||
override fun CodecScope<World>.body() = World(field(U8, World::n))
|
||||
}
|
||||
|
||||
private data class Beep(val n: Int)
|
||||
|
||||
private object BeepCodec : PacketCodec<Beep>() {
|
||||
override fun CodecScope<Beep>.body() = Beep(field(U16LE, Beep::n))
|
||||
}
|
||||
|
||||
private object SampleProtocol : Protocol() {
|
||||
init {
|
||||
c2s<Hello>(0x10u, HelloCodec)
|
||||
s2c<World>(0x20u, WorldCodec)
|
||||
bidi<Beep>(0x30u, BeepCodec)
|
||||
}
|
||||
}
|
||||
|
||||
class ProtocolTest :
|
||||
FunSpec({
|
||||
test("incoming lookup depends on side") {
|
||||
SampleProtocol.incomingCodec(Side.SERVER, 0x10u) shouldBe HelloCodec
|
||||
SampleProtocol.incomingCodec(Side.CLIENT, 0x10u) shouldBe null
|
||||
SampleProtocol.incomingCodec(Side.CLIENT, 0x20u) shouldBe WorldCodec
|
||||
}
|
||||
|
||||
test("outgoing lookup depends on side") {
|
||||
SampleProtocol.outgoingRegistration(Side.CLIENT, Hello::class)?.opcode shouldBe 0x10u
|
||||
SampleProtocol.outgoingRegistration(Side.SERVER, World::class)?.opcode shouldBe 0x20u
|
||||
}
|
||||
|
||||
test("bidi registers both directions") {
|
||||
SampleProtocol.incomingCodec(Side.SERVER, 0x30u) shouldBe BeepCodec
|
||||
SampleProtocol.incomingCodec(Side.CLIENT, 0x30u) shouldBe BeepCodec
|
||||
SampleProtocol.outgoingRegistration(Side.SERVER, Beep::class)?.opcode shouldBe 0x30u
|
||||
SampleProtocol.outgoingRegistration(Side.CLIENT, Beep::class)?.opcode shouldBe 0x30u
|
||||
}
|
||||
|
||||
test("duplicate registration throws") {
|
||||
shouldThrow<IllegalStateException> {
|
||||
object : Protocol() {
|
||||
init {
|
||||
c2s<Hello>(0x01u, HelloCodec)
|
||||
c2s<Hello>(0x02u, HelloCodec)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
test("Direction.isIncomingFor") {
|
||||
Direction.C2S.isIncomingFor(Side.SERVER) shouldBe true
|
||||
Direction.C2S.isIncomingFor(Side.CLIENT) shouldBe false
|
||||
Direction.S2C.isIncomingFor(Side.CLIENT) shouldBe true
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,133 @@
|
||||
package de.fiereu.network
|
||||
|
||||
import de.fiereu.bytecodec.CodecScope
|
||||
import de.fiereu.bytecodec.PacketCodec
|
||||
import de.fiereu.bytecodec.U16LE
|
||||
import de.fiereu.network.internal.MutableSessionContext
|
||||
import de.fiereu.network.internal.OutgoingPacket
|
||||
import de.fiereu.network.internal.SESSION_KEY
|
||||
import io.kotest.assertions.throwables.shouldThrow
|
||||
import io.kotest.core.spec.style.FunSpec
|
||||
import io.kotest.matchers.shouldBe
|
||||
import io.netty.buffer.ByteBuf
|
||||
import io.netty.buffer.Unpooled
|
||||
import io.netty.channel.embedded.EmbeddedChannel
|
||||
|
||||
private data class Ping(val n: Int)
|
||||
|
||||
private data class Pong(val n: Int)
|
||||
|
||||
private object PingCodec : PacketCodec<Ping>() {
|
||||
override fun CodecScope<Ping>.body() = Ping(field(U16LE, Ping::n))
|
||||
}
|
||||
|
||||
private object PongCodec : PacketCodec<Pong>() {
|
||||
override fun CodecScope<Pong>.body() = Pong(field(U16LE, Pong::n))
|
||||
}
|
||||
|
||||
private object PingPongProtocol : Protocol() {
|
||||
init {
|
||||
c2s<Ping>(0xA0u, PingCodec)
|
||||
s2c<Pong>(0xA1u, PongCodec)
|
||||
}
|
||||
}
|
||||
|
||||
private class ServerHandler :
|
||||
TypedProtocolHandler<PingPongProtocol>(PingPongProtocol, Side.SERVER) {
|
||||
val seen = mutableListOf<Ping>()
|
||||
|
||||
init {
|
||||
on<Ping> { event ->
|
||||
seen += event.packet
|
||||
event.session.send(Pong(event.packet.n + 1))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun channelWithHandler(handler: ProtocolHandler): EmbeddedChannel {
|
||||
val channel = EmbeddedChannel()
|
||||
val session = MutableSessionContext(handler.side, channel, handler.protocol)
|
||||
channel.attr(SESSION_KEY).set(session)
|
||||
channel.pipeline().addLast(PipelineNames.PROTOCOL_HANDLER, handler)
|
||||
return channel
|
||||
}
|
||||
|
||||
class TypedProtocolHandlerTest :
|
||||
FunSpec({
|
||||
test("incoming bytes dispatch to on<T>") {
|
||||
val handler = ServerHandler()
|
||||
val channel = channelWithHandler(handler)
|
||||
channel.writeInbound(Unpooled.wrappedBuffer(byteArrayOf(0xA0.toByte(), 0x05, 0x00)))
|
||||
handler.seen shouldBe listOf(Ping(5))
|
||||
val out = channel.readOutbound<ByteBuf>()
|
||||
out.readUnsignedByte().toInt() shouldBe 0xA1
|
||||
out.readUnsignedShortLE() shouldBe 6
|
||||
}
|
||||
|
||||
test("session.send writes through the handler") {
|
||||
val handler = ServerHandler()
|
||||
val channel = channelWithHandler(handler)
|
||||
val session = channel.attr(SESSION_KEY).get()
|
||||
session.send(Pong(42))
|
||||
val out = channel.readOutbound<ByteBuf>()
|
||||
out.readUnsignedByte().toInt() shouldBe 0xA1
|
||||
out.readUnsignedShortLE() shouldBe 42
|
||||
}
|
||||
|
||||
test("unknown opcode is logged but channel stays open") {
|
||||
val handler = ServerHandler()
|
||||
val channel = channelWithHandler(handler)
|
||||
channel.writeInbound(Unpooled.wrappedBuffer(byteArrayOf(0xFE.toByte())))
|
||||
channel.isOpen shouldBe true
|
||||
}
|
||||
|
||||
test("unhandled packet logs but keeps the channel open") {
|
||||
val protocol =
|
||||
object : Protocol() {
|
||||
init {
|
||||
c2s<Ping>(0xB0u, PingCodec)
|
||||
c2s<Pong>(0xB1u, PongCodec)
|
||||
}
|
||||
}
|
||||
class OnlyPingHandler : TypedProtocolHandler<Protocol>(protocol, Side.SERVER) {
|
||||
init {
|
||||
on<Ping> { /* no-op */ }
|
||||
}
|
||||
}
|
||||
val handler = OnlyPingHandler()
|
||||
val channel = channelWithHandler(handler)
|
||||
channel.writeInbound(Unpooled.wrappedBuffer(byteArrayOf(0xB1.toByte(), 0x01, 0x00)))
|
||||
channel.isOpen shouldBe true
|
||||
}
|
||||
|
||||
test("duplicate handler registration throws") {
|
||||
shouldThrow<HandlerRegistrationException> {
|
||||
object : TypedProtocolHandler<PingPongProtocol>(PingPongProtocol, Side.SERVER) {
|
||||
init {
|
||||
on<Ping> {}
|
||||
on<Ping> {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
test("attributes survive on a session") {
|
||||
val handler = ServerHandler()
|
||||
val channel = channelWithHandler(handler)
|
||||
val session = channel.attr(SESSION_KEY).get()
|
||||
val key = SessionAttribute.of<Long>("userId")
|
||||
session.attributes[key] = 42L
|
||||
session.attributes[key] shouldBe 42L
|
||||
session.attributes.contains(key) shouldBe true
|
||||
}
|
||||
|
||||
test("OutgoingPacket goes through ProtocolHandler.write") {
|
||||
val handler = ServerHandler()
|
||||
val channel = channelWithHandler(handler)
|
||||
val reg = PingPongProtocol.outgoingRegistration(Side.SERVER, Pong::class)!!
|
||||
channel.writeOutbound(OutgoingPacket(reg, Pong(7)))
|
||||
val out = channel.readOutbound<ByteBuf>()
|
||||
out.readUnsignedByte().toInt() shouldBe 0xA1
|
||||
out.readUnsignedShortLE() shouldBe 7
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,42 @@
|
||||
package de.fiereu.network.checksum
|
||||
|
||||
import io.kotest.core.spec.style.FunSpec
|
||||
import io.kotest.matchers.shouldBe
|
||||
import io.netty.buffer.Unpooled
|
||||
|
||||
class ChecksumTest :
|
||||
FunSpec({
|
||||
test("NoOp produces empty tag") {
|
||||
NoOpChecksum.size shouldBe 0
|
||||
NoOpChecksum.calculate(Unpooled.wrappedBuffer(byteArrayOf(1, 2, 3))).size shouldBe 0
|
||||
NoOpChecksum.verify(Unpooled.wrappedBuffer(byteArrayOf(1, 2, 3)), ByteArray(0)) shouldBe
|
||||
true
|
||||
}
|
||||
|
||||
test("CRC16 verify matches calculate") {
|
||||
val c = Crc16Checksum()
|
||||
val data = byteArrayOf(0x10, 0x20, 0x30, 0x40, 0x50)
|
||||
val tag = c.calculate(Unpooled.wrappedBuffer(data))
|
||||
tag.size shouldBe 2
|
||||
Crc16Checksum().verify(Unpooled.wrappedBuffer(data), tag) shouldBe true
|
||||
Crc16Checksum().verify(Unpooled.wrappedBuffer(byteArrayOf(0, 0)), tag) shouldBe false
|
||||
}
|
||||
|
||||
test("HMAC-SHA256 round counter advances on every verify") {
|
||||
val key = ByteArray(16) { it.toByte() }
|
||||
val calc = HmacSha256Checksum(8, key)
|
||||
val ver = HmacSha256Checksum(8, key)
|
||||
val data = byteArrayOf(0xAA.toByte(), 0xBB.toByte(), 0xCC.toByte())
|
||||
val tag0 = calc.calculate(Unpooled.wrappedBuffer(data))
|
||||
val tag1 = calc.calculate(Unpooled.wrappedBuffer(data))
|
||||
tag0.contentEquals(tag1) shouldBe false
|
||||
ver.verify(Unpooled.wrappedBuffer(data), tag0) shouldBe true
|
||||
ver.verify(Unpooled.wrappedBuffer(data), tag1) shouldBe true
|
||||
}
|
||||
|
||||
test("ChecksumFactory dispatches on size") {
|
||||
ChecksumFactory.create(0).size shouldBe 0
|
||||
ChecksumFactory.create(2).size shouldBe 2
|
||||
ChecksumFactory.create(8, ByteArray(16)).size shouldBe 8
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,47 @@
|
||||
package de.fiereu.network.cipher
|
||||
|
||||
import de.fiereu.network.handshake.EcKeys
|
||||
import io.kotest.core.spec.style.FunSpec
|
||||
import io.kotest.matchers.shouldBe
|
||||
import io.netty.buffer.Unpooled
|
||||
|
||||
class AesCtrSessionCipherTest :
|
||||
FunSpec({
|
||||
test("derived ciphers interoperate across roles") {
|
||||
val serverEphemeral = EcKeys.generateEphemeralKeyPair()
|
||||
val clientEphemeral = EcKeys.generateEphemeralKeyPair()
|
||||
|
||||
val serverCipher =
|
||||
AesCtrSessionCipher.derive(
|
||||
localPrivate = serverEphemeral.private,
|
||||
remotePublic = clientEphemeral.public,
|
||||
role = AesCtrSessionCipher.Role.SERVER,
|
||||
)
|
||||
val clientCipher =
|
||||
AesCtrSessionCipher.derive(
|
||||
localPrivate = clientEphemeral.private,
|
||||
remotePublic = serverEphemeral.public,
|
||||
role = AesCtrSessionCipher.Role.CLIENT,
|
||||
)
|
||||
|
||||
val plaintext = "the quick brown fox jumps over the lazy dog".toByteArray()
|
||||
val srcServerOut = Unpooled.wrappedBuffer(plaintext)
|
||||
val encrypted = Unpooled.buffer()
|
||||
serverCipher.encrypt(srcServerOut, encrypted)
|
||||
|
||||
val decrypted = Unpooled.buffer()
|
||||
clientCipher.decrypt(encrypted, decrypted)
|
||||
val read = ByteArray(decrypted.readableBytes())
|
||||
decrypted.readBytes(read)
|
||||
read shouldBe plaintext
|
||||
}
|
||||
|
||||
test("NoOpSessionCipher passes through") {
|
||||
val src = Unpooled.wrappedBuffer(byteArrayOf(1, 2, 3))
|
||||
val dst = Unpooled.buffer()
|
||||
NoOpSessionCipher.encrypt(src, dst)
|
||||
val arr = ByteArray(3)
|
||||
dst.readBytes(arr)
|
||||
arr shouldBe byteArrayOf(1, 2, 3)
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,124 @@
|
||||
package de.fiereu.network.coroutines
|
||||
|
||||
import de.fiereu.bytecodec.CodecScope
|
||||
import de.fiereu.bytecodec.PacketCodec
|
||||
import de.fiereu.bytecodec.U16LE
|
||||
import de.fiereu.network.HandlerRegistrationException
|
||||
import de.fiereu.network.PipelineNames
|
||||
import de.fiereu.network.Protocol
|
||||
import de.fiereu.network.ProtocolHandler
|
||||
import de.fiereu.network.Side
|
||||
import de.fiereu.network.c2s
|
||||
import de.fiereu.network.internal.MutableSessionContext
|
||||
import de.fiereu.network.internal.SESSION_KEY
|
||||
import io.kotest.assertions.throwables.shouldThrow
|
||||
import io.kotest.core.spec.style.FunSpec
|
||||
import io.kotest.matchers.shouldBe
|
||||
import io.netty.buffer.Unpooled
|
||||
import io.netty.channel.embedded.EmbeddedChannel
|
||||
import kotlinx.coroutines.CompletableDeferred
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import kotlinx.coroutines.withTimeout
|
||||
|
||||
private data class Slow(val id: Int)
|
||||
|
||||
private data class Fast(val id: Int)
|
||||
|
||||
private object SlowCodec : PacketCodec<Slow>() {
|
||||
override fun CodecScope<Slow>.body() = Slow(field(U16LE, Slow::id))
|
||||
}
|
||||
|
||||
private object FastCodec : PacketCodec<Fast>() {
|
||||
override fun CodecScope<Fast>.body() = Fast(field(U16LE, Fast::id))
|
||||
}
|
||||
|
||||
private object MixedProtocol : Protocol() {
|
||||
init {
|
||||
c2s<Slow>(0xC0u, SlowCodec)
|
||||
c2s<Fast>(0xC1u, FastCodec)
|
||||
}
|
||||
}
|
||||
|
||||
private fun channelWithHandler(handler: ProtocolHandler): EmbeddedChannel {
|
||||
val channel = EmbeddedChannel()
|
||||
val session = MutableSessionContext(handler.side, channel, handler.protocol)
|
||||
channel.attr(SESSION_KEY).set(session)
|
||||
channel.pipeline().addLast(PipelineNames.PROTOCOL_HANDLER, handler)
|
||||
return channel
|
||||
}
|
||||
|
||||
class CoroutineProtocolHandlerTest :
|
||||
FunSpec({
|
||||
test("onSuspend handler runs on the supplied scope") {
|
||||
val scope = CoroutineScope(Dispatchers.Default + Job())
|
||||
val received = CompletableDeferred<Slow>()
|
||||
val handler =
|
||||
object : CoroutineProtocolHandler<MixedProtocol>(MixedProtocol, Side.SERVER, scope) {
|
||||
init {
|
||||
onSuspend<Slow> { event -> received.complete(event.packet) }
|
||||
}
|
||||
}
|
||||
val channel = channelWithHandler(handler)
|
||||
channel.writeInbound(Unpooled.wrappedBuffer(byteArrayOf(0xC0.toByte(), 0x07, 0x00)))
|
||||
runBlocking { withTimeout(2000) { received.await() } shouldBe Slow(7) }
|
||||
scope.cancel()
|
||||
}
|
||||
|
||||
test("sync on<T> and onSuspend coexist") {
|
||||
val scope = CoroutineScope(Dispatchers.Default + Job())
|
||||
val syncSeen = mutableListOf<Fast>()
|
||||
val asyncSeen = CompletableDeferred<Slow>()
|
||||
val handler =
|
||||
object : CoroutineProtocolHandler<MixedProtocol>(MixedProtocol, Side.SERVER, scope) {
|
||||
init {
|
||||
on<Fast> { event -> syncSeen += event.packet }
|
||||
onSuspend<Slow> { event -> asyncSeen.complete(event.packet) }
|
||||
}
|
||||
}
|
||||
val channel = channelWithHandler(handler)
|
||||
channel.writeInbound(Unpooled.wrappedBuffer(byteArrayOf(0xC1.toByte(), 0x03, 0x00)))
|
||||
channel.writeInbound(Unpooled.wrappedBuffer(byteArrayOf(0xC0.toByte(), 0x09, 0x00)))
|
||||
syncSeen shouldBe listOf(Fast(3))
|
||||
runBlocking { withTimeout(2000) { asyncSeen.await() } shouldBe Slow(9) }
|
||||
scope.cancel()
|
||||
}
|
||||
|
||||
test("registering the same type twice across sync/suspend throws") {
|
||||
val scope = CoroutineScope(Dispatchers.Default + Job())
|
||||
shouldThrow<HandlerRegistrationException> {
|
||||
object : CoroutineProtocolHandler<MixedProtocol>(MixedProtocol, Side.SERVER, scope) {
|
||||
init {
|
||||
on<Slow> {}
|
||||
onSuspend<Slow> {}
|
||||
}
|
||||
}
|
||||
}
|
||||
scope.cancel()
|
||||
}
|
||||
|
||||
test("mailbox preserves ordering") {
|
||||
val scope = CoroutineScope(Dispatchers.Default + Job())
|
||||
val seen = mutableListOf<Int>()
|
||||
val all = CompletableDeferred<Unit>()
|
||||
val handler =
|
||||
object : CoroutineProtocolHandler<MixedProtocol>(MixedProtocol, Side.SERVER, scope) {
|
||||
init {
|
||||
onSuspend<Slow> { event ->
|
||||
seen += event.packet.id
|
||||
if (seen.size == 5) all.complete(Unit)
|
||||
}
|
||||
}
|
||||
}
|
||||
val channel = channelWithHandler(handler)
|
||||
for (i in 1..5) {
|
||||
channel.writeInbound(Unpooled.wrappedBuffer(byteArrayOf(0xC0.toByte(), i.toByte(), 0x00)))
|
||||
}
|
||||
runBlocking { withTimeout(2000) { all.await() } }
|
||||
seen shouldBe listOf(1, 2, 3, 4, 5)
|
||||
scope.cancel()
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,52 @@
|
||||
package de.fiereu.network.handlers
|
||||
|
||||
import io.kotest.core.spec.style.FunSpec
|
||||
import io.kotest.matchers.shouldBe
|
||||
import io.netty.buffer.ByteBuf
|
||||
import io.netty.buffer.Unpooled
|
||||
import io.netty.channel.embedded.EmbeddedChannel
|
||||
|
||||
class CompressionTest :
|
||||
FunSpec({
|
||||
test("payload below threshold preserves opcode and writes flag=0") {
|
||||
val enc = EmbeddedChannel(CompressionEncoder(threshold = 16))
|
||||
enc.writeOutbound(Unpooled.wrappedBuffer(byteArrayOf(0xAA.toByte(), 1, 2, 3, 4)))
|
||||
val out = enc.readOutbound<ByteBuf>()
|
||||
out.readableBytes() shouldBe 6
|
||||
out.readByte() shouldBe 0xAA.toByte()
|
||||
out.readByte() shouldBe 0
|
||||
val rest = ByteArray(4)
|
||||
out.readBytes(rest)
|
||||
rest shouldBe byteArrayOf(1, 2, 3, 4)
|
||||
}
|
||||
|
||||
test("encoder + decoder roundtrip for raw payload") {
|
||||
val enc = EmbeddedChannel(CompressionEncoder(threshold = 16))
|
||||
enc.writeOutbound(Unpooled.wrappedBuffer(byteArrayOf(0xAA.toByte(), 1, 2, 3, 4)))
|
||||
val compressed = enc.readOutbound<ByteBuf>()
|
||||
val dec = EmbeddedChannel(CompressionDecoder())
|
||||
dec.writeInbound(compressed)
|
||||
val out = dec.readInbound<ByteBuf>()
|
||||
out.readableBytes() shouldBe 5
|
||||
out.readByte() shouldBe 0xAA.toByte()
|
||||
val rest = ByteArray(4)
|
||||
out.readBytes(rest)
|
||||
rest shouldBe byteArrayOf(1, 2, 3, 4)
|
||||
}
|
||||
|
||||
test("encoder + decoder roundtrip for compressed payload") {
|
||||
val payload = ByteArray(512) { (it and 0x0F).toByte() }
|
||||
val enc = EmbeddedChannel(CompressionEncoder(threshold = 64))
|
||||
enc.writeOutbound(Unpooled.wrappedBuffer(byteArrayOf(0xBB.toByte()) + payload))
|
||||
val compressed = enc.readOutbound<ByteBuf>()
|
||||
compressed.getByte(0) shouldBe 0xBB.toByte()
|
||||
compressed.getByte(1) shouldBe 1
|
||||
val dec = EmbeddedChannel(CompressionDecoder())
|
||||
dec.writeInbound(compressed)
|
||||
val out = dec.readInbound<ByteBuf>()
|
||||
out.readByte() shouldBe 0xBB.toByte()
|
||||
val read = ByteArray(out.readableBytes())
|
||||
out.readBytes(read)
|
||||
read shouldBe payload
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,83 @@
|
||||
package de.fiereu.network.handlers
|
||||
|
||||
import de.fiereu.network.ChecksumMismatchException
|
||||
import de.fiereu.network.checksum.Crc16Checksum
|
||||
import de.fiereu.network.checksum.NoOpChecksum
|
||||
import io.kotest.assertions.throwables.shouldThrow
|
||||
import io.kotest.core.spec.style.FunSpec
|
||||
import io.kotest.matchers.shouldBe
|
||||
import io.netty.buffer.ByteBuf
|
||||
import io.netty.buffer.Unpooled
|
||||
import io.netty.channel.embedded.EmbeddedChannel
|
||||
|
||||
private fun EmbeddedChannel.drainOutbound(): ByteBuf {
|
||||
val out = Unpooled.buffer()
|
||||
while (true) {
|
||||
val obj = readOutbound<Any>() ?: break
|
||||
if (obj is ByteBuf) {
|
||||
out.writeBytes(obj)
|
||||
obj.release()
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
private fun rootCause(t: Throwable): Throwable {
|
||||
var c: Throwable = t
|
||||
while (c.cause != null && c.cause !== c) c = c.cause!!
|
||||
return c
|
||||
}
|
||||
|
||||
class FrameAndChecksumTest :
|
||||
FunSpec({
|
||||
test("PacketFrameEncoder writes LE length prefix including itself") {
|
||||
val channel = EmbeddedChannel(PacketFrameEncoder())
|
||||
channel.writeOutbound(
|
||||
Unpooled.wrappedBuffer(byteArrayOf(0xAA.toByte(), 0xBB.toByte(), 0xCC.toByte())))
|
||||
val out = channel.drainOutbound()
|
||||
out.readableBytes() shouldBe 5
|
||||
out.readUnsignedShortLE() shouldBe 5
|
||||
val rest = ByteArray(3)
|
||||
out.readBytes(rest)
|
||||
rest shouldBe byteArrayOf(0xAA.toByte(), 0xBB.toByte(), 0xCC.toByte())
|
||||
}
|
||||
|
||||
test("PacketFrameDecoder strips the length prefix") {
|
||||
val encoder = EmbeddedChannel(PacketFrameEncoder())
|
||||
encoder.writeOutbound(Unpooled.wrappedBuffer(byteArrayOf(1, 2, 3, 4)))
|
||||
val framed = encoder.drainOutbound()
|
||||
|
||||
val decoder = EmbeddedChannel(PacketFrameDecoder())
|
||||
decoder.writeInbound(framed)
|
||||
val out = decoder.readInbound<ByteBuf>()
|
||||
out.readableBytes() shouldBe 4
|
||||
}
|
||||
|
||||
test("ChecksumFrameEncoder appends tag; decoder strips it") {
|
||||
val enc = EmbeddedChannel(ChecksumFrameEncoder(Crc16Checksum()))
|
||||
enc.writeOutbound(Unpooled.wrappedBuffer(byteArrayOf(1, 2, 3, 4)))
|
||||
val withTag = enc.drainOutbound()
|
||||
withTag.readableBytes() shouldBe 6
|
||||
|
||||
val dec = EmbeddedChannel(ChecksumFrameDecoder(Crc16Checksum()))
|
||||
dec.writeInbound(withTag)
|
||||
val out = dec.readInbound<ByteBuf>()
|
||||
out.readableBytes() shouldBe 4
|
||||
}
|
||||
|
||||
test("ChecksumFrameDecoder throws on mismatch") {
|
||||
val dec = EmbeddedChannel(ChecksumFrameDecoder(Crc16Checksum()))
|
||||
val thrown =
|
||||
shouldThrow<Throwable> {
|
||||
dec.writeInbound(Unpooled.wrappedBuffer(byteArrayOf(1, 2, 3, 4, 0, 0)))
|
||||
}
|
||||
(rootCause(thrown) is ChecksumMismatchException) shouldBe true
|
||||
}
|
||||
|
||||
test("NoOpChecksum decoder passes payload through") {
|
||||
val dec = EmbeddedChannel(ChecksumFrameDecoder(NoOpChecksum))
|
||||
dec.writeInbound(Unpooled.wrappedBuffer(byteArrayOf(9, 9, 9)))
|
||||
val out = dec.readInbound<ByteBuf>()
|
||||
out.readableBytes() shouldBe 3
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,117 @@
|
||||
package de.fiereu.network.handshake
|
||||
|
||||
import de.fiereu.bytecodec.CodecScope
|
||||
import de.fiereu.bytecodec.PacketCodec
|
||||
import de.fiereu.bytecodec.U16LE
|
||||
import de.fiereu.network.PipelineOptions
|
||||
import de.fiereu.network.Protocol
|
||||
import de.fiereu.network.ProtocolHandler
|
||||
import de.fiereu.network.SessionIdentity
|
||||
import de.fiereu.network.SessionPhase
|
||||
import de.fiereu.network.Side
|
||||
import de.fiereu.network.TypedProtocolHandler
|
||||
import de.fiereu.network.bidi
|
||||
import de.fiereu.network.installPipeline
|
||||
import de.fiereu.network.internal.SESSION_KEY
|
||||
import io.kotest.core.spec.style.FunSpec
|
||||
import io.kotest.matchers.shouldBe
|
||||
import io.netty.buffer.ByteBuf
|
||||
import io.netty.channel.Channel
|
||||
import io.netty.channel.ChannelInitializer
|
||||
import io.netty.channel.embedded.EmbeddedChannel
|
||||
import java.security.interfaces.ECPrivateKey
|
||||
import java.security.interfaces.ECPublicKey
|
||||
|
||||
private data class Echo(val value: Int)
|
||||
|
||||
private object EchoCodec : PacketCodec<Echo>() {
|
||||
override fun CodecScope<Echo>.body() = Echo(field(U16LE, Echo::value))
|
||||
}
|
||||
|
||||
private object EchoProtocol : Protocol() {
|
||||
init {
|
||||
bidi<Echo>(0x55u, EchoCodec)
|
||||
}
|
||||
}
|
||||
|
||||
private class CollectingHandler(side: Side) :
|
||||
TypedProtocolHandler<EchoProtocol>(EchoProtocol, side) {
|
||||
val received = mutableListOf<Echo>()
|
||||
|
||||
init {
|
||||
on<Echo> { event -> received += event.packet }
|
||||
}
|
||||
}
|
||||
|
||||
private fun drain(from: EmbeddedChannel, into: EmbeddedChannel) {
|
||||
while (true) {
|
||||
val obj = from.readOutbound<ByteBuf>() ?: break
|
||||
into.writeInbound(obj)
|
||||
}
|
||||
}
|
||||
|
||||
class EndToEndHandshakeTest :
|
||||
FunSpec({
|
||||
test("server and client exchange a full handshake and an application packet") {
|
||||
val rootKeyPair = EcKeys.generateEphemeralKeyPair()
|
||||
val rootPrivate = rootKeyPair.private as ECPrivateKey
|
||||
val rootPublic = rootKeyPair.public as ECPublicKey
|
||||
|
||||
val serverApp = CollectingHandler(Side.SERVER)
|
||||
val clientApp = CollectingHandler(Side.CLIENT)
|
||||
|
||||
val options = PipelineOptions(checksumSize = 8)
|
||||
|
||||
val serverChannel =
|
||||
EmbeddedChannel(
|
||||
object : ChannelInitializer<Channel>() {
|
||||
override fun initChannel(ch: Channel) {
|
||||
installPipeline(
|
||||
pipeline = ch.pipeline(),
|
||||
side = Side.SERVER,
|
||||
identity = SessionIdentity.ServerRoot(rootPrivate),
|
||||
applicationProtocol = EchoProtocol,
|
||||
applicationHandlerFactory = { serverApp as ProtocolHandler },
|
||||
options = options,
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
val clientChannel =
|
||||
EmbeddedChannel(
|
||||
object : ChannelInitializer<Channel>() {
|
||||
override fun initChannel(ch: Channel) {
|
||||
installPipeline(
|
||||
pipeline = ch.pipeline(),
|
||||
side = Side.CLIENT,
|
||||
identity = SessionIdentity.ClientTrust(rootPublic),
|
||||
applicationProtocol = EchoProtocol,
|
||||
applicationHandlerFactory = { clientApp as ProtocolHandler },
|
||||
options = options,
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
// Client sends ClientHello on channelActive (called during init for EmbeddedChannel)
|
||||
drain(clientChannel, serverChannel)
|
||||
// Server replies ServerHello
|
||||
drain(serverChannel, clientChannel)
|
||||
// Client replies ClientReady
|
||||
drain(clientChannel, serverChannel)
|
||||
|
||||
serverChannel.attr(SESSION_KEY).get().phase shouldBe SessionPhase.ESTABLISHED
|
||||
clientChannel.attr(SESSION_KEY).get().phase shouldBe SessionPhase.ESTABLISHED
|
||||
|
||||
// Client sends an application packet through the encrypted pipeline
|
||||
clientChannel.attr(SESSION_KEY).get().send(Echo(0xCAFE))
|
||||
drain(clientChannel, serverChannel)
|
||||
serverApp.received shouldBe listOf(Echo(0xCAFE))
|
||||
|
||||
// Server responds
|
||||
serverChannel.attr(SESSION_KEY).get().send(Echo(0xBABE))
|
||||
drain(serverChannel, clientChannel)
|
||||
clientApp.received shouldBe listOf(Echo(0xBABE))
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,39 @@
|
||||
package de.fiereu.network.handshake
|
||||
|
||||
import de.fiereu.bytecodec.test.assertValueRoundtrip
|
||||
import de.fiereu.bytecodec.test.decodeBytes
|
||||
import de.fiereu.bytecodec.test.encodeToBytes
|
||||
import io.kotest.core.spec.style.FunSpec
|
||||
import io.kotest.matchers.shouldBe
|
||||
import java.security.interfaces.ECPublicKey
|
||||
|
||||
class HandshakeCodecsTest :
|
||||
FunSpec({
|
||||
test("ClientHello roundtrip recovers timestamp despite XOR obfuscation") {
|
||||
val ts = 1764115200L
|
||||
val bytes = ClientHelloCodec.encodeToBytes(ClientHelloPacket(ts))
|
||||
bytes.size shouldBe 16
|
||||
ClientHelloCodec.decodeBytes(bytes).timestamp shouldBe ts
|
||||
}
|
||||
|
||||
test("ServerHello roundtrips pubkey, signature, checksum size") {
|
||||
val keyPair = EcKeys.generateEphemeralKeyPair()
|
||||
val pkt =
|
||||
ServerHelloPacket(
|
||||
ephemeralPublic = keyPair.public as ECPublicKey,
|
||||
signature = ByteArray(64) { it.toByte() },
|
||||
checksumSize = 16,
|
||||
)
|
||||
val bytes = ServerHelloCodec.encodeToBytes(pkt)
|
||||
val decoded = ServerHelloCodec.decodeBytes(bytes)
|
||||
decoded.ephemeralPublic shouldBe pkt.ephemeralPublic
|
||||
decoded.signature shouldBe pkt.signature
|
||||
decoded.checksumSize shouldBe 16
|
||||
}
|
||||
|
||||
test("ClientReady roundtrips public key") {
|
||||
val keyPair = EcKeys.generateEphemeralKeyPair()
|
||||
val pkt = ClientReadyPacket(ephemeralPublic = keyPair.public as ECPublicKey)
|
||||
ClientReadyCodec.assertValueRoundtrip(pkt)
|
||||
}
|
||||
})
|
||||
Reference in new issue
Block a user