CLIProxyAPI icon indicating copy to clipboard operation
CLIProxyAPI copied to clipboard

[Bug] Windows pluginhost can pass GC-collected request buffers to native plugins

Open pnexus-wikii opened this issue 2 months ago • 0 comments

Is it a request payload issue?

  • [ ] Yes
  • [x] No, this is a native Windows pluginhost memory-lifetime issue.

Describe the bug

On Windows amd64, dynamicLibraryClient.Call converts Go-managed methodBytes and request memory to uintptr and passes the addresses to a native plugin through syscall.SyscallN. There is no post-call liveness barrier. Because uintptr is not a GC root, the request backing allocation can be finalized/reclaimed while the DLL is still copying it.

A c-shared plugin then faults while immediately copying the request with C.GoBytes. Two retained process crash logs had the same signature:

fatal error: fault
[signal 0xc0000005]
runtime.memmove
runtime.gobytes
main._Cfunc_GoBytes
main.cliproxyPluginCall

This is a fatal process-level access violation, so the outer plugin panic guard cannot recover it. It takes down the whole CLIProxyAPI process and all clients using the gateway.

The original crashes were observed with CLIProxyAPI 7.2.151 and the cpa-session-archive native plugin. The same vulnerable call shape is still present in v7.3.2 and current main:

https://github.com/router-for-me/CLIProxyAPI/blob/v7.3.2/internal/pluginhost/loader_windows.go#L286-L292

This is adjacent to, but not fixed by, #4538, which protects the Windows response descriptor rather than the input request buffer.

Minimal fix

Keep both Go allocations alive until the native call returns:

rc, _, _ := syscall.SyscallN(
    c.api.call,
    uintptr(unsafe.Pointer(methodBytes)),
    requestPtr,
    uintptr(len(request)),
    responseMem,
)
runtime.KeepAlive(methodBytes)
runtime.KeepAlive(request)

methodBytes has the same lifetime hazard as request, so both should be covered.

Regression test

A Windows-only direct dynamicLibraryClient.Call test can allocate a 2 MiB finalizer-backed request. Its fake native callback repeatedly forces runtime.GC()/runtime.Gosched() and checks that the owner was not finalized before reading the first and last bytes.

With GOGC=1, the unpatched loader failed this test on all 10 runs with a plugin return code indicating that the request owner finalized during the callback. With the two runtime.KeepAlive calls, the test passes for 50 repeated runs.

Expected behavior

The host must keep method and request memory valid for the full duration of a synchronous native plugin call.

OS Type

  • OS: Windows
  • Architecture: amd64
  • Go: 1.26

I have a minimal patch and regression test available if a PR would be useful.

pnexus-wikii avatar Sep 14 '26 02:09 pnexus-wikii