This commit is contained in:
Fiereu committed 2025-08-22 16:11:41 +02:00
commit c5ee4e27e6
131 files changed
+9926

No files matched your search

+63
View File
@@ -0,0 +1,63 @@
# Server Module
The server module provides the core server framework for OpenMMO using Netty for networking and protocol handling.
## Contents
### Core Classes
- **Server**: Main server class with lifecycle management (start/stop)
- **ServerBuilder**: Builder pattern for server configuration and setup
- **NettyServer**: Netty-based server implementation for async I/O
### Configuration
- **ServerConfig**: Main server configuration settings
- **TlsConfig**: TLS-specific configuration for secure communication
- **ConfigLoader**: Configuration loading utilities
### Networking Components
- **ChannelHandlerProvider**: Interface for providing Netty channel handlers
- **DefaultChannelHandlerProvider**: Default implementation of channel handler provider
### Netty Handlers
- **ProtocolHandler**: Main protocol routing and packet handling
- **PacketFrameDecoder/Encoder**: Packet framing with length prefixing
- **ChecksumFrameDecoder/Encoder**: Packet integrity validation (CRC16 and HMAC-SHA256)
- **TlsDecryptionHandler/TlsEncryptionHandler**: TLS-like encryption/decryption
### Protocol System
- **TlsContext**: TLS session context management
- **TlsProtocolHandler**: TLS protocol implementation
- **PacketEvent**: Event system for packet processing
### Cryptography
- **KeyLoader**: Utility for loading ECDSA keys from PEM files
- **Checksum**: Abstraction for packet integrity validation
- **Crc16Checksum**: CRC16 implementation
- **HmacSha256Checksum**: HMAC-SHA256 implementation
### Dependency Injection
- **ServerComponent**: Dagger component for dependency injection
- **ServerModule**: Dagger module providing server dependencies
## Features
- Asynchronous networking using Netty
- Custom TLS-like protocol for secure communication
- Packet framing and integrity validation
- Protocol switching (TLS handshake → application protocols)
- ECDSA key management for packet signing/verification
- Configurable coroutine scopes for async operations
## Dependencies
- Netty for networking
- Dagger 2 for dependency injection
- BouncyCastle for cryptography
- Kotlinx.coroutines for async operations
- Kotlinx.serialization for configuration
- TypeSafe Config for configuration management
- Protocol and Protocol.TLS modules
## Testing
- Comprehensive unit tests using Kotest
- Integration tests for Netty pipeline components
- TLS handler tests with helper utilities
- MockK for mocking dependencies
+32
View File
@@ -0,0 +1,32 @@
plugins {
`java-library`
id("buildsrc.convention.kotlin-jvm")
alias(libs.plugins.kotlin.serialization)
alias(libs.plugins.ksp)
}
group = "de.fiereu.openmmo"
version = "0.1.0"
dependencies {
api(libs.typesafe.config)
api(libs.slf4j)
api(libs.kotlin.logging)
api(libs.kotlinx.serialization.core)
api(libs.kotlinx.coroutines)
api(libs.dagger)
api(project(":protocol"))
api(project(":protocol.tls"))
ksp(libs.dagger.compiler)
implementation(libs.kotlin.reflect)
implementation(libs.netty)
implementation(libs.kotlinx.serialization.json)
implementation(libs.bundles.crypto)
testImplementation(libs.bundles.kotest)
testImplementation(libs.kotlinx.coroutines.test)
testImplementation(libs.mockk)
}
@@ -0,0 +1,54 @@
package de.fiereu.openmmo.server
import de.fiereu.openmmo.server.netty.NettyServer
import io.github.oshai.kotlinlogging.KotlinLogging
import javax.inject.Inject
import javax.inject.Singleton
private val log = KotlinLogging.logger {}
@Singleton
class Server @Inject constructor(
private val nettyServer: NettyServer
) {
@Volatile
private var isStarted = false
val isRunning: Boolean
get() = isStarted && nettyServer.isRunning
fun start() {
if (isStarted) {
log.warn { "Server is already started" }
return
}
log.info { "Starting server..." }
try {
nettyServer.start()
isStarted = true
log.info { "Server started successfully" }
} catch (e: Exception) {
log.error(e) { "Failed to start server" }
throw e
}
}
fun stop() {
if (!isStarted) {
log.warn { "Server is not started" }
return
}
log.info { "Stopping server..." }
try {
nettyServer.stop()
isStarted = false
log.info { "Server stopped successfully" }
} catch (e: Exception) {
log.error(e) { "Error during server shutdown" }
throw e
}
}
}
@@ -0,0 +1,87 @@
package de.fiereu.openmmo.server
import de.fiereu.openmmo.server.config.ServerConfig
import de.fiereu.openmmo.server.config.TlsConfig
import de.fiereu.openmmo.server.di.DaggerServerComponent
import de.fiereu.openmmo.server.di.ServerModule
import de.fiereu.openmmo.server.netty.ChannelHandlerProvider
import de.fiereu.openmmo.server.netty.handlers.ProtocolHandler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import java.security.interfaces.ECPrivateKey
import java.security.interfaces.ECPublicKey
class ServerBuilder {
private var coroutineScope: CoroutineScope? = null
private var serverConfig: ServerConfig? = null
private var tlsConfig: TlsConfig? = null
private var privateKey: ECPrivateKey? = null
private var publicKey: ECPublicKey? = null
private var protocolProvider: (() -> ProtocolHandler)? = null
fun withCoroutineScope(scope: CoroutineScope): ServerBuilder = apply {
this.coroutineScope = scope
}
fun withConfig(config: ServerConfig): ServerBuilder = apply {
this.serverConfig = config
}
fun withTlsConfig(tlsConfig: TlsConfig): ServerBuilder = apply {
this.tlsConfig = tlsConfig
}
fun withPrivateKey(privateKey: ECPrivateKey): ServerBuilder = apply {
this.privateKey = privateKey
}
fun withPublicKey(publicKey: ECPublicKey): ServerBuilder = apply {
this.publicKey = publicKey
}
fun withChannelHandlerProvider(provider: () -> ProtocolHandler): ServerBuilder = apply {
this.protocolProvider = provider
}
fun build(): Server {
val coroutineScope = coroutineScope ?: throw IllegalStateException("CoroutineScope must be provided")
val config = serverConfig ?: throw IllegalStateException("ServerConfig must be provided")
val tlsConfig = tlsConfig ?: throw IllegalStateException("TlsConfig must be provided")
val privKey = privateKey ?: throw IllegalStateException("PrivateKey must be provided")
val pubKey = publicKey ?: throw IllegalStateException("PublicKey must be provided")
val protocolProvider = protocolProvider ?: throw IllegalStateException("ChannelHandlerProvider must be provided")
val component = DaggerServerComponent.builder()
.serverModule(ServerModule(
coroutineScope,
config,
tlsConfig,
Pair(privKey, pubKey),
protocolProvider
))
.build()
return component.server()
}
companion object {
fun create(): ServerBuilder = ServerBuilder()
fun create(
config: ServerConfig,
tlsConfig: TlsConfig,
privateKey: ECPrivateKey,
publicKey: ECPublicKey,
handlerProvider: () -> ProtocolHandler
): Server {
return ServerBuilder()
.withConfig(config)
.withTlsConfig(tlsConfig)
.withPrivateKey(privateKey)
.withPublicKey(publicKey)
.withChannelHandlerProvider(handlerProvider)
.build()
}
}
}
@@ -0,0 +1,59 @@
package de.fiereu.openmmo.server.config
import com.typesafe.config.Config
import com.typesafe.config.ConfigFactory
import kotlinx.serialization.DeserializationStrategy
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.serializer
import kotlin.reflect.typeOf
object ConfigLoader {
private val json = Json {
ignoreUnknownKeys = true
isLenient = true
}
@Suppress("UNCHECKED_CAST")
inline fun <reified T> load(path: String): T {
return load(path, serializer(typeOf<T>()) as DeserializationStrategy<T>)
}
fun <T> load(path: String, deserializer: DeserializationStrategy<T>): T {
val config = ConfigFactory.load(path)
val jsonElement = configToJsonElement(config.root())
return json.decodeFromJsonElement(deserializer, jsonElement)
}
inline fun <reified T> loadWithDefaults(path: String, defaults: T): T {
return try {
load<T>(path)
} catch (e: Exception) {
defaults
}
}
private fun configToJsonElement(config: Any?): JsonElement {
return when (config) {
is Config -> buildJsonObject {
config.entrySet().forEach { (key, value) ->
put(key, configToJsonElement(value.unwrapped()))
}
}
is Map<*, *> -> buildJsonObject {
config.forEach { (key, value) ->
put(key.toString(), configToJsonElement(value))
}
}
is List<*> -> kotlinx.serialization.json.buildJsonArray {
config.forEach { add(configToJsonElement(it)) }
}
is String -> kotlinx.serialization.json.JsonPrimitive(config)
is Number -> kotlinx.serialization.json.JsonPrimitive(config)
is Boolean -> kotlinx.serialization.json.JsonPrimitive(config)
null -> kotlinx.serialization.json.JsonNull
else -> kotlinx.serialization.json.JsonPrimitive(config.toString())
}
}
}
@@ -0,0 +1,17 @@
package de.fiereu.openmmo.server.config
import kotlinx.serialization.Serializable
@Serializable
data class ServerConfig(
val host: String = "0.0.0.0",
val port: Int,
val workerThreads: Int = Runtime.getRuntime().availableProcessors(),
val bossThreads: Int = 1,
val tcpNoDelay: Boolean = true,
val keepAlive: Boolean = true,
val soBacklog: Int = 128,
val receiveBufferSize: Int = 65536,
val sendBufferSize: Int = 65536,
val writeTimeoutSeconds: Long = 1500L // 25 minutes default
)
@@ -0,0 +1,5 @@
package de.fiereu.openmmo.server.config
data class TlsConfig(
val checksumSize: Int,
)
@@ -0,0 +1,21 @@
package de.fiereu.openmmo.server.di
import dagger.Component
import de.fiereu.openmmo.server.Server
import de.fiereu.openmmo.server.config.ServerConfig
import de.fiereu.openmmo.server.netty.NettyServer
import javax.inject.Singleton
@Singleton
@Component(modules = [ServerModule::class])
interface ServerComponent {
fun server(): Server
fun nettyServer(): NettyServer
fun serverConfig(): ServerConfig
@Component.Builder
interface Builder {
fun serverModule(module: ServerModule): Builder
fun build(): ServerComponent
}
}
@@ -0,0 +1,64 @@
package de.fiereu.openmmo.server.di
import dagger.Module
import dagger.Provides
import de.fiereu.openmmo.protocols.tls.TlsServerProtocol
import de.fiereu.openmmo.server.config.ServerConfig
import de.fiereu.openmmo.server.config.TlsConfig
import de.fiereu.openmmo.server.netty.ChannelHandlerProvider
import de.fiereu.openmmo.server.netty.DefaultChannelHandlerProvider
import de.fiereu.openmmo.server.netty.handlers.ProtocolHandler
import io.netty.channel.EventLoopGroup
import io.netty.channel.MultiThreadIoEventLoopGroup
import io.netty.channel.nio.NioIoHandler
import kotlinx.coroutines.CoroutineScope
import java.security.interfaces.ECPrivateKey
import java.security.interfaces.ECPublicKey
import javax.inject.Named
import javax.inject.Singleton
@Module
class ServerModule(
private val coroutineScope: CoroutineScope,
private val config: ServerConfig,
private val tlsConfig: TlsConfig,
private val serverKeyPair: Pair<ECPrivateKey, ECPublicKey>,
private val protocolProvider: () -> ProtocolHandler
) {
@Provides
@Singleton
fun provideServerConfig(): ServerConfig = config
@Provides
@Singleton
fun provideTlsProtocol(): TlsServerProtocol = TlsServerProtocol(
serverKeyPair
)
@Provides
@Singleton
fun provideChannelHandlerProvider(
serverConfig: ServerConfig,
tlsProtocol: TlsServerProtocol
): ChannelHandlerProvider = DefaultChannelHandlerProvider(
serverConfig,
tlsConfig,
tlsProtocol,
protocolProvider
)
@Provides
@Singleton
@Named("boss")
fun provideBossEventLoopGroup(): EventLoopGroup {
return MultiThreadIoEventLoopGroup(config.bossThreads, NioIoHandler.newFactory())
}
@Provides
@Singleton
@Named("worker")
fun provideWorkerEventLoopGroup(): EventLoopGroup {
return MultiThreadIoEventLoopGroup(config.workerThreads, NioIoHandler.newFactory())
}
}
@@ -0,0 +1,11 @@
package de.fiereu.openmmo.server.io
import java.io.FileInputStream
import java.io.InputStream
fun resource(path: String): InputStream
= Thread.currentThread().contextClassLoader.getResourceAsStream(path)
?: throw IllegalArgumentException("Resource not found: $path")
fun file(path: String): InputStream
= FileInputStream(path)
@@ -0,0 +1,29 @@
package de.fiereu.openmmo.server.keys
import io.github.oshai.kotlinlogging.KotlinLogging
import org.bouncycastle.util.io.pem.PemReader
import java.io.InputStream
import java.security.interfaces.ECPublicKey
import java.security.spec.X509EncodedKeySpec
val log = KotlinLogging.logger {}
object KeyLoader {
fun loadPemECPublicKey(inputStream: InputStream): ECPublicKey {
PemReader(inputStream.reader()).use { pemReader ->
val pemObject = pemReader.readPemObject()
val keySpec = X509EncodedKeySpec(pemObject.content)
val keyFactory = java.security.KeyFactory.getInstance("EC")
return keyFactory.generatePublic(keySpec) as ECPublicKey
}
}
fun loadPemECPrivateKey(inputStream: InputStream): java.security.interfaces.ECPrivateKey {
PemReader(inputStream.reader()).use { pemReader ->
val pemObject = pemReader.readPemObject()
val keySpec = java.security.spec.PKCS8EncodedKeySpec(pemObject.content)
val keyFactory = java.security.KeyFactory.getInstance("EC")
return keyFactory.generatePrivate(keySpec) as java.security.interfaces.ECPrivateKey
}
}
}
@@ -0,0 +1,17 @@
package de.fiereu.openmmo.server.netty
import io.netty.channel.ChannelPipeline
/**
* Interface for providing channel handlers to be configured in a Netty pipeline.
* Implementations should define how the pipeline is set up with specific handlers.
*/
interface ChannelHandlerProvider {
/**
* Configures the provided [pipeline] with the necessary channel handlers.
* This method should be implemented to add specific handlers to the pipeline.
*
* @param pipeline The [ChannelPipeline] to configure with handlers.
*/
fun configurePipeline(pipeline: ChannelPipeline)
}
@@ -0,0 +1,108 @@
package de.fiereu.openmmo.server.netty
import de.fiereu.openmmo.protocols.tls.TlsServerProtocol
import de.fiereu.openmmo.server.config.ServerConfig
import de.fiereu.openmmo.server.config.TlsConfig
import de.fiereu.openmmo.server.netty.handlers.ProtocolHandler
import de.fiereu.openmmo.server.netty.handlers.checksum.ChecksumFrameDecoder
import de.fiereu.openmmo.server.netty.handlers.checksum.ChecksumFrameEncoder
import de.fiereu.openmmo.server.netty.handlers.frame.PacketFrameDecoder
import de.fiereu.openmmo.server.netty.handlers.frame.PacketFrameEncoder
import de.fiereu.openmmo.server.netty.handlers.tls.TlsDecryptionHandler
import de.fiereu.openmmo.server.netty.handlers.tls.TlsEncryptionHandler
import de.fiereu.openmmo.server.protocol.tls.NoOpTlsContext
import de.fiereu.openmmo.server.protocol.tls.TlsContext
import de.fiereu.openmmo.server.protocol.tls.TlsProtocolHandler
import de.fiereu.openmmo.server.protocol.tls.checksum.Checksum
import de.fiereu.openmmo.server.protocol.tls.checksum.NoOpChecksum
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.ChannelPipeline
import io.netty.handler.timeout.WriteTimeoutHandler
import java.util.concurrent.TimeUnit
/**
* Base class for configuring Netty channel handlers in the server.
* Default handlers:
* - Timeout handler (Timeout defined in [ServerConfig])
* - Packet frame codec
* - Checksum frame codec (initially NoOp, can be switched dynamically)
* - TLS encryption/decryption handlers (initially NoOp, can be switched dynamically)
*/
class DefaultChannelHandlerProvider(
private val serverConfig: ServerConfig,
private val tlsConfig: TlsConfig,
private val tlsProtocol: TlsServerProtocol,
private val protocolProvider: () -> ProtocolHandler,
) : ChannelHandlerProvider {
override fun configurePipeline(pipeline: ChannelPipeline) {
pipeline.addLast("timeout", WriteTimeoutHandler(serverConfig.writeTimeoutSeconds, TimeUnit.SECONDS))
pipeline.addLast("frame-decoder", PacketFrameDecoder())
pipeline.addLast("frame-encoder", PacketFrameEncoder())
pipeline.addLast("checksum-decoder", ChecksumFrameDecoder(NoOpChecksum()))
pipeline.addLast("checksum-encoder", ChecksumFrameEncoder(NoOpChecksum()))
val tlsContext = NoOpTlsContext()
pipeline.addLast("tls-decryption", TlsDecryptionHandler(tlsContext))
pipeline.addLast("tls-encryption", TlsEncryptionHandler(tlsContext))
pipeline.addLast("protocol", TlsProtocolHandler(tlsProtocol, tlsConfig, this))
}
/**
* Switches the checksum algorithm used in the pipeline.
*
* Will be called from the [TlsProtocolHandler] once the handshake is complete and a checksum algorithm is negotiated.
*
* @param ctx The channel handler context.
* @param newChecksum The new checksum algorithm to use.
*/
fun switchChecksum(ctx: ChannelHandlerContext, newChecksum: Checksum) {
val pipeline = ctx.pipeline()
if (pipeline.get("checksum-decoder") != null) {
pipeline.replace("checksum-decoder", "checksum-decoder", ChecksumFrameDecoder(newChecksum))
}
if (pipeline.get("checksum-encoder") != null) {
pipeline.replace("checksum-encoder", "checksum-encoder", ChecksumFrameEncoder(newChecksum))
}
}
/**
* Switches the TLS context used in the pipeline.
*
* Will be called from the [TlsProtocolHandler] once the handshake is complete and a TLS context is established.
*
* @param ctx The channel handler context.
* @param newTlsContext The new TLS context to use.
*/
fun switchTlsContext(ctx: ChannelHandlerContext, newTlsContext: TlsContext) {
val pipeline = ctx.pipeline()
if (pipeline.get("tls-decryption") != null) {
pipeline.replace("tls-decryption", "tls-decryption", TlsDecryptionHandler(newTlsContext))
}
if (pipeline.get("tls-encryption") != null) {
pipeline.replace("tls-encryption", "tls-encryption", TlsEncryptionHandler(newTlsContext))
}
}
/**
* Will enable the actual protocol handler after the TLS handshake is complete.
* Initially a [TlsProtocolHandler] is used to handle the handshake.
* Once the handshake is complete, this method replaces it with the actual protocol handler provided by [protocolProvider].
*
* @param ctx The channel handler context.
*/
fun enableProtocolHandler(ctx: ChannelHandlerContext) {
val pipeline = ctx.pipeline()
if (pipeline.get("protocol") != null) {
pipeline.replace("protocol", "protocol", protocolProvider())
}
}
}
@@ -0,0 +1,56 @@
package de.fiereu.openmmo.server.netty
import de.fiereu.openmmo.server.config.ServerConfig
import io.github.oshai.kotlinlogging.KotlinLogging
import io.netty.bootstrap.ServerBootstrap
import io.netty.channel.ChannelFuture
import io.netty.channel.ChannelInitializer
import io.netty.channel.ChannelOption
import io.netty.channel.EventLoopGroup
import io.netty.channel.socket.SocketChannel
import io.netty.channel.socket.nio.NioServerSocketChannel
import javax.inject.Inject
import javax.inject.Named
import javax.inject.Singleton
private val log = KotlinLogging.logger {}
@Singleton
class NettyServer @Inject constructor(
private val config: ServerConfig,
@param:Named("boss") private val bossGroup: EventLoopGroup,
@param:Named("worker") private val workerGroup: EventLoopGroup,
private val channelHandlerProvider: ChannelHandlerProvider
) {
private var channelFuture: ChannelFuture? = null
val isRunning: Boolean
get() = channelFuture?.channel()?.isActive == true
fun start() {
log.info { "Starting Netty server on ${config.host}:${config.port}" }
val bootstrap = ServerBootstrap()
.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel::class.java)
.childHandler(object : ChannelInitializer<SocketChannel>() {
override fun initChannel(ch: SocketChannel) {
channelHandlerProvider.configurePipeline(ch.pipeline())
}
})
.option(ChannelOption.SO_BACKLOG, config.soBacklog)
.childOption(ChannelOption.SO_KEEPALIVE, config.keepAlive)
.childOption(ChannelOption.TCP_NODELAY, config.tcpNoDelay)
.childOption(ChannelOption.SO_RCVBUF, config.receiveBufferSize)
.childOption(ChannelOption.SO_SNDBUF, config.sendBufferSize)
channelFuture = bootstrap.bind(config.host, config.port).await()
log.info { "Netty server started and listening on ${config.host}:${config.port}" }
}
fun stop() {
log.info { "Stopping Netty server" }
channelFuture?.channel()?.close()?.await()
bossGroup.shutdownGracefully().await()
workerGroup.shutdownGracefully().await()
log.info { "Netty server stopped" }
}
}
@@ -0,0 +1,88 @@
package de.fiereu.openmmo.server.netty.handlers
import de.fiereu.openmmo.protocols.PacketDirection
import de.fiereu.openmmo.protocols.Protocol
import de.fiereu.openmmo.protocols.getDeserializer
import de.fiereu.openmmo.server.protocol.PacketEvent
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(
private val protocol: Protocol
) : ChannelDuplexHandler() {
override fun channelRead(ctx: ChannelHandlerContext, msg: Any) {
if (msg !is ByteBuf) {
log.warn { "Received non-ByteBuf message: ${msg::class.simpleName}" }
return
}
try {
if (!msg.isReadable) {
log.warn { "Empty packet received" }
return
}
val opcodeValue = msg.readUnsignedByte().toUByte()
val deserializer = protocol.getDeserializer(opcodeValue)
if (deserializer == null) {
log.warn { "No deserializer found for ${PacketDirection.CLIENT_TO_SERVER} opcode $opcodeValue" }
return
}
val packetData = deserializer.deserialize(msg)
/*
We cant call the onPacketReceived function asynchronously directly here,
because the TLS protocol expects a synchronous flow. Meaning that the client already sends the next packet
after the ClientReady packet, so if we would process the ClientReady packet asynchronously,
the next packet would be processed before the ClientReady packet is fully processed.
-> It would be processed by the TLS protocol before and not by the next protocol (e.g. login protocol).
*/
onPacketReceived(PacketEvent(ctx, packetData))
} catch (e: Exception) {
log.error(e) { "Error processing packet" }
} finally {
msg.release()
}
}
override fun write(
ctx: ChannelHandlerContext,
msg: Any,
promise: ChannelPromise
) {
try {
val opcode = protocol.getOpcode(msg::class)
if (opcode == null) {
log.warn { "No opcode found for packet type: ${msg::class.simpleName}" }
return
}
val serializer = protocol.getSerializer(opcode)
if (serializer == null) {
log.warn { "No serializer found for ${PacketDirection.SERVER_TO_CLIENT} opcode $opcode" }
return
}
val buffer = ctx.alloc().buffer()
buffer.writeByte(opcode.value.toInt())
serializer.serializeObject(msg, buffer)
ctx.write(buffer, promise)
} catch (e: Exception) {
log.error(e) { "Error processing packet" }
}
}
override fun channelActive(ctx: ChannelHandlerContext) {
onActive(ctx)
}
abstract fun onPacketReceived(event: PacketEvent<*>)
abstract fun onActive(ctx: ChannelHandlerContext)
}
@@ -0,0 +1,49 @@
package de.fiereu.openmmo.server.netty.handlers.checksum
import de.fiereu.openmmo.server.protocol.tls.checksum.Checksum
import io.github.oshai.kotlinlogging.KotlinLogging
import io.netty.buffer.ByteBuf
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.ByteToMessageDecoder
private val log = KotlinLogging.logger {}
class ChecksumFrameDecoder(
private val checksum: Checksum
) : ByteToMessageDecoder() {
override fun decode(ctx: ChannelHandlerContext, buffer: ByteBuf, out: MutableList<Any>) {
// The regular FrameDecoder already handled length field extraction
// We receive the complete packet data here
if (checksum.size > 0) {
if (buffer.readableBytes() < checksum.size) {
log.warn { "Packet too small for checksum verification" }
return
}
// Extract checksum from end of packet
val checksumBytes = ByteArray(checksum.size)
buffer.getBytes(buffer.readableBytes() - checksum.size, checksumBytes)
// Verify checksum (excluding the checksum bytes themselves)
val dataToVerify = buffer.slice(0, buffer.readableBytes() - checksum.size)
if (!checksum.verify(dataToVerify, checksumBytes)) {
log.warn { "Checksum verification failed, dropping packet" }
return
}
// Remove checksum from packet data and pass it on
// Use slice() instead of readSlice() to avoid modifying the buffer's reader index
val packetWithoutChecksum = buffer.slice(buffer.readerIndex(), buffer.readableBytes() - checksum.size)
out.add(packetWithoutChecksum.retain())
// Advance the reader index to mark the data as consumed
buffer.readerIndex(buffer.writerIndex())
} else { // We could use the NoOpChecksum here but this is faster
// No checksum, pass through as-is
out.add(buffer.slice(buffer.readerIndex(), buffer.readableBytes()).retain())
// Advance the reader index to mark the data as consumed
buffer.readerIndex(buffer.writerIndex())
}
}
}
@@ -0,0 +1,30 @@
package de.fiereu.openmmo.server.netty.handlers.checksum
import de.fiereu.openmmo.server.protocol.tls.checksum.Checksum
import io.netty.buffer.ByteBuf
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.MessageToByteEncoder
class ChecksumFrameEncoder(
private val checksum: Checksum
) : MessageToByteEncoder<ByteBuf>() {
override fun encode(ctx: ChannelHandlerContext, msg: ByteBuf, out: ByteBuf) {
val dataLength = msg.readableBytes()
// Calculate checksum on the original data (before adding length)
val checksumBytes = if (checksum.size > 0) {
checksum.calculate(msg)
} else {
ByteArray(0)
}
// Write the packet data
out.writeBytes(msg, msg.readerIndex(), dataLength)
// Append checksum if needed
if (checksumBytes.isNotEmpty()) {
out.writeBytes(checksumBytes)
}
}
}
@@ -0,0 +1,14 @@
package de.fiereu.openmmo.server.netty.handlers.frame
import io.netty.handler.codec.LengthFieldBasedFrameDecoder
import java.nio.ByteOrder
class PacketFrameDecoder : LengthFieldBasedFrameDecoder(
ByteOrder.LITTLE_ENDIAN,
UShort.MAX_VALUE.toInt(),
0,
UShort.SIZE_BYTES,
-UShort.SIZE_BYTES, // Length includes the length field itself, so subtract 2
UShort.SIZE_BYTES,
false
)
@@ -0,0 +1,11 @@
package de.fiereu.openmmo.server.netty.handlers.frame
import io.netty.handler.codec.LengthFieldPrepender
import java.nio.ByteOrder
class PacketFrameEncoder : LengthFieldPrepender(
ByteOrder.LITTLE_ENDIAN,
UShort.SIZE_BYTES,
0,
true
)
@@ -0,0 +1,25 @@
package de.fiereu.openmmo.server.netty.handlers.tls
import de.fiereu.openmmo.server.protocol.tls.TlsContext
import io.netty.buffer.ByteBuf
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.ByteToMessageDecoder
class TlsDecryptionHandler(
private val tlsContext: TlsContext
) : ByteToMessageDecoder() {
override fun decode(ctx: ChannelHandlerContext, buffer: ByteBuf, out: MutableList<Any>) {
val dataLength = buffer.readableBytes()
if (dataLength == 0) return
val encryptedBytes = ByteArray(dataLength)
buffer.readBytes(encryptedBytes)
val decryptedBytes = tlsContext.decrypt(encryptedBytes)
val decryptedBuffer = ctx.alloc().buffer(decryptedBytes.size)
decryptedBuffer.writeBytes(decryptedBytes)
out.add(decryptedBuffer)
}
}
@@ -0,0 +1,21 @@
package de.fiereu.openmmo.server.netty.handlers.tls
import de.fiereu.openmmo.server.protocol.tls.TlsContext
import io.netty.buffer.ByteBuf
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.MessageToByteEncoder
class TlsEncryptionHandler(
private val tlsContext: TlsContext
) : MessageToByteEncoder<ByteBuf>() {
override fun encode(ctx: ChannelHandlerContext, msg: ByteBuf, out: ByteBuf) {
val dataLength = msg.readableBytes()
val inputBytes = ByteArray(dataLength)
msg.readBytes(inputBytes)
val encryptedBytes = tlsContext.encrypt(inputBytes)
out.writeBytes(encryptedBytes)
}
}
@@ -0,0 +1,20 @@
package de.fiereu.openmmo.server.protocol
import io.github.oshai.kotlinlogging.KotlinLogging
import io.netty.channel.ChannelHandlerContext
val log = KotlinLogging.logger {}
data class PacketEvent<T : Any>(
val ctx: ChannelHandlerContext,
val packet: T
)
fun <T : Any> PacketEvent<T>.disconnect(reason: () -> String = { "No reason provided" }) {
log.info { "Stopping server for client ${ctx.channel().remoteAddress()}: ${reason()}" }
ctx.close()
}
fun <T : Any> PacketEvent<T>.respond(packet: Any) {
ctx.channel().writeAndFlush(packet) // need to write to channel otherwise the ProtocolHandler will be skipped
}
@@ -0,0 +1,80 @@
package de.fiereu.openmmo.server.protocol.tls
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
interface TlsContext {
fun encrypt(data: ByteArray): ByteArray
fun decrypt(data: ByteArray): ByteArray
}
class NoOpTlsContext : TlsContext {
override fun encrypt(data: ByteArray): ByteArray = data
override fun decrypt(data: ByteArray): ByteArray = data
}
class DefaultTlsContext(
privateKey: PrivateKey,
publicKey: PublicKey
) : TlsContext {
companion object {
private val COMMON_IV = "IVDERIV".toByteArray()
private val CLIENT_KEY_SALT = "KeySalt".toByteArray() + byteArrayOf(1)
private val SERVER_KEY_SALT = "KeySalt".toByteArray() + byteArrayOf(2)
}
private var clientSeed = byteArrayOf(63, 24, -15, 98, 114, 7, 68, 24, -12, 109, -111, -105, 66, -96, -2, -55)
private var serverSeed = byteArrayOf(31, -102, -128, 60, -103, 38, 10, -117, -105, -50, 2, 116, -83, 57, 39, -76)
private val encryptionCipher: Cipher // Server to client
private val decryptionCipher: Cipher // Client to server
fun getClientSeed(): ByteArray = clientSeed.copyOf()
init {
val sharedSecret = performKeyAgreement(privateKey, publicKey)
if (sharedSecret.size * 8 >= 128) {
clientSeed = tripleHash(sharedSecret, CLIENT_KEY_SALT)
serverSeed = tripleHash(sharedSecret, SERVER_KEY_SALT)
}
encryptionCipher = createCipher(Cipher.ENCRYPT_MODE, serverSeed) // Server encrypts outgoing
decryptionCipher = createCipher(Cipher.DECRYPT_MODE, clientSeed) // Server decrypts incoming
}
private fun performKeyAgreement(privateKey: PrivateKey, publicKey: PublicKey): ByteArray {
val keyAgreement = KeyAgreement.getInstance("ECDH")
keyAgreement.init(privateKey)
keyAgreement.doPhase(publicKey, true)
return keyAgreement.generateSecret()
}
private fun tripleHash(data1: ByteArray, data2: ByteArray): ByteArray {
val sha256 = MessageDigest.getInstance("SHA-256")
sha256.update(data2)
sha256.update(data1)
sha256.update(data2)
val digest = sha256.digest()
return 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, COMMON_IV))
cipher.init(mode, key, iv)
return cipher
}
override fun encrypt(data: ByteArray): ByteArray =
encryptionCipher.update(data)
override fun decrypt(data: ByteArray): ByteArray =
decryptionCipher.update(data)
}
@@ -0,0 +1,75 @@
package de.fiereu.openmmo.server.protocol.tls
import de.fiereu.openmmo.protocols.Protocol
import de.fiereu.openmmo.protocols.tls.packets.ClientHelloPacket
import de.fiereu.openmmo.protocols.tls.packets.ClientReadyPacket
import de.fiereu.openmmo.protocols.tls.packets.ServerHelloPacket
import de.fiereu.openmmo.server.config.TlsConfig
import de.fiereu.openmmo.server.netty.DefaultChannelHandlerProvider
import de.fiereu.openmmo.server.netty.handlers.ProtocolHandler
import de.fiereu.openmmo.server.protocol.PacketEvent
import de.fiereu.openmmo.server.protocol.disconnect
import de.fiereu.openmmo.server.protocol.respond
import de.fiereu.openmmo.server.protocol.tls.checksum.ChecksumFactory
import io.github.oshai.kotlinlogging.KotlinLogging
import io.netty.buffer.ByteBuf
import io.netty.channel.ChannelHandlerContext
import java.security.KeyPairGenerator
import java.security.interfaces.ECPrivateKey
import java.security.interfaces.ECPublicKey
import java.security.spec.ECGenParameterSpec
private val log = KotlinLogging.logger {}
class TlsProtocolHandler(
protocol: Protocol,
private val tlsConfig: TlsConfig,
private val channelHandlerProvider: DefaultChannelHandlerProvider
) : ProtocolHandler(protocol) {
private val packetBuffer: MutableList<ByteBuf> = mutableListOf()
private val connectionKeyPair: Pair<ECPublicKey, ECPrivateKey>
init {
val keyPairGenerator = KeyPairGenerator.getInstance("EC")
keyPairGenerator.initialize(ECGenParameterSpec("secp256r1"))
keyPairGenerator.generateKeyPair().let {
connectionKeyPair = Pair(it.public as ECPublicKey, it.private as ECPrivateKey)
}
}
@Suppress("unchecked_cast") // The cast is in fact checked :D
override fun onPacketReceived(event: PacketEvent<*>) {
when (val packet = event.packet) {
is ClientHelloPacket -> onClientHello(event as PacketEvent<ClientHelloPacket>)
is ClientReadyPacket -> onClientReady(event as PacketEvent<ClientReadyPacket>)
else -> log.warn { "Unhandled TLS packet type: ${packet::class.simpleName}" }
}
}
override fun onActive(ctx: ChannelHandlerContext) {
log.info { "New client connected: ${ctx.channel().remoteAddress()}" }
}
fun onClientHello(event: PacketEvent<ClientHelloPacket>) {
if (System.currentTimeMillis() - event.packet.timestamp > 10_000) { // 10 seconds is arbitrary
event.disconnect { "Received stale ClientHello packet" }
return
}
event.respond(ServerHelloPacket(connectionKeyPair.first, tlsConfig.checksumSize))
}
fun onClientReady(event: PacketEvent<ClientReadyPacket>) {
val tlsContext = DefaultTlsContext(
connectionKeyPair.second,
event.packet.clientPublicKey
)
val checksum = ChecksumFactory.create(tlsConfig.checksumSize, tlsContext.getClientSeed())
channelHandlerProvider.switchChecksum(event.ctx, checksum)
channelHandlerProvider.switchTlsContext(event.ctx, tlsContext)
channelHandlerProvider.enableProtocolHandler(event.ctx)
log.info { "Client ${event.ctx.channel().remoteAddress()} completed TLS handshake. Switching to next protocol." }
}
}
@@ -0,0 +1,33 @@
package de.fiereu.openmmo.server.protocol.tls.checksum
import io.netty.buffer.ByteBuf
interface Checksum {
val size: Int
fun calculate(data: ByteBuf): ByteArray
fun verify(data: ByteBuf, expectedChecksum: ByteArray): Boolean
}
class NoOpChecksum : Checksum {
override val size: Int = 0
override fun calculate(data: ByteBuf): ByteArray = ByteArray(0)
override fun verify(data: ByteBuf, expectedChecksum: ByteArray): Boolean = true
}
object ChecksumFactory {
fun create(checksumSize: Int): Checksum {
return create(checksumSize, ByteArray(0))
}
fun create(checksumSize: Int, key: ByteArray): Checksum {
return when (checksumSize) {
0 -> NoOpChecksum()
2 -> Crc16Checksum()
in 4..32 -> HmacSha256Checksum(checksumSize, key)
else -> throw IllegalArgumentException("Unsupported checksum size: $checksumSize")
}
}
}
@@ -0,0 +1,70 @@
package de.fiereu.openmmo.server.protocol.tls.checksum
import io.netty.buffer.ByteBuf
class Crc16Checksum : Checksum {
override val size: Int = 2
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
)
}
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, expectedChecksum: ByteArray): Boolean {
if (expectedChecksum.size != 2) return false
val calculatedSum = hash(data)
val expectedSum = ((expectedChecksum[1].toInt() and 0xff) shl 8) or (expectedChecksum[0].toInt() and 0xff)
return calculatedSum == expectedSum
}
private fun hash(data: ByteBuf): Int {
var sum = 0
val readerIndex = data.readerIndex()
for (i in readerIndex until data.writerIndex()) {
val b = data.getByte(i)
sum = (sum ushr 8) xor table[(sum xor (b.toInt() and 0xff)) and 0xff]
}
return (sum and 0xffff)
}
}
@@ -0,0 +1,63 @@
package de.fiereu.openmmo.server.protocol.tls.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 {
private val mac: Mac
private var hashRound = 0
private var verifyRound = 0
init {
require(size in 4..32) { "HMAC-SHA256 size must be between 4 and 32 bytes" }
mac = Mac.getInstance("HmacSHA256")
mac.init(SecretKeySpec(key, "HmacSHA256"))
}
override fun calculate(data: ByteBuf): ByteArray {
// Read data without modifying the buffer's reader index
val dataBytes = ByteArray(data.readableBytes())
data.getBytes(data.readerIndex(), dataBytes)
mac.update(dataBytes)
mac.update(getBytes(hashRound++))
val result = mac.doFinal()
return result.copyOfRange(0, size)
}
override fun verify(data: ByteBuf, expectedChecksum: ByteArray): Boolean {
if (expectedChecksum.size != size) return false
// Read data without modifying the buffer's reader index
val dataBytes = ByteArray(data.readableBytes())
data.getBytes(data.readerIndex(), dataBytes)
mac.update(dataBytes)
mac.update(getBytes(verifyRound++))
val result = mac.doFinal()
val actualChecksum = result.copyOfRange(0, size)
return MessageDigest.isEqual(actualChecksum, expectedChecksum)
}
/**
* Convert an integer to a big endian byte array.
* @param value The integer to convert.
* @return The big endian byte array.
*/
private fun getBytes(value: Int): ByteArray {
return byteArrayOf(
((value shr 24) and 0xFF).toByte(),
((value shr 16) and 0xFF).toByte(),
((value shr 8) and 0xFF).toByte(),
(value and 0xFF).toByte()
)
}
}
@@ -0,0 +1,29 @@
package de.fiereu.openmmo.server.netty
import io.netty.buffer.ByteBuf
import io.netty.buffer.Unpooled
import io.netty.channel.embedded.EmbeddedChannel
fun EmbeddedChannel.readAllOutbound(): ByteBuf {
val encoded = Unpooled.buffer()
var buf: ByteBuf?
while (true) {
buf = this.readOutbound<ByteBuf>()
if (buf == null) break
encoded.writeBytes(buf)
buf.release()
}
return encoded
}
fun EmbeddedChannel.readAllInbound(): ByteBuf {
val encoded = Unpooled.buffer()
var buf: ByteBuf?
while (true) {
buf = this.readInbound<ByteBuf>()
if (buf == null) break
encoded.writeBytes(buf)
buf.release()
}
return encoded
}
@@ -0,0 +1,340 @@
package de.fiereu.openmmo.server.netty
import de.fiereu.openmmo.server.protocol.tls.checksum.ChecksumFactory
import de.fiereu.openmmo.server.protocol.tls.checksum.Crc16Checksum
import de.fiereu.openmmo.server.protocol.tls.checksum.HmacSha256Checksum
import de.fiereu.openmmo.server.protocol.tls.checksum.NoOpChecksum
import de.fiereu.openmmo.server.netty.handlers.checksum.ChecksumFrameDecoder
import de.fiereu.openmmo.server.netty.handlers.checksum.ChecksumFrameEncoder
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 ChecksumFrameCodecTest : FunSpec({
test("NoOpChecksum - encoder should not add checksum") {
val checksum = NoOpChecksum()
val encoder = ChecksumFrameEncoder(checksum)
val channel = EmbeddedChannel(encoder)
val payload = Unpooled.buffer()
.writeByte(0xAB)
.writeByte(0xCD)
channel.writeOutbound(payload)
val encoded = channel.readAllOutbound()
encoded.readableBytes() shouldBe 2 // 2 bytes payload (no checksum)
// Check payload
encoded.readByte() shouldBe 0xAB.toByte()
encoded.readByte() shouldBe 0xCD.toByte()
encoded.release()
channel.close()
}
test("NoOpChecksum - decoder should pass through without verification") {
val checksum = NoOpChecksum()
val decoder = ChecksumFrameDecoder(checksum)
val channel = EmbeddedChannel(decoder)
val input = Unpooled.buffer()
.writeByte(0xAB)
.writeByte(0xCD)
channel.writeInbound(input)
val decoded = channel.readAllInbound()
decoded.readableBytes() shouldBe 2
decoded.readByte() shouldBe 0xAB.toByte()
decoded.readByte() shouldBe 0xCD.toByte()
decoded.release()
channel.close()
}
test("CRC16 - encoder should append 2-byte checksum") {
val checksum = Crc16Checksum()
val encoder = ChecksumFrameEncoder(checksum)
val channel = EmbeddedChannel(encoder)
val payload = Unpooled.buffer()
.writeByte(0xAB)
.writeByte(0xCD)
channel.writeOutbound(payload)
val encoded = channel.readAllOutbound()
encoded.readableBytes() shouldBe 4 // 2 bytes payload + 2 bytes CRC16
// Check payload
encoded.readByte() shouldBe 0xAB.toByte()
encoded.readByte() shouldBe 0xCD.toByte()
// Check that checksum bytes are present (we don't verify exact values here)
encoded.readableBytes() shouldBe 2 // Should have 2 checksum bytes left
encoded.release()
channel.close()
}
test("CRC16 - decoder should verify and remove checksum") {
val checksum = Crc16Checksum()
val decoder = ChecksumFrameDecoder(checksum)
val channel = EmbeddedChannel(decoder)
// Create data and calculate its checksum
val originalData = Unpooled.buffer()
.writeByte(0xAB)
.writeByte(0xCD)
val checksumBytes = checksum.calculate(originalData)
// Create input with data + checksum
val input = Unpooled.buffer()
.writeByte(0xAB)
.writeByte(0xCD)
.writeBytes(checksumBytes)
channel.writeInbound(input)
val decoded = channel.readAllInbound()
decoded.readableBytes() shouldBe 2 // Checksum should be removed
decoded.readByte() shouldBe 0xAB.toByte()
decoded.readByte() shouldBe 0xCD.toByte()
originalData.release()
decoded.release()
channel.close()
}
test("CRC16 - decoder should drop packet with invalid checksum") {
val checksum = Crc16Checksum()
val decoder = ChecksumFrameDecoder(checksum)
val channel = EmbeddedChannel(decoder)
// Create input with data + invalid checksum
val input = Unpooled.buffer()
.writeByte(0xAB)
.writeByte(0xCD)
.writeByte(0xFF) // Invalid checksum
.writeByte(0xFF)
channel.writeInbound(input)
// Should not produce any output due to checksum failure
channel.readInbound<ByteBuf>() shouldBe null
channel.close()
}
test("HMAC-SHA256 - encoder should append variable-size checksum") {
val key = byteArrayOf(0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08)
val checksum = HmacSha256Checksum(8, key) // 8-byte HMAC
val encoder = ChecksumFrameEncoder(checksum)
val channel = EmbeddedChannel(encoder)
val payload = Unpooled.buffer()
.writeByte(0xAB)
.writeByte(0xCD)
channel.writeOutbound(payload)
val encoded = channel.readAllOutbound()
encoded.readableBytes() shouldBe 10 // 2 bytes payload + 8 bytes HMAC
// Check payload
encoded.readByte() shouldBe 0xAB.toByte()
encoded.readByte() shouldBe 0xCD.toByte()
// Check that HMAC bytes are present
encoded.readableBytes() shouldBe 8 // Should have 8 HMAC bytes left
encoded.release()
channel.close()
}
test("HMAC-SHA256 - decoder should verify and remove checksum") {
val key = byteArrayOf(0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08)
val checksum = HmacSha256Checksum(4, key) // 4-byte HMAC
val decoder = ChecksumFrameDecoder(checksum)
val channel = EmbeddedChannel(decoder)
// Create data and calculate its checksum
val originalData = Unpooled.buffer()
.writeByte(0xAB)
.writeByte(0xCD)
val checksumBytes = checksum.calculate(originalData)
// Create input with data + checksum
val input = Unpooled.buffer()
.writeByte(0xAB)
.writeByte(0xCD)
.writeBytes(checksumBytes)
channel.writeInbound(input)
val decoded = channel.readAllInbound()
decoded.readableBytes() shouldBe 2 // Checksum should be removed
decoded.readByte() shouldBe 0xAB.toByte()
decoded.readByte() shouldBe 0xCD.toByte()
originalData.release()
decoded.release()
channel.close()
}
test("HMAC-SHA256 - decoder should drop packet with invalid checksum") {
val key = byteArrayOf(0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08)
val checksum = HmacSha256Checksum(4, key)
val decoder = ChecksumFrameDecoder(checksum)
val channel = EmbeddedChannel(decoder)
// Create input with data + invalid checksum
val input = Unpooled.buffer()
.writeByte(0xAB)
.writeByte(0xCD)
.writeByte(0xFF) // Invalid checksum
.writeByte(0xFF)
.writeByte(0xFF)
.writeByte(0xFF)
channel.writeInbound(input)
// Should not produce any output due to checksum failure
channel.readInbound<ByteBuf>() shouldBe null
channel.close()
}
test("roundtrip - NoOpChecksum encoding and decoding") {
val checksum = NoOpChecksum()
val encoder = ChecksumFrameEncoder(checksum)
val decoder = ChecksumFrameDecoder(checksum)
val channel = EmbeddedChannel(encoder, decoder)
val originalPayload = byteArrayOf(0xDE.toByte(), 0xAD.toByte(), 0xBE.toByte(), 0xEF.toByte())
val input = Unpooled.buffer().writeBytes(originalPayload)
// Encode then decode
channel.writeOutbound(input) shouldBe true
val encoded = channel.readAllOutbound()
channel.writeInbound(encoded) shouldBe true
val decoded = channel.readAllInbound()
decoded.readableBytes() shouldBe originalPayload.size
for (expectedByte in originalPayload) {
decoded.readByte() shouldBe expectedByte
}
decoded.release()
channel.close()
}
test("roundtrip - CRC16 encoding and decoding") {
val encoderChecksum = Crc16Checksum()
val decoderChecksum = Crc16Checksum()
val encoder = ChecksumFrameEncoder(encoderChecksum)
val decoder = ChecksumFrameDecoder(decoderChecksum)
val originalPayload = byteArrayOf(0xDE.toByte(), 0xAD.toByte(), 0xBE.toByte(), 0xEF.toByte())
val input = Unpooled.buffer().writeBytes(originalPayload)
// Encode
val encoderChannel = EmbeddedChannel(encoder)
encoderChannel.writeOutbound(input) shouldBe true
val encoded = encoderChannel.readAllOutbound()
encoded.readableBytes() shouldBe 6 // 4 bytes payload + 2 bytes CRC16
// Decode
val decoderChannel = EmbeddedChannel(decoder)
decoderChannel.writeInbound(encoded) shouldBe true
val decoded = decoderChannel.readAllInbound()
decoded.readableBytes() shouldBe originalPayload.size
for (expectedByte in originalPayload) {
decoded.readByte() shouldBe expectedByte
}
decoded.release()
encoderChannel.close()
decoderChannel.close()
}
test("roundtrip - HMAC-SHA256 encoding and decoding") {
val key = byteArrayOf(0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08)
val encoderChecksum = HmacSha256Checksum(16, key)
val decoderChecksum = HmacSha256Checksum(16, key)
val encoder = ChecksumFrameEncoder(encoderChecksum)
val decoder = ChecksumFrameDecoder(decoderChecksum)
val originalPayload = byteArrayOf(0xDE.toByte(), 0xAD.toByte(), 0xBE.toByte(), 0xEF.toByte())
val input = Unpooled.buffer().writeBytes(originalPayload)
// Encode
val encoderChannel = EmbeddedChannel(encoder)
encoderChannel.writeOutbound(input) shouldBe true
val encoded = encoderChannel.readAllOutbound()
encoded.readableBytes() shouldBe 20 // 4 bytes payload + 16 bytes HMAC
// Decode
val decoderChannel = EmbeddedChannel(decoder)
decoderChannel.writeInbound(encoded) shouldBe true
val decoded = decoderChannel.readAllInbound()
decoded.readableBytes() shouldBe originalPayload.size
for (expectedByte in originalPayload) {
decoded.readByte() shouldBe expectedByte
}
decoded.release()
encoderChannel.close()
decoderChannel.close()
}
test("decoder should handle packet too small for checksum") {
val checksum = Crc16Checksum()
val decoder = ChecksumFrameDecoder(checksum)
val channel = EmbeddedChannel(decoder)
// Send packet smaller than checksum size
val input = Unpooled.buffer()
.writeByte(0xAB) // Only 1 byte, but CRC16 needs 2 bytes
channel.writeInbound(input)
// Should not produce any output
channel.readInbound<ByteBuf>() shouldBe null
channel.close()
}
test("ChecksumFactory - create with size only") {
val noOpChecksum = ChecksumFactory.create(0)
(noOpChecksum is NoOpChecksum) shouldBe true
val crc16Checksum = ChecksumFactory.create(2)
(crc16Checksum is Crc16Checksum) shouldBe true
}
test("ChecksumFactory - create with size and key") {
val key = byteArrayOf(0x01, 0x02, 0x03, 0x04)
val noOpChecksum = ChecksumFactory.create(0, key)
(noOpChecksum is NoOpChecksum) shouldBe true
val crc16Checksum = ChecksumFactory.create(2, key)
(crc16Checksum is Crc16Checksum) shouldBe true
val hmacChecksum = ChecksumFactory.create(8, key)
(hmacChecksum is HmacSha256Checksum) shouldBe true
hmacChecksum.size shouldBe 8
}
})
@@ -0,0 +1,179 @@
package de.fiereu.openmmo.server.netty
import de.fiereu.openmmo.server.netty.handlers.frame.PacketFrameDecoder
import de.fiereu.openmmo.server.netty.handlers.frame.PacketFrameEncoder
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
import io.kotest.matchers.nulls.shouldBeNull
import io.netty.buffer.ByteBuf
import io.netty.buffer.Unpooled
import io.netty.channel.embedded.EmbeddedChannel
class PacketFrameCodecTest : FunSpec({
test("decoder should decode frame with correct length prefix") {
val decoder = PacketFrameDecoder()
val channel = EmbeddedChannel(decoder)
// Create input: length 4 (0x0004) + payload [0xAB, 0xCD]
// Length field includes itself (2 bytes) + payload (2 bytes) = 4 total
val input = Unpooled.buffer()
.writeShortLE(4) // Length field (little endian)
.writeByte(0xAB)
.writeByte(0xCD)
channel.writeInbound(input)
val decoded = channel.readAllInbound()
decoded.readableBytes() shouldBe 2
decoded.readByte() shouldBe 0xAB.toByte()
decoded.readByte() shouldBe 0xCD.toByte()
decoded.release()
channel.close()
}
test("decoder should handle empty payload") {
val decoder = PacketFrameDecoder()
val channel = EmbeddedChannel(decoder)
// Create input: length 2 (only the length field itself)
val input = Unpooled.buffer()
.writeShortLE(2) // Length field (little endian)
channel.writeInbound(input)
val decoded = channel.readAllInbound()
decoded.readableBytes() shouldBe 0
decoded.release()
channel.close()
}
test("decoder should handle larger payload") {
val decoder = PacketFrameDecoder()
val channel = EmbeddedChannel(decoder)
val payload = byteArrayOf(0x01, 0x02, 0x03, 0x04, 0x05)
val input = Unpooled.buffer()
.writeShortLE(payload.size + 2) // Length includes length field
.writeBytes(payload)
channel.writeInbound(input)
val decoded = channel.readAllInbound()
decoded.readableBytes() shouldBe payload.size
for (expectedByte in payload) {
decoded.readByte() shouldBe expectedByte
}
decoded.release()
channel.close()
}
test("decoder should not decode incomplete frame") {
val decoder = PacketFrameDecoder()
val channel = EmbeddedChannel(decoder)
// Send only the length field without payload
val input = Unpooled.buffer()
.writeShortLE(10) // Claims 10 bytes total but we only send 2
channel.writeInbound(input)
val decoded = channel.readInbound<ByteBuf>()
decoded.shouldBeNull()
channel.close()
}
test("encoder should prepend correct length field") {
val encoder = PacketFrameEncoder()
val channel = EmbeddedChannel(encoder)
val payload = Unpooled.buffer()
.writeByte(0xAB)
.writeByte(0xCD)
channel.writeOutbound(payload)
val encoded = channel.readAllOutbound()
encoded.readableBytes() shouldBe 4
// Check length field (should be 4: 2 bytes length + 2 bytes payload)
encoded.readUnsignedShortLE() shouldBe 4
// Check payload
encoded.readByte() shouldBe 0xAB.toByte()
encoded.readByte() shouldBe 0xCD.toByte()
encoded.release()
channel.close()
}
test("encoder should handle empty payload") {
val encoder = PacketFrameEncoder()
val channel = EmbeddedChannel(encoder)
val payload = Unpooled.buffer()
channel.writeOutbound(payload)
val encoded = channel.readAllOutbound()
encoded.readableBytes() shouldBe 2
// Check length field (should be 2: only the length field)
encoded.readUnsignedShortLE() shouldBe 2
encoded.release()
channel.close()
}
test("encoder should handle larger payload") {
val encoder = PacketFrameEncoder()
val channel = EmbeddedChannel(encoder)
val payloadData = byteArrayOf(0x01, 0x02, 0x03, 0x04, 0x05)
val payload = Unpooled.buffer().writeBytes(payloadData)
channel.writeOutbound(payload)
val encoded = channel.readAllOutbound()
encoded.readableBytes() shouldBe (payloadData.size + 2)
// Check length field
encoded.readUnsignedShortLE() shouldBe (payloadData.size + 2)
// Check payload
for (expectedByte in payloadData) {
encoded.readByte() shouldBe expectedByte
}
encoded.release()
channel.close()
}
test("roundtrip encoding and decoding should work correctly") {
val encoder = PacketFrameEncoder()
val decoder = PacketFrameDecoder()
val channel = EmbeddedChannel(encoder, decoder)
val originalPayload = byteArrayOf(0xDE.toByte(), 0xAD.toByte(), 0xBE.toByte(), 0xEF.toByte())
val input = Unpooled.buffer().writeBytes(originalPayload)
// Encode then decode
channel.writeOutbound(input) shouldBe true
val encoded = channel.readAllOutbound()
channel.writeInbound(encoded) shouldBe true
val decoded = channel.readAllInbound()
decoded.readableBytes() shouldBe originalPayload.size
for (expectedByte in originalPayload) {
decoded.readByte() shouldBe expectedByte
}
decoded.release()
channel.close()
}
})
@@ -0,0 +1,380 @@
package de.fiereu.openmmo.server.netty
import de.fiereu.openmmo.server.protocol.tls.checksum.Crc16Checksum
import de.fiereu.openmmo.server.protocol.tls.checksum.HmacSha256Checksum
import de.fiereu.openmmo.server.protocol.tls.checksum.NoOpChecksum
import de.fiereu.openmmo.server.netty.handlers.checksum.ChecksumFrameDecoder
import de.fiereu.openmmo.server.netty.handlers.checksum.ChecksumFrameEncoder
import de.fiereu.openmmo.server.netty.handlers.frame.PacketFrameDecoder
import de.fiereu.openmmo.server.netty.handlers.frame.PacketFrameEncoder
import de.fiereu.openmmo.server.netty.handlers.tls.TlsDecryptionHandler
import de.fiereu.openmmo.server.netty.handlers.tls.TlsEncryptionHandler
import de.fiereu.openmmo.server.protocol.tls.DefaultTlsContext
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
import io.kotest.matchers.shouldNotBe
import io.netty.buffer.ByteBuf
import io.netty.buffer.Unpooled
import io.netty.channel.embedded.EmbeddedChannel
import io.mockk.every
import io.mockk.mockk
import javax.crypto.Cipher
class PipelineIntegrationTest : FunSpec({
test("complete outbound pipeline - TLS encryption -> checksum -> frame encoding (NoOpChecksum)") {
val tlsContext = createMockTlsContext()
val checksum = NoOpChecksum()
// Create outbound pipeline: TLS encryption -> checksum -> frame encoding
// Note: In Netty outbound pipeline, handlers are processed in REVERSE order
val tlsEncoder = TlsEncryptionHandler(tlsContext)
val checksumEncoder = ChecksumFrameEncoder(checksum)
val frameEncoder = PacketFrameEncoder()
val outboundChannel = EmbeddedChannel(frameEncoder, checksumEncoder, tlsEncoder)
val originalData = byteArrayOf(0xAB.toByte(), 0xCD.toByte(), 0xEF.toByte(), 0x12.toByte())
val input = Unpooled.buffer().writeBytes(originalData)
outboundChannel.writeOutbound(input) shouldBe true
val finalOutput = outboundChannel.readAllOutbound()
// Expected structure: [length (2 bytes)] + [encrypted_data (4 bytes)] + [checksum (0 bytes for NoOp)]
finalOutput.readableBytes() shouldBe 6 // 2 bytes length + 4 bytes encrypted data + 0 bytes checksum
// Read and verify length field (little endian)
val lengthField = finalOutput.readUnsignedShortLE()
lengthField shouldBe 6 // Length includes itself (2) + encrypted data (4) + checksum (0)
// Read the encrypted data
val encryptedData = ByteArray(4)
finalOutput.readBytes(encryptedData)
// Encrypted data should be different from original (XOR with 0x42)
encryptedData shouldNotBe originalData
// Verify it's actually XOR encrypted
val expectedEncrypted = originalData.map { (it.toInt() xor 0x42).toByte() }.toByteArray()
encryptedData shouldBe expectedEncrypted
finalOutput.release()
outboundChannel.close()
}
test("complete outbound pipeline - TLS encryption -> checksum -> frame encoding (CRC16)") {
val tlsContext = createMockTlsContext()
val checksum = Crc16Checksum()
val tlsEncoder = TlsEncryptionHandler(tlsContext)
val checksumEncoder = ChecksumFrameEncoder(checksum)
val frameEncoder = PacketFrameEncoder()
val outboundChannel = EmbeddedChannel(frameEncoder, checksumEncoder, tlsEncoder)
val originalData = byteArrayOf(0xAB.toByte(), 0xCD.toByte(), 0xEF.toByte(), 0x12.toByte())
val input = Unpooled.buffer().writeBytes(originalData)
outboundChannel.writeOutbound(input) shouldBe true
val finalOutput = outboundChannel.readAllOutbound()
// Expected structure: [length (2 bytes)] + [encrypted_data (4 bytes)] + [crc16 checksum (2 bytes)]
finalOutput.readableBytes() shouldBe 8 // 2 + 4 + 2
val lengthField = finalOutput.readUnsignedShortLE()
lengthField shouldBe 8
// Read the encrypted data
val encryptedData = ByteArray(4)
finalOutput.readBytes(encryptedData)
encryptedData shouldNotBe originalData
// Read the CRC16 checksum
val checksumData = ByteArray(2)
finalOutput.readBytes(checksumData)
// Verify checksum exists (non-zero for this data pattern)
checksumData shouldNotBe byteArrayOf(0, 0)
finalOutput.release()
outboundChannel.close()
}
test("complete outbound pipeline - TLS encryption -> checksum -> frame encoding (HMAC-SHA256)") {
val tlsContext = createMockTlsContext()
val key = byteArrayOf(0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08)
val checksum = HmacSha256Checksum(8, key)
val tlsEncoder = TlsEncryptionHandler(tlsContext)
val checksumEncoder = ChecksumFrameEncoder(checksum)
val frameEncoder = PacketFrameEncoder()
val outboundChannel = EmbeddedChannel(frameEncoder, checksumEncoder, tlsEncoder)
val originalData = byteArrayOf(0xAB.toByte(), 0xCD.toByte(), 0xEF.toByte(), 0x12.toByte())
val input = Unpooled.buffer().writeBytes(originalData)
outboundChannel.writeOutbound(input) shouldBe true
val finalOutput = outboundChannel.readAllOutbound()
// Expected structure: [length (2 bytes)] + [encrypted_data (4 bytes)] + [hmac (8 bytes)]
finalOutput.readableBytes() shouldBe 14 // 2 + 4 + 8
val lengthField = finalOutput.readUnsignedShortLE()
lengthField shouldBe 14
// Read the encrypted data
val encryptedData = ByteArray(4)
finalOutput.readBytes(encryptedData)
encryptedData shouldNotBe originalData
// Read the HMAC
val hmacData = ByteArray(8)
finalOutput.readBytes(hmacData)
// HMAC should exist and be non-zero
hmacData shouldNotBe ByteArray(8) { 0 }
finalOutput.release()
outboundChannel.close()
}
test("complete inbound pipeline - frame decoding -> checksum verification -> TLS decryption (NoOpChecksum)") {
val tlsContext = createMockTlsContext()
val checksum = NoOpChecksum()
// Create inbound pipeline: frame decoding -> checksum verification -> TLS decryption
val frameDecoder = PacketFrameDecoder()
val checksumDecoder = ChecksumFrameDecoder(checksum)
val tlsDecoder = TlsDecryptionHandler(tlsContext)
val inboundChannel = EmbeddedChannel(frameDecoder, checksumDecoder, tlsDecoder)
val originalData = byteArrayOf(0xAB.toByte(), 0xCD.toByte(), 0xEF.toByte(), 0x12.toByte())
// First encrypt the data to simulate what would come from the outbound pipeline
val encryptedData = originalData.map { (it.toInt() xor 0x42).toByte() }.toByteArray()
// Create the complete packet: length + encrypted data (no checksum for NoOp)
val packetLength = 2 + encryptedData.size // length field + data
val completePacket = Unpooled.buffer()
.writeShortLE(packetLength)
.writeBytes(encryptedData)
inboundChannel.writeInbound(completePacket) shouldBe true
val decryptedOutput = inboundChannel.readAllInbound()
decryptedOutput.readableBytes() shouldBe originalData.size
val decryptedBytes = ByteArray(decryptedOutput.readableBytes())
decryptedOutput.readBytes(decryptedBytes)
// Should get back the original data
decryptedBytes shouldBe originalData
decryptedOutput.release()
inboundChannel.close()
}
test("complete inbound pipeline - frame decoding -> checksum verification -> TLS decryption (CRC16)") {
val tlsContext = createMockTlsContext()
val checksum = Crc16Checksum()
val frameDecoder = PacketFrameDecoder()
val checksumDecoder = ChecksumFrameDecoder(checksum)
val tlsDecoder = TlsDecryptionHandler(tlsContext)
val inboundChannel = EmbeddedChannel(frameDecoder, checksumDecoder, tlsDecoder)
val originalData = byteArrayOf(0xAB.toByte(), 0xCD.toByte(), 0xEF.toByte(), 0x12.toByte())
// Encrypt the data
val encryptedData = originalData.map { (it.toInt() xor 0x42).toByte() }.toByteArray()
// Calculate checksum for the encrypted data
val encryptedBuffer = Unpooled.buffer().writeBytes(encryptedData)
val checksumBytes = checksum.calculate(encryptedBuffer)
encryptedBuffer.release()
// Create the complete packet: length + encrypted data + checksum
val packetLength = 2 + encryptedData.size + checksumBytes.size
val completePacket = Unpooled.buffer()
.writeShortLE(packetLength)
.writeBytes(encryptedData)
.writeBytes(checksumBytes)
inboundChannel.writeInbound(completePacket) shouldBe true
val decryptedOutput = inboundChannel.readAllInbound()
decryptedOutput.readableBytes() shouldBe originalData.size
val decryptedBytes = ByteArray(decryptedOutput.readableBytes())
decryptedOutput.readBytes(decryptedBytes)
decryptedBytes shouldBe originalData
decryptedOutput.release()
inboundChannel.close()
}
test("complete inbound pipeline - frame decoding -> checksum verification -> TLS decryption (HMAC-SHA256)") {
val tlsContext = createMockTlsContext()
val key = byteArrayOf(0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08)
val checksum = HmacSha256Checksum(8, key)
val frameDecoder = PacketFrameDecoder()
val checksumDecoder = ChecksumFrameDecoder(checksum)
val tlsDecoder = TlsDecryptionHandler(tlsContext)
val inboundChannel = EmbeddedChannel(frameDecoder, checksumDecoder, tlsDecoder)
val originalData = byteArrayOf(0xAB.toByte(), 0xCD.toByte(), 0xEF.toByte(), 0x12.toByte())
// Encrypt the data
val encryptedData = originalData.map { (it.toInt() xor 0x42).toByte() }.toByteArray()
// Calculate HMAC for the encrypted data
val encryptedBuffer = Unpooled.buffer().writeBytes(encryptedData)
val hmacBytes = checksum.calculate(encryptedBuffer)
encryptedBuffer.release()
// Create the complete packet: length + encrypted data + hmac
val packetLength = 2 + encryptedData.size + hmacBytes.size
val completePacket = Unpooled.buffer()
.writeShortLE(packetLength)
.writeBytes(encryptedData)
.writeBytes(hmacBytes)
inboundChannel.writeInbound(completePacket) shouldBe true
val decryptedOutput = inboundChannel.readAllInbound()
decryptedOutput.readableBytes() shouldBe originalData.size
val decryptedBytes = ByteArray(decryptedOutput.readableBytes())
decryptedOutput.readBytes(decryptedBytes)
decryptedBytes shouldBe originalData
decryptedOutput.release()
inboundChannel.close()
}
test("complete roundtrip - outbound then inbound pipeline should preserve original data") {
val tlsContext = createMockTlsContext()
val checksum = Crc16Checksum()
// Outbound pipeline: TLS encryption -> checksum -> frame encoding
val tlsEncoder = TlsEncryptionHandler(tlsContext)
val checksumEncoder = ChecksumFrameEncoder(checksum)
val frameEncoder = PacketFrameEncoder()
val outboundChannel = EmbeddedChannel(frameEncoder, checksumEncoder, tlsEncoder)
// Inbound pipeline: frame decoding -> checksum verification -> TLS decryption
val frameDecoder = PacketFrameDecoder()
val checksumDecoder = ChecksumFrameDecoder(checksum)
val tlsDecoder = TlsDecryptionHandler(tlsContext)
val inboundChannel = EmbeddedChannel(frameDecoder, checksumDecoder, tlsDecoder)
val originalData = byteArrayOf(0xDE.toByte(), 0xAD.toByte(), 0xBE.toByte(), 0xEF.toByte())
val input = Unpooled.buffer().writeBytes(originalData)
// Process through outbound pipeline
outboundChannel.writeOutbound(input) shouldBe true
val processedPacket = outboundChannel.readAllOutbound()
// Process through inbound pipeline
inboundChannel.writeInbound(processedPacket) shouldBe true
val finalOutput = inboundChannel.readAllInbound()
// Should get back the original data
finalOutput.readableBytes() shouldBe originalData.size
val finalBytes = ByteArray(finalOutput.readableBytes())
finalOutput.readBytes(finalBytes)
finalBytes shouldBe originalData
finalOutput.release()
outboundChannel.close()
inboundChannel.close()
}
test("complete roundtrip with multiple packets should maintain order and content") {
// Create separate TLS contexts for encoder and decoder to avoid stream cipher sync issues
val encoderTlsContext = createMockTlsContext()
val decoderTlsContext = createMockTlsContext() // Same XOR key, but separate cipher state
val key = byteArrayOf(1, 2, 3, 4, 5, 6, 7, 8)
// Create separate checksum instances for encoder and decoder
// Both start with the same key but maintain separate round counters
val encoderChecksum = HmacSha256Checksum(4, key)
val decoderChecksum = HmacSha256Checksum(4, key)
// Create pipelines
val tlsEncoder = TlsEncryptionHandler(encoderTlsContext)
val checksumEncoder = ChecksumFrameEncoder(encoderChecksum)
val frameEncoder = PacketFrameEncoder()
val outboundChannel = EmbeddedChannel(frameEncoder, checksumEncoder, tlsEncoder)
val frameDecoder = PacketFrameDecoder()
val checksumDecoder = ChecksumFrameDecoder(decoderChecksum)
val tlsDecoder = TlsDecryptionHandler(decoderTlsContext)
val inboundChannel = EmbeddedChannel(frameDecoder, checksumDecoder, tlsDecoder)
val packets = listOf(
byteArrayOf(0x01, 0x02, 0x03),
byteArrayOf(0x04, 0x05, 0x06, 0x07),
byteArrayOf(0x08, 0x09),
byteArrayOf(0x0A, 0x0B, 0x0C, 0x0D, 0x0E)
)
val processedPackets = mutableListOf<ByteArray>()
// Process each packet through the complete pipeline
for (originalPacket in packets) {
val input = Unpooled.buffer().writeBytes(originalPacket)
// Outbound processing
outboundChannel.writeOutbound(input) shouldBe true
val processedPacket = outboundChannel.readAllOutbound()
// Inbound processing
inboundChannel.writeInbound(processedPacket) shouldBe true
val finalOutput = inboundChannel.readAllInbound()
val finalBytes = ByteArray(finalOutput.readableBytes())
finalOutput.readBytes(finalBytes)
processedPackets.add(finalBytes)
finalOutput.release()
}
// Verify all packets were processed correctly
packets.forEachIndexed { index, originalPacket ->
processedPackets[index] shouldBe originalPacket
}
outboundChannel.close()
inboundChannel.close()
}
test("inbound pipeline should reject packet with invalid checksum") {
val tlsContext = createMockTlsContext()
val checksum = Crc16Checksum()
val frameDecoder = PacketFrameDecoder()
val checksumDecoder = ChecksumFrameDecoder(checksum)
val tlsDecoder = TlsDecryptionHandler(tlsContext)
val inboundChannel = EmbeddedChannel(frameDecoder, checksumDecoder, tlsDecoder)
val originalData = byteArrayOf(0xAB.toByte(), 0xCD.toByte(), 0xEF.toByte(), 0x12.toByte())
val encryptedData = originalData.map { (it.toInt() xor 0x42).toByte() }.toByteArray()
// Create packet with invalid checksum
val packetLength = 2 + encryptedData.size + 2 // length + data + invalid checksum
val invalidPacket = Unpooled.buffer()
.writeShortLE(packetLength)
.writeBytes(encryptedData)
.writeByte(0xFF) // Invalid checksum
.writeByte(0xFF)
inboundChannel.writeInbound(invalidPacket) shouldBe false
// Should not produce any output due to checksum failure
inboundChannel.readInbound<ByteBuf>() shouldBe null
inboundChannel.close()
}
})
@@ -0,0 +1,248 @@
package de.fiereu.openmmo.server.netty
import de.fiereu.openmmo.server.netty.handlers.tls.TlsDecryptionHandler
import de.fiereu.openmmo.server.netty.handlers.tls.TlsEncryptionHandler
import de.fiereu.openmmo.server.protocol.tls.DefaultTlsContext
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
import io.kotest.matchers.shouldNotBe
import io.netty.buffer.ByteBuf
import io.netty.buffer.Unpooled
import io.netty.channel.embedded.EmbeddedChannel
import io.mockk.every
import io.mockk.mockk
import javax.crypto.Cipher
class TlsHandlerTest : FunSpec({
test("TlsEncryptionHandler should encrypt data") {
val tlsContext = createMockTlsContext()
val encoder = TlsEncryptionHandler(tlsContext)
val channel = EmbeddedChannel(encoder)
val originalData = byteArrayOf(0xAB.toByte(), 0xCD.toByte(), 0xEF.toByte(), 0x12.toByte())
val input = Unpooled.buffer().writeBytes(originalData)
channel.writeOutbound(input)
val encrypted = channel.readAllOutbound()
encrypted.readableBytes() shouldBe originalData.size
// The encrypted data should be different from the original
val encryptedBytes = ByteArray(encrypted.readableBytes())
encrypted.readBytes(encryptedBytes)
encryptedBytes shouldNotBe originalData
encrypted.release()
channel.close()
}
test("TlsDecryptionHandler should decrypt data") {
val tlsContext = createMockTlsContext()
val decoder = TlsDecryptionHandler(tlsContext)
val channel = EmbeddedChannel(decoder)
val originalData = byteArrayOf(0xAB.toByte(), 0xCD.toByte(), 0xEF.toByte(), 0x12.toByte())
// First encrypt the data using the TLS context directly
val encryptedBytes = tlsContext.encrypt(originalData)
val input = Unpooled.buffer().writeBytes(encryptedBytes)
channel.writeInbound(input)
val decrypted = channel.readAllInbound()
decrypted.readableBytes() shouldBe originalData.size
val decryptedBytes = ByteArray(decrypted.readableBytes())
decrypted.readBytes(decryptedBytes)
decryptedBytes shouldBe originalData
decrypted.release()
channel.close()
}
test("TlsEncryptionHandler should handle empty data") {
val tlsContext = createMockTlsContext()
val encoder = TlsEncryptionHandler(tlsContext)
val channel = EmbeddedChannel(encoder)
val input = Unpooled.buffer() // Empty buffer
channel.writeOutbound(input)
val encrypted = channel.readAllOutbound()
encrypted.readableBytes() shouldBe 0
encrypted.release()
channel.close()
}
test("TlsDecryptionHandler should handle empty data") {
val tlsContext = createMockTlsContext()
val decoder = TlsDecryptionHandler(tlsContext)
val channel = EmbeddedChannel(decoder)
val input = Unpooled.buffer() // Empty buffer
channel.writeInbound(input)
// Should not produce any output for empty input
channel.readInbound<ByteBuf>() shouldBe null
channel.close()
}
test("TlsEncryptionHandler should handle large data") {
val tlsContext = createMockTlsContext()
val encoder = TlsEncryptionHandler(tlsContext)
val channel = EmbeddedChannel(encoder)
val largeData = ByteArray(1024) { it.toByte() }
val input = Unpooled.buffer().writeBytes(largeData)
channel.writeOutbound(input)
val encrypted = channel.readAllOutbound()
encrypted.readableBytes() shouldBe largeData.size
// The encrypted data should be different from the original
val encryptedBytes = ByteArray(encrypted.readableBytes())
encrypted.readBytes(encryptedBytes)
encryptedBytes shouldNotBe largeData
encrypted.release()
channel.close()
}
test("TlsDecryptionHandler should handle large data") {
val tlsContext = createMockTlsContext()
val decoder = TlsDecryptionHandler(tlsContext)
val channel = EmbeddedChannel(decoder)
val largeData = ByteArray(1024) { it.toByte() }
// First encrypt the data using the TLS context directly
val encryptedBytes = tlsContext.encrypt(largeData)
val input = Unpooled.buffer().writeBytes(encryptedBytes)
channel.writeInbound(input)
val decrypted = channel.readAllInbound()
decrypted.readableBytes() shouldBe largeData.size
val decryptedBytes = ByteArray(decrypted.readableBytes())
decrypted.readBytes(decryptedBytes)
decryptedBytes shouldBe largeData
decrypted.release()
channel.close()
}
test("roundtrip - encryption then decryption should preserve data") {
val tlsContext = createMockTlsContext()
val encoder = TlsEncryptionHandler(tlsContext)
val decoder = TlsDecryptionHandler(tlsContext)
val originalData = byteArrayOf(0xDE.toByte(), 0xAD.toByte(), 0xBE.toByte(), 0xEF.toByte())
val input = Unpooled.buffer().writeBytes(originalData)
// Encrypt
val encryptChannel = EmbeddedChannel(encoder)
encryptChannel.writeOutbound(input) shouldBe true
val encrypted = encryptChannel.readAllOutbound()
// Decrypt
val decryptChannel = EmbeddedChannel(decoder)
decryptChannel.writeInbound(encrypted) shouldBe true
val decrypted = decryptChannel.readAllInbound()
decrypted.readableBytes() shouldBe originalData.size
val decryptedBytes = ByteArray(decrypted.readableBytes())
decrypted.readBytes(decryptedBytes)
decryptedBytes shouldBe originalData
decrypted.release()
encryptChannel.close()
decryptChannel.close()
}
test("roundtrip - multiple packets should maintain stream cipher state") {
val tlsContext = createMockTlsContext()
val encoder = TlsEncryptionHandler(tlsContext)
val decoder = TlsDecryptionHandler(tlsContext)
val encryptChannel = EmbeddedChannel(encoder)
val decryptChannel = EmbeddedChannel(decoder)
val packets = listOf(
byteArrayOf(0x01, 0x02, 0x03),
byteArrayOf(0x04, 0x05),
byteArrayOf(0x06, 0x07, 0x08, 0x09)
)
val decryptedPackets = mutableListOf<ByteArray>()
// Process each packet in order (maintaining stream cipher state)
for (packet in packets) {
val input = Unpooled.buffer().writeBytes(packet)
// Encrypt
encryptChannel.writeOutbound(input) shouldBe true
val encrypted = encryptChannel.readAllOutbound()
// Decrypt
decryptChannel.writeInbound(encrypted) shouldBe true
val decrypted = decryptChannel.readAllInbound()
val decryptedBytes = ByteArray(decrypted.readableBytes())
decrypted.readBytes(decryptedBytes)
decryptedPackets.add(decryptedBytes)
decrypted.release()
}
// Verify all packets were decrypted correctly
packets.forEachIndexed { index, originalPacket ->
decryptedPackets[index] shouldBe originalPacket
}
encryptChannel.close()
decryptChannel.close()
}
test("two different TlsContexts should produce different ciphertexts") {
val tlsContext1 = createMockTlsContext()
val tlsContext2 = createMockTlsContext(0x24)
val encoder1 = TlsEncryptionHandler(tlsContext1)
val encoder2 = TlsEncryptionHandler(tlsContext2)
val channel1 = EmbeddedChannel(encoder1)
val channel2 = EmbeddedChannel(encoder2)
val originalData = byteArrayOf(0xAB.toByte(), 0xCD.toByte(), 0xEF.toByte(), 0x12.toByte())
val input1 = Unpooled.buffer().writeBytes(originalData)
val input2 = Unpooled.buffer().writeBytes(originalData)
channel1.writeOutbound(input1)
channel2.writeOutbound(input2)
val encrypted1 = channel1.readAllOutbound()
val encrypted2 = channel2.readAllOutbound()
encrypted1.readableBytes() shouldBe encrypted2.readableBytes()
val encrypted1Bytes = ByteArray(encrypted1.readableBytes())
val encrypted2Bytes = ByteArray(encrypted2.readableBytes())
encrypted1.readBytes(encrypted1Bytes)
encrypted2.readBytes(encrypted2Bytes)
// Different contexts should produce different ciphertext
encrypted1Bytes shouldNotBe encrypted2Bytes
encrypted1.release()
encrypted2.release()
channel1.close()
channel2.close()
}
})
@@ -0,0 +1,21 @@
package de.fiereu.openmmo.server.netty
import de.fiereu.openmmo.server.protocol.tls.TlsContext
import io.mockk.every
import io.mockk.mockk
fun createMockTlsContext(xorKey: Int = 0x42): TlsContext {
val mockTlsContext = mockk<TlsContext>(relaxed = true)
every { mockTlsContext.encrypt(any<ByteArray>()) } answers {
val input = firstArg<ByteArray>()
input.map { (it.toInt() xor xorKey).toByte() }.toByteArray()
}
every { mockTlsContext.decrypt(any<ByteArray>()) } answers {
val input = firstArg<ByteArray>()
input.map { (it.toInt() xor xorKey).toByte() }.toByteArray()
}
return mockTlsContext
}