179 lines
4.9 KiB
Go
179 lines
4.9 KiB
Go
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
|
|
// Package assurance appends Python-schema-compatible hash-chain records for
|
|
// local forensic artifacts. Artifact hashing streams from disk, and previous-
|
|
// record lookup reads only a bounded tail of the chain.
|
|
package assurance
|
|
|
|
import (
|
|
"bufio"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
const (
|
|
Schema = "enodia.hash_chain.v1"
|
|
ChainName = "hash-chain.jsonl"
|
|
maxTailBytes = 1 << 20
|
|
)
|
|
|
|
type Record struct {
|
|
Schema string `json:"schema"`
|
|
Time float64 `json:"time"`
|
|
Kind string `json:"kind"`
|
|
Path string `json:"path"`
|
|
Size int64 `json:"size"`
|
|
SHA256 string `json:"sha256"`
|
|
PrevHash string `json:"prev_hash"`
|
|
ChainHash string `json:"chain_hash"`
|
|
}
|
|
|
|
type Chain struct {
|
|
Path string
|
|
mu sync.Mutex
|
|
}
|
|
|
|
// New preflights the private append-only chain file before service readiness.
|
|
func New(directory string) (*Chain, error) {
|
|
if directory == "" {
|
|
return nil, fmt.Errorf("assurance directory is required")
|
|
}
|
|
if err := os.MkdirAll(directory, 0o750); err != nil {
|
|
return nil, fmt.Errorf("create assurance directory: %w", err)
|
|
}
|
|
path := filepath.Join(directory, ChainName)
|
|
file, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("preflight assurance chain: %w", err)
|
|
}
|
|
if err := file.Close(); err != nil {
|
|
return nil, fmt.Errorf("close assurance chain: %w", err)
|
|
}
|
|
if err := os.Chmod(path, 0o600); err != nil {
|
|
return nil, fmt.Errorf("protect assurance chain: %w", err)
|
|
}
|
|
return &Chain{Path: path}, nil
|
|
}
|
|
|
|
// Append hashes artifact and durably appends its chained evidence record.
|
|
func (c *Chain) Append(kind, artifact string, when time.Time) (Record, error) {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
digest, size, err := fileDigest(artifact)
|
|
if err != nil {
|
|
// Python records unavailable artifacts with empty evidence rather than
|
|
// dropping the chain entry.
|
|
digest, size = "", 0
|
|
}
|
|
previous, err := lastHash(c.Path)
|
|
if err != nil {
|
|
return Record{}, err
|
|
}
|
|
record := Record{
|
|
Schema: Schema, Time: float64(when.UnixNano()) / 1e9, Kind: kind,
|
|
Path: artifact, Size: size, SHA256: digest, PrevHash: previous,
|
|
}
|
|
payload, err := canonicalPayload(record)
|
|
if err != nil {
|
|
return Record{}, err
|
|
}
|
|
sum := sha256.Sum256(append(payload, []byte(previous)...))
|
|
record.ChainHash = hex.EncodeToString(sum[:])
|
|
raw, err := json.Marshal(record)
|
|
if err != nil {
|
|
return Record{}, fmt.Errorf("encode assurance record: %w", err)
|
|
}
|
|
file, err := os.OpenFile(c.Path, os.O_APPEND|os.O_WRONLY, 0o600)
|
|
if err != nil {
|
|
return Record{}, fmt.Errorf("open assurance chain: %w", err)
|
|
}
|
|
defer file.Close()
|
|
if _, err := file.Write(append(raw, '\n')); err != nil {
|
|
return Record{}, fmt.Errorf("append assurance chain: %w", err)
|
|
}
|
|
if err := file.Sync(); err != nil {
|
|
return Record{}, fmt.Errorf("sync assurance chain: %w", err)
|
|
}
|
|
return record, nil
|
|
}
|
|
|
|
func fileDigest(path string) (string, int64, error) {
|
|
file, err := os.Open(path)
|
|
if err != nil {
|
|
return "", 0, err
|
|
}
|
|
defer file.Close()
|
|
hash := sha256.New()
|
|
size, err := io.Copy(hash, file)
|
|
if err != nil {
|
|
return "", 0, err
|
|
}
|
|
return hex.EncodeToString(hash.Sum(nil)), size, nil
|
|
}
|
|
|
|
func lastHash(path string) (string, error) {
|
|
file, err := os.Open(path)
|
|
if err != nil {
|
|
return "", fmt.Errorf("open assurance tail: %w", err)
|
|
}
|
|
defer file.Close()
|
|
info, err := file.Stat()
|
|
if err != nil {
|
|
return "", fmt.Errorf("stat assurance chain: %w", err)
|
|
}
|
|
offset := info.Size() - maxTailBytes
|
|
if offset < 0 {
|
|
offset = 0
|
|
}
|
|
if _, err := file.Seek(offset, io.SeekStart); err != nil {
|
|
return "", fmt.Errorf("seek assurance tail: %w", err)
|
|
}
|
|
raw, err := io.ReadAll(io.LimitReader(file, maxTailBytes))
|
|
if err != nil {
|
|
return "", fmt.Errorf("read assurance tail: %w", err)
|
|
}
|
|
lines := strings.Split(strings.TrimSpace(string(raw)), "\n")
|
|
for index := len(lines) - 1; index >= 0; index-- {
|
|
var record Record
|
|
if json.Unmarshal([]byte(lines[index]), &record) == nil && record.ChainHash != "" {
|
|
return record.ChainHash, nil
|
|
}
|
|
}
|
|
return "", nil
|
|
}
|
|
|
|
func canonicalPayload(record Record) ([]byte, error) {
|
|
// encoding/json sorts string map keys, matching Python's sort_keys=True.
|
|
return json.Marshal(map[string]any{
|
|
"schema": record.Schema, "time": record.Time, "kind": record.Kind,
|
|
"path": record.Path, "size": record.Size, "sha256": record.SHA256,
|
|
"prev_hash": record.PrevHash,
|
|
})
|
|
}
|
|
|
|
// ReadAll decodes a chain for verification and read-only consumers.
|
|
func ReadAll(path string) ([]Record, error) {
|
|
file, err := os.Open(path)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer file.Close()
|
|
var records []Record
|
|
scanner := bufio.NewScanner(file)
|
|
for scanner.Scan() {
|
|
var record Record
|
|
if err := json.Unmarshal(scanner.Bytes(), &record); err != nil {
|
|
return nil, err
|
|
}
|
|
records = append(records, record)
|
|
}
|
|
return records, scanner.Err()
|
|
}
|