Skip to content

Commit 0afe9fd

Browse files
chagongCopilot
andauthored
fix: harden debug session loopback binding, auth handshake, and DAP framing (#653)
* fix: harden debug session loopback binding, auth handshake, and DAP framing - Replace the shared wildcard debug server socket with per-session loopback (127.0.0.1) server sockets, a 256-bit JavaDebug-Auth handshake with constant-time verification, single-client socket closure, and an unused session timeout reaper (protocolVersion >= 2 via startDebugSession). - Enforce initialize lifecycle gating in DebugAdapter before request argument deserialization, guard AttachRequestHandler against uninitialized contexts, and prevent self-PID termination in DebuggeeProcessHelper. - Slice inbound Content-Length frames by UTF-8 byte length rather than UTF-16 character count in AbstractProtocolServer, with header and body size bounds. - Bind JDI launch listening sockets strictly to 127.0.0.1 via LoopbackSocketListeningConnector with debugger-first JDWP-Handshake validation and guaranteed stopListening cleanup across launch error paths. - Add unit and OSGi end-to-end regression tests covering authentication, framing, initialization gating, loopback JDI listening, launch, oDebug, and �ttach flows. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * test: handle TCP reset when server closes rejected sockets on macOS On BSD/macOS kernels, closing a socket while unread client bytes remain in SO_RCVBUF sends a TCP RST (SocketException: Connection reset) rather than a FIN (-1 EOF). Accept either EOF or SocketException after connect when verifying that unauthenticated or invalid-token sockets are closed without emitting any DAP response. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * fix: bound JDWP packet length, handshake deadline, and rejected listener cleanup - Enforce an upper JDWP packet-size bound (64 MiB default) in LoopbackSocketConnection.readPacket() and close the connection before allocating oversized buffers. - Enforce an absolute wall-clock deadline across performJdwpHandshake() reads so slow-drip peers cannot stretch per-read SO_TIMEOUT. - Remove and close session listeners when executor submission throws in startDebugSession() and startLegacyLoopbackSession(). Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * fix(plugin): isolate session pools, bound auth deadline, and serialize JDWP I/O Separate listener, handshake, and session worker pools with per-listener candidate permits, enforce an absolute authentication handshake deadline across reads, and serialize JDWP socket packet reads and writes while preserving mid-packet EOF errors. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * fix(plugin): bound launch failure cleanup and async test javac drain Close the JDWP listener immediately on launch failure, drain debuggee stdout/stderr asynchronously with bounded timeouts while terminating the child process, and drain javac output asynchronously in end-to-end test compilation. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * fix: complete launch future only from winning outcome handler Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * feat: add JDWP handshake usage telemetry and handshake timeout overrides Record structured `jdwp handshake` usage telemetry (`outcome`, `duration`, `timeoutMs`) inside `LoopbackSocketListeningConnector.performJdwpHandshake` and allow overriding the 5-second DAP and JDWP handshake timeouts via `java.debug.dap.handshakeTimeoutMs` and `java.debug.jdwp.handshakeTimeoutMs` system properties. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --------- Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
1 parent f29e011 commit 0afe9fd

19 files changed

Lines changed: 3681 additions & 280 deletions

File tree

‎com.microsoft.java.debug.core/src/main/java/com/microsoft/java/debug/core/adapter/DebugAdapter.java‎

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,11 +81,31 @@ public CompletableFuture<Messages.Response> dispatchRequest(Messages.Request req
8181
response.success = true;
8282

8383
Command command = Command.parse(request.command);
84-
Arguments cmdArgs = JsonUtils.fromJson(request.arguments, command.getArgumentType());
8584

8685
if (debugContext.isVmTerminated() && command != Command.DISCONNECT) {
8786
return CompletableFuture.completedFuture(response);
8887
}
88+
if (!debugContext.isInitialized()
89+
&& command != Command.INITIALIZE
90+
&& command != Command.DISCONNECT
91+
&& command != Command.UNSUPPORTED) {
92+
final String errorMessage = String.format(
93+
"'%s' request is rejected since the debug session has not been initialized yet.", request.command);
94+
logger.log(Level.SEVERE, errorMessage);
95+
ErrorCode errorCode = ErrorCode.SESSION_NOT_INITIALIZED;
96+
if (command == Command.LAUNCH) {
97+
errorCode = ErrorCode.LAUNCH_FAILURE;
98+
} else if (command == Command.ATTACH) {
99+
errorCode = ErrorCode.ATTACH_FAILURE;
100+
}
101+
return AdapterUtils.createAsyncErrorResponse(response, errorCode, errorMessage);
102+
}
103+
if (debugContext.isInitialized() && command == Command.INITIALIZE) {
104+
final String errorMessage = "'initialize' request is rejected since the debug session has already been initialized.";
105+
logger.log(Level.SEVERE, errorMessage);
106+
return AdapterUtils.createAsyncErrorResponse(response, ErrorCode.UNKNOWN_FAILURE, errorMessage);
107+
}
108+
Arguments cmdArgs = JsonUtils.fromJson(request.arguments, command.getArgumentType());
89109
List<IDebugRequestHandler> handlers = this.debugContext.getLaunchMode() == LaunchMode.DEBUG
90110
? requestHandlersForDebug.get(command) : requestHandlersForNoDebug.get(command);
91111
if (handlers != null && !handlers.isEmpty()) {

‎com.microsoft.java.debug.core/src/main/java/com/microsoft/java/debug/core/adapter/ErrorCode.java‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,8 @@ public enum ErrorCode {
3636
EVALUATION_COMPILE_ERROR(2001),
3737
EVALUATE_NOT_SUSPENDED_THREAD(2002),
3838
HCR_FAILURE(3001),
39-
INVALID_DAP_HEADER(3002);
39+
INVALID_DAP_HEADER(3002),
40+
SESSION_NOT_INITIALIZED(3003);
4041

4142
private int id;
4243

‎com.microsoft.java.debug.core/src/main/java/com/microsoft/java/debug/core/adapter/handler/AttachRequestHandler.java‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
import java.util.List;
1919
import java.util.Map;
2020
import java.util.concurrent.CompletableFuture;
21+
import java.util.logging.Level;
2122
import java.util.logging.Logger;
2223

2324
import com.microsoft.java.debug.core.Configuration;
@@ -55,6 +56,12 @@ public List<Command> getTargetCommands() {
5556

5657
@Override
5758
public CompletableFuture<Response> handle(Command command, Arguments arguments, Response response, IDebugAdapterContext context) {
59+
if (!context.isInitialized()) {
60+
final String errorMessage = "'attach' request is rejected since the debug session has not been initialized yet.";
61+
logger.log(Level.SEVERE, errorMessage);
62+
return CompletableFuture.completedFuture(
63+
AdapterUtils.setErrorResponse(response, ErrorCode.SESSION_NOT_INITIALIZED, errorMessage));
64+
}
5865
AttachArguments attachArguments = (AttachArguments) arguments;
5966
context.setAttached(true);
6067
context.setSourcePaths(attachArguments.sourcePaths);

‎com.microsoft.java.debug.core/src/main/java/com/microsoft/java/debug/core/adapter/handler/DebuggeeProcessHelper.java‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,10 +23,13 @@ static void terminate(IDebugAdapterContext context) {
2323
Process debuggeeProcess = context.getDebuggeeProcess();
2424
if (debuggeeProcess != null) {
2525
debuggeeProcess.destroy();
26-
} else if (context.getProcessId() > 0) {
27-
Optional<ProcessHandle> debuggeeHandle = ProcessHandle.of(context.getProcessId());
28-
if (debuggeeHandle.isPresent()) {
29-
debuggeeHandle.get().destroy();
26+
} else {
27+
long pid = context.getProcessId();
28+
if (pid > 0 && pid != ProcessHandle.current().pid()) {
29+
Optional<ProcessHandle> debuggeeHandle = ProcessHandle.of(pid);
30+
if (debuggeeHandle.isPresent()) {
31+
debuggeeHandle.get().destroy();
32+
}
3033
}
3134
}
3235
}

‎com.microsoft.java.debug.core/src/main/java/com/microsoft/java/debug/core/adapter/handler/LaunchWithDebuggingDelegate.java‎

Lines changed: 87 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -69,13 +69,23 @@ public CompletableFuture<Response> launchInTerminal(LaunchArguments launchArgume
6969
vmHandler.setVmProvider(vmProvider);
7070
final String launchInTerminalErrorFormat = "Failed to launch debuggee in terminal. Reason: %s";
7171

72+
ListeningConnector listenConnector = null;
73+
Map<String, Connector.Argument> args = null;
74+
boolean listenerStarted = false;
7275
try {
7376
List<ListeningConnector> connectors = vmProvider.getVirtualMachineManager().listeningConnectors();
74-
ListeningConnector listenConnector = connectors.get(0);
75-
Map<String, Connector.Argument> args = listenConnector.defaultArguments();
77+
listenConnector = connectors.get(0);
78+
args = listenConnector.defaultArguments();
7679
((Connector.IntegerArgument) args.get("timeout")).setValue(ATTACH_TERMINAL_TIMEOUT);
80+
Connector.Argument localAddress = args.get("localAddress");
81+
if (localAddress != null) {
82+
localAddress.setValue("127.0.0.1");
83+
}
7784
String address = listenConnector.startListening(args);
85+
listenerStarted = true;
7886

87+
final ListeningConnector activeConnector = listenConnector;
88+
final Map<String, Connector.Argument> activeArgs = args;
7989
final String[] names = launchArguments.mainClass.split("[/\\.]");
8090
final String terminalName = "Debug: " + names[names.length - 1];
8191
String[] cmds = LaunchRequestHandler.constructLaunchCommands(launchArguments, false, address);
@@ -102,81 +112,89 @@ public CompletableFuture<Response> launchInTerminal(LaunchArguments launchArgume
102112
// the local .m2 repository path, it may exceed the limit.
103113
context.getProtocolServer().sendRequest(request, RUNINTERMINAL_TIMEOUT)
104114
.whenComplete((runResponse, ex) -> {
105-
if (runResponse != null) {
106-
if (runResponse.success) {
107-
try {
115+
try {
116+
if (runResponse != null) {
117+
if (runResponse.success) {
108118
try {
109-
RunInTerminalResponseBody terminalResponse = JsonUtils.fromJson(
110-
JsonUtils.toJson(runResponse.body), RunInTerminalResponseBody.class);
111-
context.setProcessId(terminalResponse.processId);
112-
context.setShellProcessId(terminalResponse.shellProcessId);
113-
} catch (JsonSyntaxException e) {
114-
logger.severe("Failed to resolve runInTerminal response: " + e.toString());
115-
}
116-
VirtualMachine vm = listenConnector.accept(args);
117-
vmHandler.connectVirtualMachine(vm);
118-
context.setDebugSession(new DebugSession(vm));
119-
logger.info("Launching debuggee in terminal console succeeded.");
120-
if (context.getShellProcessId() > 0) {
121-
ProcessHandle debuggeeProcess = LaunchUtils.findJavaProcessInTerminalShell(context.getShellProcessId(), cmds[0], 0);
122-
if (debuggeeProcess != null) {
123-
context.setProcessId(debuggeeProcess.pid());
119+
try {
120+
RunInTerminalResponseBody terminalResponse = JsonUtils.fromJson(
121+
JsonUtils.toJson(runResponse.body), RunInTerminalResponseBody.class);
122+
context.setProcessId(terminalResponse.processId);
123+
context.setShellProcessId(terminalResponse.shellProcessId);
124+
} catch (JsonSyntaxException e) {
125+
logger.severe("Failed to resolve runInTerminal response: " + e.toString());
126+
}
127+
VirtualMachine vm = activeConnector.accept(activeArgs);
128+
vmHandler.connectVirtualMachine(vm);
129+
context.setDebugSession(new DebugSession(vm));
130+
logger.info("Launching debuggee in terminal console succeeded.");
131+
if (context.getShellProcessId() > 0) {
132+
ProcessHandle debuggeeProcess = LaunchUtils.findJavaProcessInTerminalShell(
133+
context.getShellProcessId(), cmds[0], 0);
134+
if (debuggeeProcess != null) {
135+
context.setProcessId(debuggeeProcess.pid());
136+
}
137+
}
138+
resultFuture.complete(response);
139+
} catch (TransportTimeoutException e) {
140+
int commandLength = StringUtils.length(launchArguments.cwd) + 1;
141+
for (String cmd : cmds) {
142+
commandLength += StringUtils.length(cmd) + 1;
124143
}
125-
}
126-
resultFuture.complete(response);
127-
} catch (TransportTimeoutException e) {
128-
int commandLength = StringUtils.length(launchArguments.cwd) + 1;
129-
for (String cmd : cmds) {
130-
commandLength += StringUtils.length(cmd) + 1;
131-
}
132144

133-
final int threshold = SystemUtils.IS_OS_WINDOWS ? 8092 : 32 * 1024;
134-
String errorMessage = String.format(launchInTerminalErrorFormat, e.toString());
135-
if (commandLength >= threshold) {
136-
errorMessage = "Failed to launch debuggee in terminal. The possible reason is the command line too long. "
137-
+ "More details: " + e.toString();
138-
logger.severe(errorMessage
139-
+ "\r\n"
140-
+ "The estimated command line length is " + commandLength + ". "
141-
+ "Try to enable shortenCommandLine option in the debug launch configuration.");
142-
}
145+
final int threshold = SystemUtils.IS_OS_WINDOWS ? 8092 : 32 * 1024;
146+
String errorMessage = String.format(launchInTerminalErrorFormat, e.toString());
147+
if (commandLength >= threshold) {
148+
errorMessage = "Failed to launch debuggee in terminal. The possible reason is the command line too long. "
149+
+ "More details: " + e.toString();
150+
logger.severe(errorMessage
151+
+ "\r\n"
152+
+ "The estimated command line length is " + commandLength + ". "
153+
+ "Try to enable shortenCommandLine option in the debug launch configuration.");
154+
}
143155

156+
resultFuture.completeExceptionally(
157+
new DebugException(
158+
errorMessage,
159+
ErrorCode.LAUNCH_IN_TERMINAL_FAILURE.getId()
160+
)
161+
);
162+
} catch (IOException | IllegalConnectorArgumentsException e) {
163+
resultFuture.completeExceptionally(
164+
new DebugException(
165+
String.format(launchInTerminalErrorFormat, e.toString()),
166+
ErrorCode.LAUNCH_IN_TERMINAL_FAILURE.getId()
167+
)
168+
);
169+
}
170+
} else {
144171
resultFuture.completeExceptionally(
145172
new DebugException(
146-
errorMessage,
147-
ErrorCode.LAUNCH_IN_TERMINAL_FAILURE.getId()
148-
)
149-
);
150-
} catch (IOException | IllegalConnectorArgumentsException e) {
151-
resultFuture.completeExceptionally(
152-
new DebugException(
153-
String.format(launchInTerminalErrorFormat, e.toString()),
173+
String.format(launchInTerminalErrorFormat, runResponse.message),
154174
ErrorCode.LAUNCH_IN_TERMINAL_FAILURE.getId()
155175
)
156176
);
157177
}
158178
} else {
179+
if (ex instanceof CompletionException && ex.getCause() != null) {
180+
ex = ex.getCause();
181+
}
182+
String errorMessage = String.format(launchInTerminalErrorFormat, ex != null ? ex.toString() : "Null response");
159183
resultFuture.completeExceptionally(
160184
new DebugException(
161-
String.format(launchInTerminalErrorFormat, runResponse.message),
185+
String.format(launchInTerminalErrorFormat, errorMessage),
162186
ErrorCode.LAUNCH_IN_TERMINAL_FAILURE.getId()
163187
)
164188
);
165189
}
166-
} else {
167-
if (ex instanceof CompletionException && ex.getCause() != null) {
168-
ex = ex.getCause();
169-
}
170-
String errorMessage = String.format(launchInTerminalErrorFormat, ex != null ? ex.toString() : "Null response");
171-
resultFuture.completeExceptionally(
172-
new DebugException(
173-
String.format(launchInTerminalErrorFormat, errorMessage),
174-
ErrorCode.LAUNCH_IN_TERMINAL_FAILURE.getId()
175-
)
176-
);
190+
} finally {
191+
stopListeningQuietly(activeConnector, activeArgs);
177192
}
178193
});
179-
} catch (IOException | IllegalConnectorArgumentsException e) {
194+
} catch (IOException | IllegalConnectorArgumentsException | RuntimeException e) {
195+
if (listenerStarted) {
196+
stopListeningQuietly(listenConnector, args);
197+
}
180198
resultFuture.completeExceptionally(
181199
new DebugException(
182200
String.format(launchInTerminalErrorFormat, e.toString()),
@@ -246,4 +264,15 @@ public void preLaunch(LaunchArguments launchArguments, IDebugAdapterContext cont
246264
context.setMainClass(LaunchRequestHandler.parseMainClassWithoutModuleName(launchArguments.mainClass));
247265
context.setStepFilters(launchArguments.stepFilters);
248266
}
267+
268+
private static void stopListeningQuietly(ListeningConnector connector, Map<String, Connector.Argument> args) {
269+
if (connector == null) {
270+
return;
271+
}
272+
try {
273+
connector.stopListening(args);
274+
} catch (IOException | IllegalConnectorArgumentsException e) {
275+
logger.fine("Failed to close JDI listening socket: " + e.toString());
276+
}
277+
}
249278
}

0 commit comments

Comments
 (0)