83 lines
2.2 KiB
Go
83 lines
2.2 KiB
Go
package main
|
|
|
|
import (
|
|
"archive/tar"
|
|
"fmt"
|
|
"net/http"
|
|
"os"
|
|
)
|
|
|
|
type fsExtractRequest struct {
|
|
Path string `json:"path"`
|
|
Server string `json:"server"`
|
|
Overwrite bool `json:"overwrite"`
|
|
}
|
|
|
|
func readFSExtractRequest(w http.ResponseWriter, r *http.Request, limit int64) (fsExtractRequest, error) {
|
|
var body fsExtractRequest
|
|
err := readJSON(w, r, limit, &body)
|
|
// adpanel:extract-no-clobber - the protected method cannot opt into replacement.
|
|
if r.Method == http.MethodPut {
|
|
body.Overwrite = false
|
|
}
|
|
return body, err
|
|
}
|
|
|
|
func sanitizeFileMode(mode os.FileMode, isDir bool) os.FileMode {
|
|
mode &^= os.ModeSetuid | os.ModeSetgid | os.ModeSticky
|
|
if isDir {
|
|
return mode.Perm() & 0o755
|
|
}
|
|
return mode.Perm() & 0o644
|
|
}
|
|
|
|
// adpanel:extract-no-clobber - sanitize only the output inode this extraction wrote.
|
|
func sanitizeExtractedFileMode(file *os.File) error {
|
|
info, err := file.Stat()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
mode := sanitizeFileMode(info.Mode(), false)
|
|
if info.Mode() == mode {
|
|
return nil
|
|
}
|
|
return file.Chmod(mode)
|
|
}
|
|
|
|
func openExtractRoot(dest string, maxTotal int64) (*safeRoot, error) {
|
|
if maxTotal <= 0 {
|
|
return nil, fmt.Errorf("no extract budget")
|
|
}
|
|
if err := ensureDir(dest); err != nil {
|
|
return nil, err
|
|
}
|
|
return safeOpenRoot(dest)
|
|
}
|
|
|
|
// adpanel:fs-toctou - resolve the destination through the server scope, not by reopening a checked absolute path.
|
|
func openScopedExtractRoot(scope *safeRoot, relativeDir string) (*safeRoot, error) {
|
|
dir, err := safeOpenDirAt(scope, relativeDir)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &safeRoot{file: dir, path: dir.Name()}, nil
|
|
}
|
|
|
|
func extractZipSafeFrom(file *os.File, size int64, dest string, maxTotal int64, overwrite bool) (int, error) {
|
|
root, err := openExtractRoot(dest, maxTotal)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
defer root.Close()
|
|
return extractZipSafeAt(file, size, root, maxTotal, overwrite)
|
|
}
|
|
|
|
func extractTarSafe(reader *tar.Reader, dest string, maxTotal int64, overwrite bool, installerOutput ...bool) (int, error) {
|
|
root, err := openExtractRoot(dest, maxTotal)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
defer root.Close()
|
|
return extractTarSafeAt(reader, root, maxTotal, overwrite, len(installerOutput) > 0 && installerOutput[0])
|
|
}
|