fix(webconsole): authenticate sftp endpoints and check session owner (#25502)

The sftp list/download/upload endpoints were not protected by
authentication, only by the UUID4 session id. Anyone who learned the
session id (it appears in URLs and logs) could list, download and
upload files of the VM over the victim's active SSH/SFTP channel.

Wrap all three endpoints with auth.Authenticate and record the owner
of each sftp session at registration, so only the user who opened the
session can use it.

Co-authored-by: Qiu Jian <qiujian@yunionyun.com>
Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
Jian Qiu
2026-09-04 13:46:08 +08:00
committed by GitHub
parent 2f0ce30f5c
commit 95332ed656
4 changed files with 135 additions and 13 deletions

View File

@@ -0,0 +1,107 @@
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package server
import (
"context"
"encoding/base64"
"net/http"
"strings"
"time"
"yunion.io/x/jsonutils"
"yunion.io/x/log"
"yunion.io/x/pkg/appctx"
"yunion.io/x/pkg/errors"
identityapi "yunion.io/x/onecloud/pkg/apis/identity"
"yunion.io/x/onecloud/pkg/appsrv"
"yunion.io/x/onecloud/pkg/httperrors"
"yunion.io/x/onecloud/pkg/mcclient"
"yunion.io/x/onecloud/pkg/mcclient/auth"
)
const yunionAuthCookie = "yunionauth"
// AuthenticateSftp authenticates SFTP HTTP endpoints.
// Browser calls go through apigateway or hit webconsole directly with the
// yunionauth cookie (no X-Auth-Token).
func AuthenticateSftp(f appsrv.FilterHandler) appsrv.FilterHandler {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
token, err := fetchSftpUserCred(ctx, r)
if err != nil || token == nil {
log.Errorf("sftp auth failed: %v", err)
httperrors.UnauthorizedError(ctx, w, "Unauthorized")
return
}
ctx = context.WithValue(ctx, appctx.APP_CONTEXT_KEY_AUTH_TOKEN, token)
f(ctx, w, r)
}
}
func fetchSftpUserCred(ctx context.Context, r *http.Request) (mcclient.TokenCredential, error) {
if tokenStr := r.Header.Get(identityapi.AUTH_TOKEN_HEADER); tokenStr != "" {
token, err := auth.DefaultTokenVerifier(ctx, tokenStr)
if err != nil {
return nil, errors.Wrap(err, "verify X-Auth-Token")
}
return token, nil
}
return tokenFromYunionAuthCookie(r)
}
func tokenFromYunionAuthCookie(r *http.Request) (mcclient.TokenCredential, error) {
cookie, err := r.Cookie(yunionAuthCookie)
if err != nil || cookie == nil || cookie.Value == "" {
return nil, errors.Wrap(httperrors.ErrInvalidCredential, "no auth token or yunionauth cookie")
}
raw, err := decodeYunionAuthCookie(cookie.Value)
if err != nil {
return nil, errors.Wrap(err, "decode yunionauth cookie")
}
info, err := jsonutils.ParseString(raw)
if err != nil {
return nil, errors.Wrap(err, "parse yunionauth cookie")
}
if expStr, _ := info.GetString("exp"); expStr != "" {
exp, err := time.Parse(time.RFC3339, expStr)
if err == nil && time.Now().After(exp) {
return nil, errors.Wrap(httperrors.ErrInvalidCredential, "yunionauth cookie expired")
}
}
userId, _ := info.GetString("user_id")
if userId == "" {
return nil, errors.Wrap(httperrors.ErrInvalidCredential, "yunionauth cookie missing user_id")
}
user, _ := info.GetString("user")
return &mcclient.SSimpleToken{
User: user,
UserId: userId,
}, nil
}
func decodeYunionAuthCookie(val string) (string, error) {
s := strings.ReplaceAll(val, "-", "+")
s = strings.ReplaceAll(s, "_", "/")
for len(s)%4 != 0 {
s += "="
}
b, err := base64.StdEncoding.DecodeString(s)
if err != nil {
return "", err
}
return string(b), nil
}

View File

@@ -35,21 +35,28 @@ import (
"yunion.io/x/onecloud/pkg/appsrv"
"yunion.io/x/onecloud/pkg/httperrors"
"yunion.io/x/onecloud/pkg/mcclient"
"yunion.io/x/onecloud/pkg/mcclient/auth"
)
const (
SESSION_ID = "<session-id>"
)
type sftpClientEntry struct {
client *sftp.Client
ownerId string
}
var (
sftpMux = sync.Mutex{}
sftpClients = make(map[string]*sftp.Client)
sftpClients = make(map[string]*sftpClientEntry)
)
func addSftpClient(sId string, client *sftp.Client) {
func addSftpClient(sId, ownerId string, client *sftp.Client) {
sftpMux.Lock()
defer sftpMux.Unlock()
sftpClients[sId] = client
sftpClients[sId] = &sftpClientEntry{client: client, ownerId: ownerId}
}
func delSftpClient(sId string) {
@@ -58,14 +65,19 @@ func delSftpClient(sId string) {
delete(sftpClients, sId)
}
func getSftpClient(sId string) (*sftp.Client, error) {
// getSftpClient returns the sftp client of the session if it belongs to the
// requesting user
func getSftpClient(sId string, userCred mcclient.TokenCredential) (*sftp.Client, error) {
sftpMux.Lock()
defer sftpMux.Unlock()
client, ok := sftpClients[sId]
entry, ok := sftpClients[sId]
if !ok {
return nil, errors.Wrapf(cloudprovider.ErrNotFound, "%s", sId)
}
return client, nil
if userCred == nil || entry.ownerId != userCred.GetUserId() {
return nil, httperrors.NewForbiddenError("sftp session %s does not belong to current user", sId)
}
return entry.client, nil
}
type sLinkFile struct {
@@ -122,8 +134,9 @@ func HandleSftpList(ctx context.Context, w http.ResponseWriter, r *http.Request)
dir, _ = query.GetString("path")
}
sId := params[SESSION_ID]
userCred := auth.FetchUserCredential(ctx, nil)
files, err := func() (Files, error) {
client, err := getSftpClient(sId)
client, err := getSftpClient(sId, userCred)
if err != nil {
return nil, errors.Wrapf(err, "getSftpClient")
}
@@ -180,9 +193,10 @@ func HandleSftpUpload(ctx context.Context, w http.ResponseWriter, r *http.Reques
dir, _ = query.GetString("path")
}
sId := params[SESSION_ID]
userCred := auth.FetchUserCredential(ctx, nil)
err := func() error {
sftp, err := getSftpClient(sId)
sftp, err := getSftpClient(sId, userCred)
if err != nil {
return errors.Wrapf(err, "getSftpClient")
}
@@ -229,9 +243,10 @@ func HandleSftpDownload(ctx context.Context, w http.ResponseWriter, r *http.Requ
}
dir, _ := query.GetString("path")
sId := params[SESSION_ID]
userCred := auth.FetchUserCredential(ctx, nil)
err := func() error {
sftp, err := getSftpClient(sId)
sftp, err := getSftpClient(sId, userCred)
if err != nil {
return errors.Wrapf(err, "getSftpClient")
}

View File

@@ -112,7 +112,7 @@ func (s *WebsocketServer) initWs(w http.ResponseWriter, r *http.Request) error {
if err != nil {
return errors.Wrapf(err, "new sftp client")
}
addSftpClient(s.Session.Id, s.sftp)
addSftpClient(s.Session.Id, s.Session.GetClientSession().GetUserId(), s.sftp)
s.session, err = s.conn.NewSession()
if err != nil {

View File

@@ -63,8 +63,8 @@ const (
func initHandlers(app *appsrv.Application, isSlave bool) {
app_common.ExportOptionsHandler(app, &o.Options)
app.AddHandler("GET", ApiPathPrefix+"sftp/<session-id>/list", server.HandleSftpList)
app.AddHandler("GET", ApiPathPrefix+"sftp/<session-id>/download", server.HandleSftpDownload)
app.AddHandler("GET", ApiPathPrefix+"sftp/<session-id>/list", server.AuthenticateSftp(server.HandleSftpList))
app.AddHandler("GET", ApiPathPrefix+"sftp/<session-id>/download", server.AuthenticateSftp(server.HandleSftpDownload))
if !isSlave {
app.AddHandler("POST", ApiPathPrefix+"k8s/<podName>/shell", auth.Authenticate(handleK8sShell))
@@ -75,7 +75,7 @@ func initHandlers(app *appsrv.Application, isSlave bool) {
app.AddHandler("POST", ApiPathPrefix+"server/<id>", auth.Authenticate(handleServerRemoteConsole))
app.AddHandler("POST", ApiPathPrefix+"adb/<id>/shell", auth.Authenticate(handleAdbShell))
app.AddHandler("POST", ApiPathPrefix+"server-rdp/<id>", auth.Authenticate(handleServerRemoteRDPConsole))
app.AddHandler("POST", ApiPathPrefix+"sftp/<session-id>/upload", server.HandleSftpUpload)
app.AddHandler("POST", ApiPathPrefix+"sftp/<session-id>/upload", server.AuthenticateSftp(server.HandleSftpUpload))
}
for _, man := range []db.IModelManager{