Files

325 lines
11 KiB
Go

package isolation
import (
"context"
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"net/url"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"time"
)
const maxPythonSourceBytes = 80 << 20
func (a Agent) installPythonRuntime(w http.ResponseWriter, r *http.Request) {
var input PythonRuntimeInstallSpec
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
if err := decoder.Decode(&input); err != nil || decoder.Decode(&struct{}{}) != io.EOF || !supportedPythonSourceVersion(input.Version) {
http.Error(w, "invalid Python version", http.StatusBadRequest)
return
}
if err := a.installPythonSource(r.Context(), input.Version); err != nil {
slog.Error("Python source installation failed", "version", input.Version, "error", err)
http.Error(w, "cannot install verified Python source: "+err.Error(), http.StatusPreconditionFailed)
return
}
w.WriteHeader(http.StatusOK)
}
func supportedPythonSourceVersion(version string) bool {
if !pythonManagerVersionPattern.MatchString(version) {
return false
}
parts := strings.Split(version, ".")
minor, err := strconv.Atoi(parts[1])
return err == nil && parts[0] == "3" && minor >= 10 && minor <= 99
}
func (a Agent) installPythonSource(ctx context.Context, version string) error {
managerRoot := a.PythonManagerRoot
if managerRoot == "" {
managerRoot = "/www/server/python_manager/versions"
}
if !filepath.IsAbs(managerRoot) || filepath.Clean(managerRoot) != managerRoot || requirePhysicalDirectory(managerRoot) != nil {
return errors.New("Python manager root is unavailable")
}
resolvedManager, err := filepath.EvalSymlinks(managerRoot)
if err != nil || filepath.Clean(resolvedManager) != managerRoot {
return errors.New("Python manager root contains a symbolic link")
}
finalRoot := filepath.Join(managerRoot, version)
if info, statErr := os.Lstat(finalRoot); statErr == nil {
if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
return errors.New("Python version path is unsafe")
}
return a.validateInstalledPython(ctx, finalRoot)
} else if !errors.Is(statErr, os.ErrNotExist) {
return statErr
}
buildRoot := a.PythonBuildRoot
if buildRoot == "" {
buildRoot = "/var/lib/sea-vhost-agent/python-builds"
}
if !filepath.IsAbs(buildRoot) || filepath.Clean(buildRoot) != buildRoot {
return errors.New("invalid Python build root")
}
if err = os.MkdirAll(buildRoot, 0700); err != nil {
return err
}
if err = requirePhysicalDirectory(buildRoot); err != nil {
return errors.New("Python build root contains a symbolic link")
}
releaseLock, err := acquirePythonInstallLock(buildRoot, version)
if err != nil {
return err
}
defer releaseLock()
// An earlier request may have finished between the initial existence check
// and lock acquisition. Do not rebuild or overwrite its completed version.
if info, statErr := os.Lstat(finalRoot); statErr == nil {
if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
return errors.New("Python version path is unsafe")
}
return a.validateInstalledPython(ctx, finalRoot)
} else if !errors.Is(statErr, os.ErrNotExist) {
return statErr
}
workRoot, err := os.MkdirTemp(buildRoot, "python-"+version+"-")
if err != nil {
return err
}
defer os.RemoveAll(workRoot)
// Check the destination before spending time compiling. On systemd hosts
// the versions directory must be prepared before the agent starts.
stageBase := filepath.Join(managerRoot, ".sea-vhost-stage-"+version+"-"+filepath.Base(workRoot))
if err = os.Mkdir(stageBase, 0700); err != nil {
return fmt.Errorf("Python versions directory is not writable; rerun the node installer to prepare runtime mounts: %w", err)
}
defer os.RemoveAll(stageBase)
archivePath, err := a.downloadVerifiedPythonSource(ctx, workRoot, version)
if err != nil {
return err
}
if err = a.command(ctx, "tar", "-xJf", archivePath, "-C", workRoot); err != nil {
return err
}
sourceRoot := filepath.Join(workRoot, "Python-"+version)
configure := filepath.Join(sourceRoot, "configure")
if info, statErr := os.Stat(configure); statErr != nil || !runtimeExecutable(info) {
return errors.New("verified Python source archive has an invalid layout")
}
if err = a.commandAt(ctx, sourceRoot, configure, "--prefix="+finalRoot, "--with-ensurepip=install"); err != nil {
return err
}
jobs := runtime.NumCPU()
if jobs < 1 {
jobs = 1
} else if jobs > 4 {
jobs = 4
}
if err = a.command(ctx, "make", "-C", sourceRoot, "-j", strconv.Itoa(jobs)); err != nil {
return err
}
if err = a.command(ctx, "make", "-C", sourceRoot, "DESTDIR="+stageBase, "install"); err != nil {
return err
}
stagedRoot := stagedPythonInstallRoot(stageBase, finalRoot)
if info, statErr := os.Lstat(stagedRoot); statErr != nil || !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
return errors.New("Python staged installation is invalid")
}
if err = a.normalizeSharedPythonAccess(ctx, stagedRoot); err != nil {
return err
}
if err = os.WriteFile(filepath.Join(stagedRoot, ".sea-vhost-runtime"), []byte(version+"\n"), 0600); err != nil {
return err
}
if err = os.Rename(stagedRoot, finalRoot); err != nil {
return err
}
if err = a.validateInstalledPython(ctx, finalRoot); err != nil {
marker, _ := os.ReadFile(filepath.Join(finalRoot, ".sea-vhost-runtime"))
if strings.TrimSpace(string(marker)) == version {
_ = os.RemoveAll(finalRoot)
}
return err
}
return nil
}
func stagedPythonInstallRoot(stageBase, finalRoot string) string {
relative := strings.TrimPrefix(finalRoot, filepath.VolumeName(finalRoot))
relative = strings.TrimLeft(relative, `/\\`)
return filepath.Join(stageBase, relative)
}
func (a Agent) validateInstalledPython(ctx context.Context, root string) error {
python := filepath.Join(root, "bin", "python3")
resolved, err := filepath.EvalSymlinks(python)
if err != nil || !strings.HasPrefix(filepath.Clean(resolved)+string(os.PathSeparator), filepath.Clean(root)+string(os.PathSeparator)) {
return errors.New("Python interpreter escaped its installation root")
}
info, err := os.Stat(resolved)
if err != nil || !runtimeExecutable(info) {
return errors.New("Python interpreter is unavailable")
}
return a.command(ctx, python, "-c", "import ensurepip,ssl,sqlite3,venv")
}
func (a Agent) downloadVerifiedPythonSource(ctx context.Context, workRoot, version string) (string, error) {
metadataBase := strings.TrimRight(a.PythonMetadataBaseURL, "/")
if metadataBase == "" {
metadataBase = "https://www.python.org/ftp/python"
}
fileName := "Python-" + version + ".tar.xz"
metadataURL := metadataBase + "/" + version + "/" + fileName + ".sigstore"
var bundleBytes []byte
var err error
trustedOfficial := metadataBase == "https://www.python.org/ftp/python"
if trustedOfficial {
bundleBytes, _ = a.readPythonMetadataCache(fileName + ".sigstore")
}
if len(bundleBytes) == 0 {
bundleBytes, err = fetchPythonURL(ctx, metadataURL, 1<<20)
}
if err != nil {
return "", fmt.Errorf("fetch official Python signature metadata: %w", err)
}
expectedDigest, err := pythonSourceDigest(bundleBytes)
if err != nil {
return "", err
}
if trustedOfficial {
a.cachePythonMetadata(fileName+".sigstore", bundleBytes)
if cached, cacheErr := a.readPythonVerificationCache(fileName, maxPythonSourceBytes); cacheErr == nil {
actual := sha256.Sum256(cached)
if subtle.ConstantTimeCompare(actual[:], expectedDigest) != 1 {
return "", errors.New("offline Python source digest mismatch")
}
archivePath := filepath.Join(workRoot, fileName)
if err = os.WriteFile(archivePath, cached, 0600); err != nil {
return "", err
}
return archivePath, nil
}
}
bases := a.PythonSourceBaseURLs
if len(bases) == 0 {
bases = []string{"https://mirrors.huaweicloud.com/python", "https://www.python.org/ftp/python"}
}
var failures []string
for _, base := range bases {
sourceURL := strings.TrimRight(base, "/") + "/" + version + "/" + fileName
archivePath := filepath.Join(workRoot, fileName)
actualDigest, downloadErr := downloadPythonArchive(ctx, sourceURL, archivePath)
if downloadErr == nil && subtle.ConstantTimeCompare(actualDigest, expectedDigest) == 1 {
return archivePath, nil
}
_ = os.Remove(archivePath)
if downloadErr != nil {
failures = append(failures, downloadErr.Error())
} else {
failures = append(failures, "digest mismatch from "+sourceURL)
}
}
return "", fmt.Errorf("no verified Python source mirror succeeded: %s", strings.Join(failures, "; "))
}
func pythonSourceDigest(bundleBytes []byte) ([]byte, error) {
var bundle struct {
MessageSignature struct {
MessageDigest struct {
Algorithm string `json:"algorithm"`
Digest string `json:"digest"`
} `json:"messageDigest"`
} `json:"messageSignature"`
}
if json.Unmarshal(bundleBytes, &bundle) != nil || bundle.MessageSignature.MessageDigest.Algorithm != "SHA2_256" {
return nil, errors.New("official Python signature metadata is invalid")
}
expectedDigest, err := base64.StdEncoding.DecodeString(bundle.MessageSignature.MessageDigest.Digest)
if err != nil || len(expectedDigest) != sha256.Size {
return nil, errors.New("official Python source digest is invalid")
}
return expectedDigest, nil
}
func fetchPythonURL(ctx context.Context, rawURL string, limit int64) ([]byte, error) {
parsed, err := url.Parse(rawURL)
if err != nil || (parsed.Scheme != "https" && parsed.Scheme != "http") || parsed.User != nil || parsed.Host == "" {
return nil, errors.New("invalid source URL")
}
request, err := http.NewRequestWithContext(ctx, http.MethodGet, parsed.String(), nil)
if err != nil {
return nil, err
}
response, err := (&http.Client{Timeout: 2 * time.Minute}).Do(request)
if err != nil {
return nil, err
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return nil, fmt.Errorf("source returned HTTP %d", response.StatusCode)
}
data, err := io.ReadAll(io.LimitReader(response.Body, limit+1))
if err != nil {
return nil, err
}
if int64(len(data)) > limit {
return nil, errors.New("source response exceeded size limit")
}
return data, nil
}
func downloadPythonArchive(ctx context.Context, rawURL, destination string) ([]byte, error) {
parsed, err := url.Parse(rawURL)
if err != nil || (parsed.Scheme != "https" && parsed.Scheme != "http") || parsed.User != nil || parsed.Host == "" {
return nil, errors.New("invalid source URL")
}
request, err := http.NewRequestWithContext(ctx, http.MethodGet, parsed.String(), nil)
if err != nil {
return nil, err
}
response, err := (&http.Client{Timeout: 15 * time.Minute}).Do(request)
if err != nil {
return nil, err
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%s returned HTTP %d", parsed.Host, response.StatusCode)
}
file, err := os.OpenFile(destination, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
if err != nil {
return nil, err
}
hash := sha256.New()
written, copyErr := io.Copy(io.MultiWriter(file, hash), io.LimitReader(response.Body, maxPythonSourceBytes+1))
closeErr := file.Close()
if copyErr != nil {
return nil, copyErr
}
if closeErr != nil {
return nil, closeErr
}
if written > maxPythonSourceBytes {
return nil, errors.New("Python source archive exceeded size limit")
}
digest := hash.Sum(nil)
slog.Info("downloaded Python source", "version", filepath.Base(destination), "host", parsed.Host, "sha256", hex.EncodeToString(digest))
return digest, nil
}