95 lines
2.5 KiB
Go
95 lines
2.5 KiB
Go
package isolation
|
|
|
|
import (
|
|
"errors"
|
|
"io"
|
|
"os"
|
|
"path/filepath"
|
|
)
|
|
|
|
func (a Agent) pythonMetadataDirectory() string {
|
|
if a.PythonMetadataCacheRoot != "" {
|
|
return a.PythonMetadataCacheRoot
|
|
}
|
|
return "/var/lib/sea-vhost-agent/python-metadata"
|
|
}
|
|
|
|
// A cache is software verification material, not a node-side platform ledger.
|
|
// It can only be supplied by root (including an offline import of the official
|
|
// .sigstore file); unprivileged users and symlinks cannot establish trust.
|
|
func (a Agent) readPythonMetadataCache(name string) ([]byte, error) {
|
|
data, err := a.readPythonVerificationCache(name, 1<<20)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if _, err = pythonSourceDigest(data); err != nil {
|
|
return nil, err
|
|
}
|
|
return data, nil
|
|
}
|
|
|
|
func (a Agent) readPythonVerificationCache(name string, limit int64) ([]byte, error) {
|
|
directory := a.pythonMetadataDirectory()
|
|
if filepath.Base(name) != name || requirePhysicalDirectory(directory) != nil {
|
|
return nil, errors.New("unsafe metadata cache")
|
|
}
|
|
info, err := os.Lstat(directory)
|
|
if err != nil || !rootOwnedPythonMetadata(info) || info.Mode().Perm()&0022 != 0 {
|
|
return nil, errors.New("untrusted metadata cache directory")
|
|
}
|
|
root, err := os.OpenRoot(directory)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer root.Close()
|
|
info, err = root.Lstat(name)
|
|
if err != nil || !info.Mode().IsRegular() || !rootOwnedPythonMetadata(info) || info.Mode().Perm()&0022 != 0 || info.Size() > limit {
|
|
return nil, errors.New("untrusted metadata cache file")
|
|
}
|
|
file, err := root.Open(name)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer file.Close()
|
|
data, err := io.ReadAll(io.LimitReader(file, limit+1))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if int64(len(data)) > limit {
|
|
return nil, errors.New("metadata cache exceeds limit")
|
|
}
|
|
return data, nil
|
|
}
|
|
|
|
func (a Agent) cachePythonMetadata(name string, data []byte) {
|
|
if !canWritePythonMetadataCache() || filepath.Base(name) != name {
|
|
return
|
|
}
|
|
directory := a.pythonMetadataDirectory()
|
|
if os.MkdirAll(directory, 0700) != nil || requirePhysicalDirectory(directory) != nil {
|
|
return
|
|
}
|
|
info, err := os.Lstat(directory)
|
|
if err != nil || !rootOwnedPythonMetadata(info) || info.Mode().Perm()&0022 != 0 {
|
|
return
|
|
}
|
|
file, err := os.CreateTemp(directory, ".metadata-")
|
|
if err != nil {
|
|
return
|
|
}
|
|
temporary := file.Name()
|
|
defer os.Remove(temporary)
|
|
if file.Chmod(0600) != nil {
|
|
file.Close()
|
|
return
|
|
}
|
|
if _, err = file.Write(data); err != nil {
|
|
file.Close()
|
|
return
|
|
}
|
|
if file.Close() != nil {
|
|
return
|
|
}
|
|
_ = os.Rename(temporary, filepath.Join(directory, name))
|
|
}
|