fix(rpc): bind io_stream sessions to creator to prevent terminal/fm hijack

createTerminal and createFM correctly check server ownership before
issuing a stream UUID, but terminalStream and fmStream only verified
that the UUID existed. Any authenticated user holding a valid stream
UUID could attach to it, gaining the original creator's live shell or
file-manager session — and the UUID is exposed via URL path (referer
leaks, access logs, browser history, frontend error reporters).

Bind the creator user ID into ioStreamContext at CreateStream time,
expose StreamOwnership and IsStreamAuthorizedForUser, and check
ownership in terminalStream/fmStream before the WebSocket upgrade so a
rejected attempt does not tear down the legitimate stream via defer.

NAT streams are also routed through CreateStream(_, 0); they are not
reachable from /ws/terminal or /ws/file so a sentinel user ID is fine.

Co-authored-by: naiba/CloudCode <hi+cloudcode@nai.ba>
This commit is contained in:
naiba
2026-05-18 15:16:40 +00:00
co-authored by naiba/CloudCode
parent e7c2e453c0
commit 6661d6a7fc
6 changed files with 238 additions and 5 deletions
+7 -1
View File
@@ -46,7 +46,7 @@ func createFM(c *gin.Context) (*model.CreateFMResponse, error) {
return nil, err
}
rpc.NezhaHandlerSingleton.CreateStream(streamId)
rpc.NezhaHandlerSingleton.CreateStream(streamId, getUid(c))
fmData, _ := json.Marshal(&model.TaskFM{
StreamID: streamId,
@@ -72,6 +72,12 @@ func createFM(c *gin.Context) (*model.CreateFMResponse, error) {
// @Router /ws/file/{id} [get]
func fmStream(c *gin.Context) (any, error) {
streamId := c.Param("id")
// GHSA-style fix: io_stream sessions must be reachable only by their creator
// (or an admin). Without this, any authenticated user who learns a stream
// UUID can hijack a live file-manager session on the target server.
if !rpc.NezhaHandlerSingleton.IsStreamAuthorizedForUser(streamId, getUid(c), callerIsAdmin(c)) {
return nil, singleton.Localizer.ErrorT("permission denied")
}
if _, err := rpc.NezhaHandlerSingleton.GetStream(streamId); err != nil {
return nil, err
}
@@ -0,0 +1,117 @@
package controller
import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"github.com/nezhahq/nezha/model"
"github.com/nezhahq/nezha/pkg/i18n"
"github.com/nezhahq/nezha/service/rpc"
"github.com/nezhahq/nezha/service/singleton"
)
func ensureLocalizerForStreamTests(t *testing.T) {
t.Helper()
if singleton.Localizer == nil {
singleton.Localizer = i18n.NewLocalizer("en_US", "nezha", "translations", i18n.Translations)
}
// upgrader stays nil — these tests must reject the caller BEFORE WS upgrade.
// If a test ever reaches the upgrade path it will panic on nil upgrader,
// surfacing the regression.
}
// decodeCommonResponseError returns Success and Error of a CommonResponse[any].
func decodeCommonResponseError(t *testing.T, body []byte) (bool, string) {
t.Helper()
var resp struct {
Success bool `json:"success"`
Error string `json:"error"`
}
if err := json.Unmarshal(body, &resp); err != nil {
t.Fatalf("decode response: %v body=%s", err, string(body))
}
return resp.Success, resp.Error
}
func setAuthUser(c *gin.Context, userID uint64, role model.Role) {
c.Set(model.CtxKeyAuthorizedUser, &model.User{
Common: model.Common{ID: userID},
Role: role,
})
}
func TestTerminalStreamRejectsForeignMember(t *testing.T) {
gin.SetMode(gin.TestMode)
ensureLocalizerForStreamTests(t)
rpc.NezhaHandlerSingleton = rpc.NewNezhaHandler()
rpc.NezhaHandlerSingleton.CreateStream("alice-terminal", 100)
r := gin.New()
r.Use(func(c *gin.Context) {
setAuthUser(c, 200, model.RoleMember) // bob
c.Next()
})
r.GET("/ws/terminal/:id", commonHandler(terminalStream))
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/ws/terminal/alice-terminal", nil)
r.ServeHTTP(w, req)
success, errMsg := decodeCommonResponseError(t, w.Body.Bytes())
assert.False(t, success, "foreign member must not be authorized to attach to alice's terminal")
assert.Contains(t, errMsg, "permission denied")
// And the existing stream must NOT have been torn down by the failed attempt.
_, stillExists := rpc.NezhaHandlerSingleton.StreamOwnership("alice-terminal")
assert.True(t, stillExists, "rejected attempt must not destroy the legitimate session")
}
func TestFMStreamRejectsForeignMember(t *testing.T) {
gin.SetMode(gin.TestMode)
ensureLocalizerForStreamTests(t)
rpc.NezhaHandlerSingleton = rpc.NewNezhaHandler()
rpc.NezhaHandlerSingleton.CreateStream("alice-fm", 100)
r := gin.New()
r.Use(func(c *gin.Context) {
setAuthUser(c, 200, model.RoleMember)
c.Next()
})
r.GET("/ws/file/:id", commonHandler(fmStream))
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/ws/file/alice-fm", nil)
r.ServeHTTP(w, req)
success, errMsg := decodeCommonResponseError(t, w.Body.Bytes())
assert.False(t, success, "foreign member must not be authorized to attach to alice's FM session")
assert.Contains(t, errMsg, "permission denied")
_, stillExists := rpc.NezhaHandlerSingleton.StreamOwnership("alice-fm")
assert.True(t, stillExists, "rejected attempt must not destroy the legitimate FM session")
}
func TestTerminalStreamRejectsUnknownStreamID(t *testing.T) {
gin.SetMode(gin.TestMode)
ensureLocalizerForStreamTests(t)
rpc.NezhaHandlerSingleton = rpc.NewNezhaHandler()
r := gin.New()
r.Use(func(c *gin.Context) {
setAuthUser(c, 100, model.RoleMember)
c.Next()
})
r.GET("/ws/terminal/:id", commonHandler(terminalStream))
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/ws/terminal/nonexistent", nil)
r.ServeHTTP(w, req)
success, _ := decodeCommonResponseError(t, w.Body.Bytes())
assert.False(t, success, "unknown stream id must produce an error response")
}
+8 -1
View File
@@ -44,7 +44,7 @@ func createTerminal(c *gin.Context) (*model.CreateTerminalResponse, error) {
return nil, err
}
rpc.NezhaHandlerSingleton.CreateStream(streamId)
rpc.NezhaHandlerSingleton.CreateStream(streamId, getUid(c))
terminalData, _ := json.Marshal(&model.TerminalTask{
StreamID: streamId,
@@ -72,6 +72,13 @@ func createTerminal(c *gin.Context) (*model.CreateTerminalResponse, error) {
// @Router /ws/terminal/{id} [get]
func terminalStream(c *gin.Context) (any, error) {
streamId := c.Param("id")
// GHSA-style fix: io_stream sessions must be reachable only by their creator
// (or an admin). Without this, any authenticated user who learns a stream
// UUID — via Referer leak, access logs, browser history — can hijack a live
// terminal and gain shell access to the target server.
if !rpc.NezhaHandlerSingleton.IsStreamAuthorizedForUser(streamId, getUid(c), callerIsAdmin(c)) {
return nil, singleton.Localizer.ErrorT("permission denied")
}
if _, err := rpc.NezhaHandlerSingleton.GetStream(streamId); err != nil {
return nil, err
}
+4 -1
View File
@@ -138,7 +138,10 @@ func ServeNAT(w http.ResponseWriter, r *http.Request, natConfig *model.NAT) {
return
}
rpcService.NezhaHandlerSingleton.CreateStream(streamId)
// NAT streams are anonymous HTTP-facing tunnels; they are NOT reachable
// via /ws/terminal or /ws/file (which check stream ownership), so the
// creator user ID does not need to identify a real user.
rpcService.NezhaHandlerSingleton.CreateStream(streamId, 0)
defer rpcService.NezhaHandlerSingleton.CloseStream(streamId)
taskData, err := json.Marshal(model.TaskNAT{