-
Notifications
You must be signed in to change notification settings - Fork 170
Expand file tree
/
Copy pathKtorServerManager.kt
More file actions
203 lines (165 loc) · 7.42 KB
/
Copy pathKtorServerManager.kt
File metadata and controls
203 lines (165 loc) · 7.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
package net.portswigger.mcp
import burp.api.montoya.MontoyaApi
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.server.plugins.cors.routing.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.modelcontextprotocol.kotlin.sdk.Implementation
import io.modelcontextprotocol.kotlin.sdk.ServerCapabilities
import io.modelcontextprotocol.kotlin.sdk.server.Server
import io.modelcontextprotocol.kotlin.sdk.server.ServerOptions
import io.modelcontextprotocol.kotlin.sdk.server.mcp
import net.portswigger.mcp.config.McpConfig
import net.portswigger.mcp.tools.registerTools
import java.net.URI
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
class KtorServerManager(private val api: MontoyaApi) : ServerManager {
private var server: EmbeddedServer<*, *>? = null
private val executor: ExecutorService = Executors.newSingleThreadExecutor()
override fun start(config: McpConfig, callback: (ServerState) -> Unit) {
callback(ServerState.Starting)
executor.submit {
try {
server?.stop(1000, 5000)
server = null
val mcpServer = Server(
serverInfo = Implementation("burp-suite", "1.1.2"), options = ServerOptions(
capabilities = ServerCapabilities(
tools = ServerCapabilities.Tools(listChanged = false)
)
)
)
server = embeddedServer(Netty, port = config.port, host = config.host) {
install(CORS) {
allowHost("localhost:${config.port}")
allowHost("127.0.0.1:${config.port}")
if (config.host.lowercase() !in setOf("localhost", "127.0.0.1")) {
allowHost("${config.host}:${config.port}")
}
allowMethod(HttpMethod.Get)
allowMethod(HttpMethod.Post)
allowHeader(HttpHeaders.ContentType)
allowHeader(HttpHeaders.Accept)
allowHeader("Last-Event-ID")
allowCredentials = false
allowNonSimpleContentTypes = true
maxAgeInSeconds = 3600
}
intercept(ApplicationCallPipeline.Call) {
val origin = call.request.header("Origin")
val host = call.request.header("Host")
val referer = call.request.header("Referer")
val userAgent = call.request.header("User-Agent")
if (origin != null && !isValidOrigin(origin, config.host)) {
api.logging().logToOutput("Blocked DNS rebinding attack from origin: $origin")
call.respond(HttpStatusCode.Forbidden)
return@intercept
} else if (isBrowserRequest(userAgent)) {
api.logging().logToOutput("Blocked browser request without Origin header")
call.respond(HttpStatusCode.Forbidden)
return@intercept
}
if (host != null && !isValidHost(host, config.port, config.host)) {
api.logging().logToOutput("Blocked DNS rebinding attack from host: $host")
call.respond(HttpStatusCode.Forbidden)
return@intercept
}
if (referer != null && !isValidReferer(referer, config.host)) {
api.logging().logToOutput("Blocked suspicious request from referer: $referer")
call.respond(HttpStatusCode.Forbidden)
return@intercept
}
call.response.header("X-Frame-Options", "DENY")
call.response.header("X-Content-Type-Options", "nosniff")
call.response.header("Referrer-Policy", "same-origin")
call.response.header("Content-Security-Policy", "default-src 'none'")
}
mcp {
mcpServer
}
mcpServer.registerTools(api, config)
}.apply {
start(wait = false)
}
api.logging().logToOutput("Started MCP server on ${config.host}:${config.port}")
callback(ServerState.Running)
} catch (e: Exception) {
api.logging().logToError(e)
callback(ServerState.Failed(e))
}
}
}
override fun stop(callback: (ServerState) -> Unit) {
callback(ServerState.Stopping)
executor.submit {
try {
server?.stop(1000, 5000)
server = null
api.logging().logToOutput("Stopped MCP server")
callback(ServerState.Stopped)
} catch (e: Exception) {
api.logging().logToError(e)
callback(ServerState.Failed(e))
}
}
}
override fun shutdown() {
server?.stop(1000, 5000)
server = null
executor.shutdown()
executor.awaitTermination(10, TimeUnit.SECONDS)
}
private fun isValidOrigin(origin: String, configuredHost: String): Boolean {
try {
val url = URI(origin).toURL()
val hostname = url.host.lowercase()
val allowedHosts = mutableSetOf("localhost", "127.0.0.1")
allowedHosts.add(configuredHost.lowercase())
return hostname in allowedHosts
} catch (_: Exception) {
return false
}
}
private fun isBrowserRequest(userAgent: String?): Boolean {
if (userAgent == null) return false
val userAgentLower = userAgent.lowercase()
val browserIndicators = listOf(
"mozilla/", "chrome/", "safari/", "webkit/", "gecko/", "firefox/", "edge/", "opera/", "browser"
)
return browserIndicators.any { userAgentLower.contains(it) }
}
private fun isValidHost(host: String, expectedPort: Int, configuredHost: String): Boolean {
try {
val parts = host.split(":")
val hostname = parts[0].lowercase()
val port = if (parts.size > 1) parts[1].toIntOrNull() else null
val allowedHosts = mutableSetOf("localhost", "127.0.0.1")
allowedHosts.add(configuredHost.lowercase())
if (hostname !in allowedHosts) {
return false
}
if (port != null && port != expectedPort) {
return false
}
return true
} catch (_: Exception) {
return false
}
}
private fun isValidReferer(referer: String, configuredHost: String): Boolean {
try {
val url = URI(referer).toURL()
val hostname = url.host.lowercase()
val allowedHosts = mutableSetOf("localhost", "127.0.0.1")
allowedHosts.add(configuredHost.lowercase())
return hostname in allowedHosts
} catch (_: Exception) {
return false
}
}
}