mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-12-07 07:03:56 +08:00
fix(server): anchor chat uploads with os.OpenRoot to block symlink escapes
Fixes GHSA-r7q2 and GHSA-7h5v: chatUpload previously joined base/uploads and ran os.MkdirAll + saveUpload outside an os.Root handle, allowing an exec process that owns the workspace to replace uploads/ with a symlink and make the root panel process write files outside s.m.dir. Anchor every chat upload under os.OpenRoot(s.m.dir), verify each directory component via root.Mkdir + root.Lstat (rejecting symlinks), choose free names via root.Lstat, and write via root.OpenFile(..., O_WRONLY|O_CREATE| O_EXCL, 0644).
This commit is contained in:
+120
-9
@@ -4,6 +4,8 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -92,8 +94,19 @@ func (s *Server) chatUpload(w http.ResponseWriter, r *http.Request) {
|
||||
} else if sub == "sessions" {
|
||||
base = agent.EnsureSessionDir(s.m.dir, id)
|
||||
}
|
||||
dir := filepath.Join(base, "uploads")
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
root, err := os.OpenRoot(s.m.dir)
|
||||
if err != nil {
|
||||
writeErr(w, 500, "failed to open workspace root: "+err.Error())
|
||||
return
|
||||
}
|
||||
defer root.Close()
|
||||
relBase, err := filepath.Rel(s.m.dir, base)
|
||||
if err != nil || relBase == "." || relBase == ".." || strings.HasPrefix(relBase, ".."+string(filepath.Separator)) || filepath.IsAbs(relBase) {
|
||||
writeErr(w, 500, "invalid upload base directory")
|
||||
return
|
||||
}
|
||||
relDir := filepath.Join(relBase, "uploads")
|
||||
if err := ensureRootRealDir(root, relDir, 0o755); err != nil {
|
||||
writeErr(w, 500, "failed to create directory: "+err.Error())
|
||||
return
|
||||
}
|
||||
@@ -127,17 +140,13 @@ func (s *Server) chatUpload(w http.ResponseWriter, r *http.Request) {
|
||||
if name == "" || name == "." || name == ".." || strings.ContainsAny(name, `/\`) {
|
||||
continue
|
||||
}
|
||||
dest, err := uniqueUploadPath(dir, name)
|
||||
finalName, err := saveRootChatUpload(root, relDir, name, hdr)
|
||||
if err != nil {
|
||||
writeErr(w, 500, "Save failed: "+err.Error())
|
||||
return
|
||||
}
|
||||
if err := saveUpload(hdr, dest); err != nil {
|
||||
writeErr(w, 500, "Save failed: "+err.Error())
|
||||
return
|
||||
}
|
||||
base := filepath.Base(dest)
|
||||
out = append(out, chatAttachment{Name: base, Path: "uploads/" + base, Size: hdr.Size, Abs: dest})
|
||||
abs := filepath.Join(base, "uploads", finalName)
|
||||
out = append(out, chatAttachment{Name: finalName, Path: "uploads/" + finalName, Size: hdr.Size, Abs: abs})
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"attachments": out})
|
||||
}
|
||||
@@ -213,3 +222,105 @@ func humanBytes(n int64) string {
|
||||
return fmt.Sprintf("%d B", n)
|
||||
}
|
||||
}
|
||||
|
||||
// ensureRootRealDir creates each missing component of relDir inside root via
|
||||
// root.Mkdir and verifies via root.Lstat that every component (including the
|
||||
// final directory) is a real directory, never a symlink.
|
||||
func ensureRootRealDir(root *os.Root, relDir string, perm os.FileMode) error {
|
||||
clean := filepath.Clean(relDir)
|
||||
if clean == "." || clean == ".." || strings.HasPrefix(clean, ".."+string(filepath.Separator)) || filepath.IsAbs(clean) {
|
||||
return fmt.Errorf("invalid relative directory %q", relDir)
|
||||
}
|
||||
parts := strings.Split(filepath.ToSlash(clean), "/")
|
||||
cur := ""
|
||||
for _, part := range parts {
|
||||
if part == "" || part == "." {
|
||||
continue
|
||||
}
|
||||
if cur == "" {
|
||||
cur = part
|
||||
} else {
|
||||
cur = filepath.Join(cur, part)
|
||||
}
|
||||
if err := root.Mkdir(cur, perm); err != nil && !errors.Is(err, os.ErrExist) {
|
||||
return err
|
||||
}
|
||||
fi, err := root.Lstat(cur)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !fi.IsDir() || fi.Mode()&os.ModeSymlink != 0 {
|
||||
return fmt.Errorf("path %q is not a real directory", cur)
|
||||
}
|
||||
}
|
||||
fi, err := root.Lstat(clean)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !fi.IsDir() || fi.Mode()&os.ModeSymlink != 0 {
|
||||
return fmt.Errorf("path %q is not a real directory", clean)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// saveRootChatUpload chooses a free filename inside root/relDir via root.Lstat
|
||||
// and writes the uploaded stream via root.OpenFile(..., O_WRONLY|O_CREATE|O_EXCL, 0644),
|
||||
// preventing symlink traversal or overwrites even if the worker owns the workspace.
|
||||
func saveRootChatUpload(root *os.Root, relDir, name string, hdr *multipart.FileHeader) (string, error) {
|
||||
relPath, finalName, err := uniqueRootUploadPath(root, relDir, name)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
src, err := hdr.Open()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer src.Close()
|
||||
out, err := root.OpenFile(relPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if _, err := io.Copy(out, src); err != nil {
|
||||
_ = out.Close()
|
||||
_ = root.Remove(relPath)
|
||||
return "", err
|
||||
}
|
||||
if err := out.Close(); err != nil {
|
||||
_ = root.Remove(relPath)
|
||||
return "", err
|
||||
}
|
||||
return finalName, nil
|
||||
}
|
||||
|
||||
func uniqueRootUploadPath(root *os.Root, relDir, name string) (relPath, finalName string, err error) {
|
||||
if ok, err := rootUploadPathFree(root, filepath.Join(relDir, name)); err != nil {
|
||||
return "", "", err
|
||||
} else if ok {
|
||||
return filepath.Join(relDir, name), name, nil
|
||||
}
|
||||
ext := filepath.Ext(name)
|
||||
stem := strings.TrimSuffix(name, ext)
|
||||
for i := 1; i <= maxUploadNameTries; i++ {
|
||||
candName := fmt.Sprintf("%s-%d%s", stem, i, ext)
|
||||
candRel := filepath.Join(relDir, candName)
|
||||
ok, err := rootUploadPathFree(root, candRel)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
if ok {
|
||||
return candRel, candName, nil
|
||||
}
|
||||
}
|
||||
return "", "", fmt.Errorf("no free name for upload %q", name)
|
||||
}
|
||||
|
||||
func rootUploadPathFree(root *os.Root, relPath string) (bool, error) {
|
||||
_, err := root.Lstat(relPath)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return true, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func buildUploadMultipart(t *testing.T, field, filename, content string) (*bytes.Buffer, string) {
|
||||
t.Helper()
|
||||
var buf bytes.Buffer
|
||||
mw := multipart.NewWriter(&buf)
|
||||
fw, err := mw.CreateFormFile(field, filename)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := fw.Write([]byte(content)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := mw.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return &buf, mw.FormDataContentType()
|
||||
}
|
||||
|
||||
// TestChatUploadRejectsSymlinkedUploadsDir verifies GHSA-r7q2 / GHSA-7h5v:
|
||||
// replacing the run directory's uploads/ with a symlink outside the workspace
|
||||
// must fail with HTTP 500 and write zero files outside, while a normal upload
|
||||
// returns HTTP 200 and saves the file inside uploads/.
|
||||
func TestChatUploadRejectsSymlinkedUploadsDir(t *testing.T) {
|
||||
workDir := t.TempDir()
|
||||
outsideDir := t.TempDir()
|
||||
|
||||
// Prepare a session run directory whose uploads/ is a symlink escaping workDir.
|
||||
sessionID := "symtest"
|
||||
runDir := filepath.Join(workDir, "sessions", sessionID)
|
||||
if err := os.MkdirAll(runDir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(outsideDir, filepath.Join(runDir, "uploads")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
s := &Server{m: &Manager{dir: workDir}}
|
||||
|
||||
body, ctype := buildUploadMultipart(t, "file", "pwn.txt", "SHOULD_NOT_ESCAPE")
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/chat/upload?scope=session&id="+sessionID, body)
|
||||
req.Header.Set("Content-Type", ctype)
|
||||
rec := httptest.NewRecorder()
|
||||
s.chatUpload(rec, req)
|
||||
|
||||
if rec.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("symlinked uploads dir: got HTTP %d (body=%s), want 500", rec.Code, rec.Body.String())
|
||||
}
|
||||
entries, err := os.ReadDir(outsideDir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(entries) != 0 {
|
||||
t.Fatalf("file escaped outside workspace through symlinked uploads/: %v", entries)
|
||||
}
|
||||
|
||||
// Normal upload to a clean session directory succeeds with HTTP 200 and writes inside uploads/.
|
||||
normalID := "normaltest"
|
||||
body2, ctype2 := buildUploadMultipart(t, "file", "report.txt", "SAFE_UPLOAD_BODY")
|
||||
req2 := httptest.NewRequest(http.MethodPost, "/api/chat/upload?scope=session&id="+normalID, body2)
|
||||
req2.Header.Set("Content-Type", ctype2)
|
||||
rec2 := httptest.NewRecorder()
|
||||
s.chatUpload(rec2, req2)
|
||||
|
||||
if rec2.Code != http.StatusOK {
|
||||
t.Fatalf("normal upload: got HTTP %d (body=%s), want 200", rec2.Code, rec2.Body.String())
|
||||
}
|
||||
var resp struct {
|
||||
Attachments []chatAttachment `json:"attachments"`
|
||||
}
|
||||
if err := json.Unmarshal(rec2.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("decode response: %v", err)
|
||||
}
|
||||
if len(resp.Attachments) != 1 || resp.Attachments[0].Name != "report.txt" || resp.Attachments[0].Path != "uploads/report.txt" {
|
||||
t.Fatalf("unexpected attachments: %+v", resp.Attachments)
|
||||
}
|
||||
expectedPath := filepath.Join(workDir, "sessions", normalID, "uploads", "report.txt")
|
||||
if resp.Attachments[0].Abs != expectedPath {
|
||||
t.Fatalf("Abs = %q, want %q", resp.Attachments[0].Abs, expectedPath)
|
||||
}
|
||||
raw, err := os.ReadFile(expectedPath)
|
||||
if err != nil || string(raw) != "SAFE_UPLOAD_BODY" {
|
||||
t.Fatalf("saved file mismatch: raw=%q err=%v", raw, err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user