Skip to content

Commit

Permalink
Remove hacky ways of setrting context
Browse files Browse the repository at this point in the history
  • Loading branch information
akolosov-n committed Aug 21, 2024
1 parent 51f871b commit 9bf5a1c
Show file tree
Hide file tree
Showing 6 changed files with 12 additions and 112 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ import io.netty.channel.ChannelHandlerContext
import io.netty.channel.ChannelPromise
import io.netty.channel.socket.DatagramPacket
import org.opencoap.ssl.SslConfig
import org.opencoap.ssl.SslException
import org.opencoap.ssl.transport.ByteBufferPacket
import org.opencoap.ssl.transport.DtlsServer
import org.opencoap.ssl.transport.DtlsSessionLifecycleCallbacks
Expand All @@ -32,7 +31,6 @@ import java.time.Duration
import java.util.concurrent.CompletableFuture
import java.util.concurrent.CompletableFuture.completedFuture

@Suppress("DEPRECATION")
class DtlsChannelHandler @JvmOverloads constructor(
private val sslConfig: SslConfig,
private val expireAfter: Duration = Duration.ofSeconds(60),
Expand Down Expand Up @@ -96,16 +94,6 @@ class DtlsChannelHandler @JvmOverloads constructor(
dtlsServer.handleOutboundDtlsSessionContext(msg.recipient(), msg.sessionContext, promise.toCompletableFuture())
}
is DatagramPacket -> write(msg, promise, ctx)
is SessionAuthenticationContext -> {
msg.map.forEach { (key, value) ->
if (!dtlsServer.putSessionAuthenticationContext(msg.adr, key, value)) {
promise.setFailure(SslException("Session does not exists"))
}
}
if (!promise.isDone) {
promise.setSuccess()
}
}

else -> ctx.write(msg, promise)
}
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ import org.opencoap.ssl.EmptyCidSupplier
import org.opencoap.ssl.PskAuth
import org.opencoap.ssl.RandomCidSupplier
import org.opencoap.ssl.SslConfig
import org.opencoap.ssl.SslException
import org.opencoap.ssl.netty.NettyHelpers.createBootstrap
import org.opencoap.ssl.transport.DtlsServer
import org.opencoap.ssl.transport.HashMapSessionStore
Expand All @@ -55,7 +54,6 @@ import java.time.Instant
import java.util.concurrent.ExecutionException
import kotlin.random.Random

@Suppress("DEPRECATION")
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class NettyTest {

Expand Down Expand Up @@ -173,24 +171,6 @@ class NettyTest {
clients.forEach(Transport<String>::close)
}

@Test
fun `should forward authentication context`() {
// connect and handshake
val client = NettyTransportAdapter.connect(clientConf, srvAddress).mapToString()

assertTrue(client.send("hi").await())
assertEquals("ECHO:hi", client.receive(5.seconds).await())

// when
srvChannel.writeAndFlush(SessionAuthenticationContext(client.localAddress(), mapOf("AUTH" to "007:"))).get()

// then
assertTrue(client.send("hi").await())
assertEquals("ECHO:007:hi", client.receive(5.seconds).await())

client.close()
}

@Test
fun `should forward authentication context passed inside outbound datagram`() {
// connect and handshake
Expand All @@ -210,13 +190,6 @@ class NettyTest {
client.close()
}

@Test
fun `should fail to forward authentication context for non existing client`() {
assertThatThrownBy {
srvChannel.writeAndFlush(SessionAuthenticationContext(localAddress(1), mapOf("AUTH" to "007:"))).get()
}.hasRootCause(SslException("Session does not exists"))
}

@Test
fun `server should load session from store`() {
sessionStore.write(StoredSessionPair.cid, SessionWithContext(StoredSessionPair.srvSession, mapOf(), Instant.ofEpochSecond(123456789)))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,10 +94,6 @@ class DtlsServer(
return (sessions[peerAddress] as? DtlsSession)?.encrypt(plainPacket)
}

@Deprecated("Pass authentication context in the DtlSContext of the outbound datagram instead")
fun putSessionAuthenticationContext(adr: InetSocketAddress, key: String, value: String?): Boolean =
updateSessionAuthenticationContext(adr, mapOf(key to value))

private fun updateSessionAuthenticationContext(adr: InetSocketAddress, authCtxUpdate: Map<String, String?>): Boolean {
if (authCtxUpdate.isEmpty()) return true

Expand Down Expand Up @@ -126,13 +122,22 @@ class DtlsServer(
}
}

fun closeSession(addr: InetSocketAddress) {
private fun closeSession(addr: InetSocketAddress) {
sessions.remove(addr)?.apply {
storeAndClose()
logger.info("[{}] [CID:{}] DTLS session was stored", peerAddress, (this as? DtlsSession)?.sessionContext?.cid?.toHex() ?: "na")
}
}

fun handleOutboundDtlsSessionContext(adr: InetSocketAddress, ctx: DtlsSessionContext, writeFuture: CompletableFuture<Boolean>) {
if (ctx.sessionSuspensionHint) {
writeFuture.thenAccept {
closeSession(adr)
}
}
updateSessionAuthenticationContext(adr, ctx.authenticationContext)
}

fun loadSession(sessBuf: SessionWithContext?, adr: InetSocketAddress, cid: ByteArray): Boolean {
return try {
if (sessBuf == null) {
Expand Down Expand Up @@ -404,15 +409,6 @@ class DtlsServer(

return false
}

fun handleOutboundDtlsSessionContext(adr: InetSocketAddress, ctx: DtlsSessionContext, writeFuture: CompletableFuture<Boolean>) {
if (ctx.sessionSuspensionHint) {
writeFuture.thenAccept {
closeSession(adr)
}
}
updateSessionAuthenticationContext(adr, ctx.authenticationContext)
}
}

fun ByteBuffer.seek(offset: Int): ByteBuffer = this.position(this.position() + offset) as ByteBuffer
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ import java.util.function.Function
/*
Single threaded dtls server on top of DatagramChannel.
*/
@Suppress("DEPRECATION")
class DtlsServerTransport private constructor(
private val transport: Transport<ByteBufferPacket>,
private val dtlsServer: DtlsServer,
Expand Down Expand Up @@ -115,10 +114,4 @@ class DtlsServerTransport private constructor(
}.get(30, TimeUnit.SECONDS)
executor.shutdown()
}

@Deprecated("Pass authentication context in the DtlSContext of the outbound datagram instead")
fun putSessionAuthenticationContext(adr: InetSocketAddress, key: String, value: String?): CompletableFuture<Boolean> =
executor.supply {
dtlsServer.putSessionAuthenticationContext(adr, key, value)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,6 @@ import java.util.concurrent.TimeUnit
import java.util.function.Consumer
import kotlin.random.Random

@Suppress("DEPRECATION")
class DtlsServerTransportTest {

private val psk = PskAuth("dupa", byteArrayOf(1))
Expand All @@ -71,14 +70,11 @@ class DtlsServerTransportTest {
if (msg == "error") {
throw Exception("error")
} else if (msg.startsWith("Authenticate:")) {
server.putSessionAuthenticationContext(packet.peerAddress, "auth", msg.substring(12))
server.send(Packet("OK".toByteBuffer(), packet.peerAddress))
} else if (msg.startsWith("AuthenticateWithContext:")) {
server.send(
Packet(
"OK".toByteBuffer(),
packet.peerAddress,
DtlsSessionContext(authenticationContext = mapOf("auth" to msg.substring(23)))
DtlsSessionContext(authenticationContext = mapOf("auth" to msg.substring(12)))
)
)
} else {
Expand Down Expand Up @@ -464,36 +460,12 @@ class DtlsServerTransportTest {
client.close()
}

@Test
fun `should set and use session context`() {
// given
server = DtlsServerTransport.create(conf, sessionStore = sessionStore)
val serverReceived = server.receive(1.seconds)
// and, client connected
val client = DtlsTransmitter.connect(server, clientConfig).await()
client.send("hello!")
assertEquals("hello!", serverReceived.await().buffer.decodeToString())

// when, session context is set
assertTrue(server.putSessionAuthenticationContext(serverReceived.await().peerAddress, "auth", "id:dev-007").await())

// and, client sends messages
client.send("msg1")
client.send("msg2")

// then
assertEquals(mapOf("auth" to "id:dev-007"), server.receive(1.seconds).await().sessionContext.authenticationContext)
assertEquals(mapOf("auth" to "id:dev-007"), server.receive(1.seconds).await().sessionContext.authenticationContext)

client.close()
}

@Test
fun `should set and use session context passed inside outbound datagram`() {
server = DtlsServerTransport.create(conf, expireAfter = 100.millis, sessionStore = sessionStore, lifecycleCallbacks = sslLifecycleCallbacks).listen(echoHandler)
// client connected
val client = DtlsTransmitter.connect(server, clientConfig).await()
client.send("AuthenticateWithContext:dev-007")
client.send("Authenticate:dev-007")
assertEquals("OK", client.receiveString())
client.send("hi")
assertEquals("hi:resp:dev-007", client.receiveString())
Expand Down

0 comments on commit 9bf5a1c

Please sign in to comment.