You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
291 lines
8.7 KiB
Go
291 lines
8.7 KiB
Go
package publicguard
|
|
|
|
import (
|
|
"bytes"
|
|
"crypto/sha256"
|
|
"crypto/subtle"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"path/filepath"
|
|
"reflect"
|
|
"strings"
|
|
"syscall"
|
|
|
|
"golang.org/x/sys/unix"
|
|
)
|
|
|
|
const (
|
|
projectionStateVersion = uint64(1)
|
|
maximumStateBytes = 4 << 20
|
|
)
|
|
|
|
type projectionStore struct {
|
|
path string
|
|
ownerUID uint32
|
|
}
|
|
|
|
type projectionPayload struct {
|
|
Version uint64 `json:"version"`
|
|
Bindings []Binding `json:"bindings"`
|
|
}
|
|
|
|
type projectionDocument struct {
|
|
Version uint64 `json:"version"`
|
|
Bindings []Binding `json:"bindings"`
|
|
SHA256 string `json:"sha256"`
|
|
}
|
|
|
|
func openProjectionStore(path string) (*projectionStore, []Binding, error) {
|
|
store, err := newProjectionStore(path, 0)
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
bindings, err := store.load(false)
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
return store, bindings, nil
|
|
}
|
|
|
|
func newProjectionStore(path string, ownerUID uint32) (*projectionStore, error) {
|
|
if path == "" || !filepath.IsAbs(path) || filepath.Clean(path) != path ||
|
|
path == string(filepath.Separator) || strings.ContainsRune(path, 0) {
|
|
return nil, errors.New("public guard state path must be a clean absolute path")
|
|
}
|
|
store := &projectionStore{path: path, ownerUID: ownerUID}
|
|
if err := store.validateDirectory(); err != nil {
|
|
return nil, err
|
|
}
|
|
return store, nil
|
|
}
|
|
|
|
func (store *projectionStore) validateDirectory() error {
|
|
if store == nil {
|
|
return errors.New("public guard state store is unavailable")
|
|
}
|
|
info, err := os.Lstat(filepath.Dir(store.path))
|
|
if err != nil || !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
|
|
return fmt.Errorf("public guard state directory is unavailable: %w", err)
|
|
}
|
|
uid, ok := ownerUID(info)
|
|
if !ok || uid != store.ownerUID {
|
|
return errors.New("public guard state directory must have the expected owner")
|
|
}
|
|
if info.Mode().Perm()&0o022 != 0 {
|
|
return errors.New("public guard state directory must not be group or world writable")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (store *projectionStore) load(required bool) ([]Binding, error) {
|
|
if store == nil {
|
|
return nil, errors.New("public guard state store is unavailable")
|
|
}
|
|
descriptor, err := unix.Open(store.path, unix.O_RDONLY|unix.O_CLOEXEC|unix.O_NOFOLLOW, 0)
|
|
if errors.Is(err, unix.ENOENT) {
|
|
if required {
|
|
return nil, errors.New("public guard state is missing")
|
|
}
|
|
return nil, nil
|
|
}
|
|
if err != nil {
|
|
return nil, fmt.Errorf("open public guard state: %w", err)
|
|
}
|
|
file := os.NewFile(uintptr(descriptor), store.path)
|
|
if file == nil {
|
|
_ = unix.Close(descriptor)
|
|
return nil, errors.New("open public guard state")
|
|
}
|
|
defer file.Close()
|
|
info, err := file.Stat()
|
|
if err != nil {
|
|
return nil, fmt.Errorf("inspect public guard state: %w", err)
|
|
}
|
|
if err := store.validateFile(info); err != nil {
|
|
return nil, err
|
|
}
|
|
raw, err := io.ReadAll(io.LimitReader(file, maximumStateBytes+1))
|
|
if err != nil {
|
|
return nil, fmt.Errorf("read public guard state: %w", err)
|
|
}
|
|
if len(raw) == 0 || len(raw) > maximumStateBytes {
|
|
return nil, errors.New("public guard state is empty or oversized")
|
|
}
|
|
return decodeProjectionDocument(raw)
|
|
}
|
|
|
|
func (store *projectionStore) validateFile(info os.FileInfo) error {
|
|
if info == nil || !info.Mode().IsRegular() ||
|
|
info.Mode().Perm() != 0o600 ||
|
|
info.Mode()&(os.ModeSetuid|os.ModeSetgid|os.ModeSticky) != 0 {
|
|
return errors.New("public guard state must be a regular 0600 file")
|
|
}
|
|
uid, ok := ownerUID(info)
|
|
if !ok || uid != store.ownerUID {
|
|
return errors.New("public guard state must have the expected owner")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func ownerUID(info os.FileInfo) (uint32, bool) {
|
|
if info == nil {
|
|
return 0, false
|
|
}
|
|
stat, ok := info.Sys().(*syscall.Stat_t)
|
|
if !ok {
|
|
return 0, false
|
|
}
|
|
return stat.Uid, true
|
|
}
|
|
|
|
func (store *projectionStore) save(bindings []Binding) error {
|
|
if store == nil {
|
|
return errors.New("public guard state store is unavailable")
|
|
}
|
|
normalized, err := normalizeProjection(bindings)
|
|
if err != nil {
|
|
return fmt.Errorf("validate public guard state: %w", err)
|
|
}
|
|
encoded, err := encodeProjectionDocument(normalized)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := store.validateDirectory(); err != nil {
|
|
return err
|
|
}
|
|
if info, statErr := os.Lstat(store.path); statErr == nil {
|
|
if info.Mode()&os.ModeSymlink != 0 {
|
|
return errors.New("public guard state must not be a symbolic link")
|
|
}
|
|
if err := store.validateFile(info); err != nil {
|
|
return err
|
|
}
|
|
} else if !errors.Is(statErr, os.ErrNotExist) {
|
|
return fmt.Errorf("inspect public guard state: %w", statErr)
|
|
}
|
|
|
|
temporary, err := os.CreateTemp(filepath.Dir(store.path), ".public-guard-v1-*")
|
|
if err != nil {
|
|
return fmt.Errorf("create public guard state: %w", err)
|
|
}
|
|
temporaryPath := temporary.Name()
|
|
installed := false
|
|
defer func() {
|
|
_ = temporary.Close()
|
|
if !installed {
|
|
_ = os.Remove(temporaryPath)
|
|
}
|
|
}()
|
|
if err := temporary.Chmod(0o600); err != nil {
|
|
return fmt.Errorf("secure public guard state: %w", err)
|
|
}
|
|
if info, err := temporary.Stat(); err != nil {
|
|
return fmt.Errorf("inspect public guard state temporary file: %w", err)
|
|
} else if err := store.validateFile(info); err != nil {
|
|
return err
|
|
}
|
|
if written, err := temporary.Write(encoded); err != nil {
|
|
return fmt.Errorf("write public guard state: %w", err)
|
|
} else if written != len(encoded) {
|
|
return fmt.Errorf("write public guard state: %w", io.ErrShortWrite)
|
|
}
|
|
if err := temporary.Sync(); err != nil {
|
|
return fmt.Errorf("synchronize public guard state: %w", err)
|
|
}
|
|
if err := temporary.Close(); err != nil {
|
|
return fmt.Errorf("close public guard state: %w", err)
|
|
}
|
|
if err := os.Rename(temporaryPath, store.path); err != nil {
|
|
return fmt.Errorf("install public guard state: %w", err)
|
|
}
|
|
installed = true
|
|
directory, err := os.Open(filepath.Dir(store.path))
|
|
if err != nil {
|
|
return fmt.Errorf("open public guard state directory for synchronization: %w", err)
|
|
}
|
|
defer directory.Close()
|
|
if err := directory.Sync(); err != nil {
|
|
return fmt.Errorf("synchronize public guard state directory: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (store *projectionStore) commit(bindings []Binding) error {
|
|
current, err := store.load(false)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
normalized, err := normalizeProjection(bindings)
|
|
if err != nil {
|
|
return fmt.Errorf("validate public guard state: %w", err)
|
|
}
|
|
if current != nil && reflect.DeepEqual(current, normalized) {
|
|
return nil
|
|
}
|
|
return store.save(normalized)
|
|
}
|
|
|
|
func encodeProjectionDocument(bindings []Binding) ([]byte, error) {
|
|
payload := projectionPayload{Version: projectionStateVersion, Bindings: bindings}
|
|
payloadJSON, err := json.Marshal(payload)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("encode public guard state payload: %w", err)
|
|
}
|
|
digest := sha256.Sum256(payloadJSON)
|
|
document := projectionDocument{
|
|
Version: payload.Version, Bindings: payload.Bindings, SHA256: hex.EncodeToString(digest[:]),
|
|
}
|
|
encoded, err := json.Marshal(document)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("encode public guard state: %w", err)
|
|
}
|
|
if len(encoded) == 0 || len(encoded) > maximumStateBytes {
|
|
return nil, errors.New("public guard state is empty or oversized")
|
|
}
|
|
return encoded, nil
|
|
}
|
|
|
|
func decodeProjectionDocument(raw []byte) ([]Binding, error) {
|
|
decoder := json.NewDecoder(bytes.NewReader(raw))
|
|
decoder.DisallowUnknownFields()
|
|
var document projectionDocument
|
|
if err := decoder.Decode(&document); err != nil {
|
|
return nil, fmt.Errorf("decode public guard state: %w", err)
|
|
}
|
|
var extra any
|
|
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
|
|
return nil, errors.New("public guard state contains trailing data")
|
|
}
|
|
if document.Version != projectionStateVersion || document.Bindings == nil ||
|
|
len(document.SHA256) != sha256.Size*2 || strings.ToLower(document.SHA256) != document.SHA256 {
|
|
return nil, errors.New("public guard state has an invalid envelope")
|
|
}
|
|
digestBytes, err := hex.DecodeString(document.SHA256)
|
|
if err != nil || len(digestBytes) != sha256.Size {
|
|
return nil, errors.New("public guard state has an invalid digest")
|
|
}
|
|
normalized, err := normalizeProjection(document.Bindings)
|
|
if err != nil || !reflect.DeepEqual(normalized, document.Bindings) {
|
|
return nil, errors.New("public guard state projection is not canonical")
|
|
}
|
|
payloadJSON, err := json.Marshal(projectionPayload{Version: document.Version, Bindings: document.Bindings})
|
|
if err != nil {
|
|
return nil, fmt.Errorf("encode public guard state payload: %w", err)
|
|
}
|
|
want := sha256.Sum256(payloadJSON)
|
|
if subtle.ConstantTimeCompare(digestBytes, want[:]) != 1 {
|
|
return nil, errors.New("public guard state digest does not match")
|
|
}
|
|
canonical, err := json.Marshal(document)
|
|
if err != nil || !bytes.Equal(raw, canonical) {
|
|
return nil, errors.New("public guard state is not exact canonical JSON")
|
|
}
|
|
bindings := make([]Binding, len(document.Bindings))
|
|
copy(bindings, document.Bindings)
|
|
return bindings, nil
|
|
}
|