2021-01-10 14:44:32 -07:00
|
|
|
// Package tofu implements trust on first use using hosts and fingerprints.
|
|
|
|
package tofu
|
2020-09-25 16:53:20 -06:00
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
2021-01-13 14:33:48 -07:00
|
|
|
"bytes"
|
2020-09-25 16:53:20 -06:00
|
|
|
"crypto/sha512"
|
2021-01-13 14:33:48 -07:00
|
|
|
"crypto/x509"
|
|
|
|
"errors"
|
2020-09-25 16:53:20 -06:00
|
|
|
"fmt"
|
|
|
|
"io"
|
2021-01-14 14:54:38 -07:00
|
|
|
"os"
|
2021-01-14 16:50:03 -07:00
|
|
|
"sort"
|
2020-11-05 20:30:13 -07:00
|
|
|
"strconv"
|
2020-09-25 16:53:20 -06:00
|
|
|
"strings"
|
2020-12-17 15:07:00 -07:00
|
|
|
"sync"
|
2020-11-09 10:04:53 -07:00
|
|
|
"time"
|
2020-09-25 16:53:20 -06:00
|
|
|
)
|
|
|
|
|
2021-01-14 14:14:40 -07:00
|
|
|
// KnownHosts represents a list of known hosts.
|
|
|
|
// The zero value for KnownHosts represents an empty list ready to use.
|
2020-12-17 14:49:59 -07:00
|
|
|
//
|
2021-01-14 14:14:40 -07:00
|
|
|
// KnownHosts is safe for concurrent use by multiple goroutines.
|
|
|
|
type KnownHosts struct {
|
|
|
|
hosts map[string]Host
|
|
|
|
mu sync.RWMutex
|
2020-11-09 10:26:08 -07:00
|
|
|
}
|
|
|
|
|
2021-01-14 14:14:40 -07:00
|
|
|
// Add adds a host to the list of known hosts.
|
2021-01-25 10:02:09 -07:00
|
|
|
func (k *KnownHosts) Add(h Host) {
|
2021-01-13 14:33:48 -07:00
|
|
|
k.mu.Lock()
|
|
|
|
defer k.mu.Unlock()
|
|
|
|
if k.hosts == nil {
|
2021-01-14 12:15:08 -07:00
|
|
|
k.hosts = map[string]Host{}
|
2021-01-13 14:33:48 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
k.hosts[h.Hostname] = h
|
2020-11-09 10:04:53 -07:00
|
|
|
}
|
|
|
|
|
2021-01-14 14:14:40 -07:00
|
|
|
// Lookup returns the known host entry corresponding to the given hostname.
|
|
|
|
func (k *KnownHosts) Lookup(hostname string) (Host, bool) {
|
2021-01-13 14:33:48 -07:00
|
|
|
k.mu.RLock()
|
|
|
|
defer k.mu.RUnlock()
|
|
|
|
c, ok := k.hosts[hostname]
|
|
|
|
return c, ok
|
|
|
|
}
|
|
|
|
|
2021-01-14 16:52:43 -07:00
|
|
|
// Entries returns the known host entries sorted by hostname.
|
|
|
|
func (k *KnownHosts) Entries() []Host {
|
2021-01-14 16:50:03 -07:00
|
|
|
keys := make([]string, 0, len(k.hosts))
|
|
|
|
for key := range k.hosts {
|
|
|
|
keys = append(keys, key)
|
|
|
|
}
|
|
|
|
sort.Strings(keys)
|
|
|
|
|
|
|
|
hosts := make([]Host, 0, len(k.hosts))
|
|
|
|
for _, key := range keys {
|
|
|
|
hosts = append(hosts, k.hosts[key])
|
|
|
|
}
|
|
|
|
return hosts
|
|
|
|
}
|
|
|
|
|
2021-01-14 14:14:40 -07:00
|
|
|
// WriteTo writes the list of known hosts to the provided io.Writer.
|
|
|
|
func (k *KnownHosts) WriteTo(w io.Writer) (int64, error) {
|
2020-12-17 14:49:59 -07:00
|
|
|
k.mu.RLock()
|
|
|
|
defer k.mu.RUnlock()
|
2021-01-13 14:33:48 -07:00
|
|
|
|
2021-01-14 14:14:40 -07:00
|
|
|
var written int
|
2021-01-13 14:33:48 -07:00
|
|
|
|
2021-01-14 14:14:40 -07:00
|
|
|
bw := bufio.NewWriter(w)
|
2021-01-13 14:33:48 -07:00
|
|
|
for _, h := range k.hosts {
|
2021-01-14 14:14:40 -07:00
|
|
|
n, err := bw.WriteString(h.String())
|
|
|
|
written += n
|
2021-01-13 14:33:48 -07:00
|
|
|
if err != nil {
|
2021-01-14 14:14:40 -07:00
|
|
|
return int64(written), err
|
2020-11-09 10:04:53 -07:00
|
|
|
}
|
2021-01-13 14:33:48 -07:00
|
|
|
|
|
|
|
bw.WriteByte('\n')
|
2021-01-14 14:14:40 -07:00
|
|
|
written += 1
|
2020-09-25 21:06:54 -06:00
|
|
|
}
|
2021-01-13 14:33:48 -07:00
|
|
|
|
2021-01-14 14:14:40 -07:00
|
|
|
return int64(written), bw.Flush()
|
2020-09-25 21:06:54 -06:00
|
|
|
}
|
|
|
|
|
2021-01-14 15:09:31 -07:00
|
|
|
// Load loads the known hosts entries from the provided path.
|
|
|
|
func (k *KnownHosts) Load(path string) error {
|
|
|
|
f, err := os.Open(path)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer f.Close()
|
|
|
|
|
|
|
|
return k.Parse(f)
|
|
|
|
}
|
|
|
|
|
2021-01-14 14:14:40 -07:00
|
|
|
// Parse parses the provided io.Reader and adds the parsed hosts to the list.
|
2020-11-09 10:26:08 -07:00
|
|
|
// Invalid entries are ignored.
|
2021-01-14 14:14:40 -07:00
|
|
|
//
|
2021-01-14 17:56:04 -07:00
|
|
|
// For more control over errors encountered during parsing, use bufio.Scanner
|
|
|
|
// in combination with ParseHost. For example:
|
|
|
|
//
|
|
|
|
// var knownHosts tofu.KnownHosts
|
|
|
|
// scanner := bufio.NewScanner(r)
|
|
|
|
// for scanner.Scan() {
|
2021-01-14 17:57:52 -07:00
|
|
|
// host, err := tofu.ParseHost(scanner.Bytes())
|
2021-01-14 17:56:04 -07:00
|
|
|
// if err != nil {
|
|
|
|
// // handle error
|
|
|
|
// } else {
|
|
|
|
// knownHosts.Add(host)
|
|
|
|
// }
|
|
|
|
// }
|
|
|
|
// err := scanner.Err()
|
|
|
|
// if err != nil {
|
|
|
|
// // handle error
|
|
|
|
// }
|
|
|
|
//
|
2021-01-14 14:14:40 -07:00
|
|
|
func (k *KnownHosts) Parse(r io.Reader) error {
|
2020-12-17 14:49:59 -07:00
|
|
|
k.mu.Lock()
|
|
|
|
defer k.mu.Unlock()
|
2021-01-13 14:33:48 -07:00
|
|
|
|
|
|
|
if k.hosts == nil {
|
2021-01-14 12:15:08 -07:00
|
|
|
k.hosts = map[string]Host{}
|
2020-10-13 17:54:48 -06:00
|
|
|
}
|
2021-01-13 14:33:48 -07:00
|
|
|
|
2020-09-25 16:53:20 -06:00
|
|
|
scanner := bufio.NewScanner(r)
|
|
|
|
for scanner.Scan() {
|
2021-01-13 14:33:48 -07:00
|
|
|
text := scanner.Bytes()
|
|
|
|
if len(text) == 0 {
|
2020-10-13 17:54:48 -06:00
|
|
|
continue
|
|
|
|
}
|
2020-09-25 16:53:20 -06:00
|
|
|
|
2021-01-14 14:14:40 -07:00
|
|
|
h, err := ParseHost(text)
|
2020-11-05 20:30:13 -07:00
|
|
|
if err != nil {
|
2021-01-14 14:14:40 -07:00
|
|
|
continue
|
2020-11-05 20:30:13 -07:00
|
|
|
}
|
|
|
|
|
2021-01-13 14:33:48 -07:00
|
|
|
k.hosts[h.Hostname] = h
|
|
|
|
}
|
|
|
|
|
2021-01-14 14:14:40 -07:00
|
|
|
return scanner.Err()
|
2020-09-25 18:55:37 -06:00
|
|
|
}
|
2020-09-25 16:53:20 -06:00
|
|
|
|
2021-01-14 17:56:04 -07:00
|
|
|
// TOFU implements basic trust on first use.
|
2021-01-14 17:40:19 -07:00
|
|
|
//
|
|
|
|
// If the host is not on file, it is added to the list.
|
2021-01-25 10:02:09 -07:00
|
|
|
// If the host on file is expired, a new entry is added to the list.
|
2021-01-14 17:40:19 -07:00
|
|
|
// If the fingerprint does not match the one on file, an error is returned.
|
2021-01-14 14:14:40 -07:00
|
|
|
func (k *KnownHosts) TOFU(hostname string, cert *x509.Certificate) error {
|
2021-01-14 12:15:08 -07:00
|
|
|
host := NewHost(hostname, cert.Raw, cert.NotAfter)
|
2021-01-13 14:33:48 -07:00
|
|
|
|
|
|
|
knownHost, ok := k.Lookup(hostname)
|
|
|
|
if !ok || time.Now().After(knownHost.Expires) {
|
|
|
|
k.Add(host)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check fingerprint
|
|
|
|
if !bytes.Equal(knownHost.Fingerprint, host.Fingerprint) {
|
|
|
|
return fmt.Errorf("fingerprint for %q does not match", hostname)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
2020-09-25 18:22:48 -06:00
|
|
|
}
|
|
|
|
|
2021-01-14 14:54:38 -07:00
|
|
|
// HostWriter writes host entries to an io.WriteCloser.
|
|
|
|
//
|
|
|
|
// HostWriter is safe for concurrent use by multiple goroutines.
|
2021-01-14 14:14:40 -07:00
|
|
|
type HostWriter struct {
|
|
|
|
bw *bufio.Writer
|
2021-01-14 14:54:38 -07:00
|
|
|
cl io.Closer
|
2021-01-14 14:35:54 -07:00
|
|
|
mu sync.Mutex
|
2021-01-14 14:14:40 -07:00
|
|
|
}
|
2021-01-13 14:33:48 -07:00
|
|
|
|
2021-01-14 14:54:38 -07:00
|
|
|
// NewHostWriter returns a new host writer that writes to
|
|
|
|
// the provided io.WriteCloser.
|
|
|
|
func NewHostWriter(w io.WriteCloser) *HostWriter {
|
2021-01-14 14:14:40 -07:00
|
|
|
return &HostWriter{
|
|
|
|
bw: bufio.NewWriter(w),
|
2021-01-14 14:54:38 -07:00
|
|
|
cl: w,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-01-25 10:02:09 -07:00
|
|
|
// OpenHostsFile returns a new host writer that appends to the file at the given path.
|
2021-01-14 17:56:04 -07:00
|
|
|
// The file is created if it does not exist.
|
2021-01-25 10:02:09 -07:00
|
|
|
func OpenHostsFile(path string) (*HostWriter, error) {
|
2021-01-14 14:54:38 -07:00
|
|
|
f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
2021-01-14 14:14:40 -07:00
|
|
|
}
|
2021-01-14 14:54:38 -07:00
|
|
|
return NewHostWriter(f), nil
|
2021-01-14 14:14:40 -07:00
|
|
|
}
|
2021-01-13 14:33:48 -07:00
|
|
|
|
2021-01-14 14:14:40 -07:00
|
|
|
// WriteHost writes the host to the underlying io.Writer.
|
2021-01-14 14:35:54 -07:00
|
|
|
func (h *HostWriter) WriteHost(host Host) error {
|
|
|
|
h.mu.Lock()
|
|
|
|
defer h.mu.Unlock()
|
2021-01-13 14:33:48 -07:00
|
|
|
|
2021-01-14 14:35:54 -07:00
|
|
|
h.bw.WriteString(host.String())
|
|
|
|
h.bw.WriteByte('\n')
|
|
|
|
|
|
|
|
if err := h.bw.Flush(); err != nil {
|
2021-01-14 14:54:38 -07:00
|
|
|
return fmt.Errorf("failed to write host: %w", err)
|
2020-12-16 21:58:02 -07:00
|
|
|
}
|
2021-01-14 14:14:40 -07:00
|
|
|
return nil
|
2021-01-13 14:33:48 -07:00
|
|
|
}
|
|
|
|
|
2021-01-14 17:56:04 -07:00
|
|
|
// Close closes the underlying io.Closer.
|
2021-01-14 14:54:38 -07:00
|
|
|
func (h *HostWriter) Close() error {
|
|
|
|
h.mu.Lock()
|
|
|
|
defer h.mu.Unlock()
|
|
|
|
return h.cl.Close()
|
|
|
|
}
|
|
|
|
|
2021-01-25 10:02:09 -07:00
|
|
|
// PersistentHosts represents a persistent set of known hosts.
|
|
|
|
type PersistentHosts struct {
|
|
|
|
hosts *KnownHosts
|
|
|
|
writer *HostWriter
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewPersistentHosts returns a new persistent set of known hosts.
|
|
|
|
func NewPersistentHosts(hosts *KnownHosts, writer *HostWriter) *PersistentHosts {
|
|
|
|
return &PersistentHosts{
|
|
|
|
hosts,
|
|
|
|
writer,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// LoadPersistentHosts loads persistent hosts from the file at the given path.
|
|
|
|
func LoadPersistentHosts(path string) (*PersistentHosts, error) {
|
|
|
|
hosts := &KnownHosts{}
|
|
|
|
if err := hosts.Load(path); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
writer, err := OpenHostsFile(path)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return &PersistentHosts{
|
|
|
|
hosts,
|
|
|
|
writer,
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Add adds a host to the list of known hosts.
|
|
|
|
// It returns an error if the host could not be persisted.
|
|
|
|
func (p *PersistentHosts) Add(h Host) error {
|
|
|
|
err := p.writer.WriteHost(h)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("failed to persist host: %w", err)
|
|
|
|
}
|
|
|
|
p.hosts.Add(h)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Lookup returns the known host entry corresponding to the given hostname.
|
|
|
|
func (p *PersistentHosts) Lookup(hostname string) (Host, bool) {
|
|
|
|
return p.hosts.Lookup(hostname)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Entries returns the known host entries sorted by hostname.
|
|
|
|
func (p *PersistentHosts) Entries() []Host {
|
|
|
|
return p.hosts.Entries()
|
|
|
|
}
|
|
|
|
|
|
|
|
// TOFU implements trust on first use with a persistent set of known hosts.
|
|
|
|
//
|
|
|
|
// If the host is not on file, it is added to the list.
|
|
|
|
// If the host on file is expired, a new entry is added to the list.
|
|
|
|
// If the fingerprint does not match the one on file, an error is returned.
|
|
|
|
func (p *PersistentHosts) TOFU(hostname string, cert *x509.Certificate) error {
|
|
|
|
host := NewHost(hostname, cert.Raw, cert.NotAfter)
|
|
|
|
|
|
|
|
knownHost, ok := p.Lookup(hostname)
|
|
|
|
if !ok || time.Now().After(knownHost.Expires) {
|
|
|
|
return p.Add(host)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check fingerprint
|
|
|
|
if !bytes.Equal(knownHost.Fingerprint, host.Fingerprint) {
|
|
|
|
return fmt.Errorf("fingerprint for %q does not match", hostname)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Close closes the underlying HostWriter.
|
|
|
|
func (p *PersistentHosts) Close() error {
|
|
|
|
return p.writer.Close()
|
|
|
|
}
|
|
|
|
|
2021-01-14 14:14:40 -07:00
|
|
|
// Host represents a host entry with a fingerprint using a certain algorithm.
|
2021-01-14 12:15:08 -07:00
|
|
|
type Host struct {
|
2021-01-13 14:33:48 -07:00
|
|
|
Hostname string // hostname
|
|
|
|
Algorithm string // fingerprint algorithm e.g. SHA-512
|
|
|
|
Fingerprint Fingerprint // fingerprint
|
|
|
|
Expires time.Time // unix time of the fingerprint expiration date
|
|
|
|
}
|
|
|
|
|
2021-01-14 14:14:40 -07:00
|
|
|
// NewHost returns a new host with a SHA-512 fingerprint of
|
|
|
|
// the provided raw data.
|
2021-01-14 12:15:08 -07:00
|
|
|
func NewHost(hostname string, raw []byte, expires time.Time) Host {
|
|
|
|
sum := sha512.Sum512(raw)
|
|
|
|
|
|
|
|
return Host{
|
|
|
|
Hostname: hostname,
|
|
|
|
Algorithm: "SHA-512",
|
|
|
|
Fingerprint: sum[:],
|
|
|
|
Expires: expires,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-01-14 14:14:40 -07:00
|
|
|
// ParseHost parses a host from the provided text.
|
|
|
|
func ParseHost(text []byte) (Host, error) {
|
|
|
|
var h Host
|
|
|
|
err := h.UnmarshalText(text)
|
|
|
|
return h, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// String returns a string representation of the host.
|
|
|
|
func (h Host) String() string {
|
|
|
|
var b strings.Builder
|
|
|
|
b.WriteString(h.Hostname)
|
|
|
|
b.WriteByte(' ')
|
|
|
|
b.WriteString(h.Algorithm)
|
|
|
|
b.WriteByte(' ')
|
|
|
|
b.WriteString(h.Fingerprint.String())
|
|
|
|
b.WriteByte(' ')
|
|
|
|
b.WriteString(strconv.FormatInt(h.Expires.Unix(), 10))
|
|
|
|
return b.String()
|
|
|
|
}
|
|
|
|
|
|
|
|
// UnmarshalText unmarshals the host from the provided text.
|
2021-01-14 12:15:08 -07:00
|
|
|
func (h *Host) UnmarshalText(text []byte) error {
|
2021-01-13 14:33:48 -07:00
|
|
|
const format = "hostname algorithm hex-fingerprint expiry-unix-ts"
|
|
|
|
|
|
|
|
parts := bytes.Split(text, []byte(" "))
|
|
|
|
if len(parts) != 4 {
|
2021-01-25 10:02:09 -07:00
|
|
|
return fmt.Errorf("expected the format %q", format)
|
2021-01-13 14:33:48 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
if len(parts[0]) == 0 {
|
|
|
|
return errors.New("empty hostname")
|
|
|
|
}
|
|
|
|
|
2021-01-14 12:15:08 -07:00
|
|
|
h.Hostname = string(parts[0])
|
2021-01-13 14:33:48 -07:00
|
|
|
|
|
|
|
algorithm := string(parts[1])
|
|
|
|
if algorithm != "SHA-512" {
|
2021-01-25 10:02:09 -07:00
|
|
|
return fmt.Errorf("unsupported algorithm %q", algorithm)
|
2021-01-13 14:33:48 -07:00
|
|
|
}
|
|
|
|
|
2021-01-14 12:15:08 -07:00
|
|
|
h.Algorithm = algorithm
|
2021-01-13 14:33:48 -07:00
|
|
|
|
|
|
|
fingerprint := make([]byte, 0, sha512.Size)
|
2021-01-14 14:14:40 -07:00
|
|
|
scanner := bufio.NewScanner(bytes.NewReader(parts[2]))
|
|
|
|
scanner.Split(scanFingerprint)
|
2021-01-13 14:33:48 -07:00
|
|
|
|
2021-01-14 14:14:40 -07:00
|
|
|
for scanner.Scan() {
|
|
|
|
b, err := strconv.ParseUint(scanner.Text(), 16, 8)
|
2021-01-13 14:33:48 -07:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("failed to parse fingerprint hash: %w", err)
|
|
|
|
}
|
|
|
|
fingerprint = append(fingerprint, byte(b))
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(fingerprint) != sha512.Size {
|
|
|
|
return fmt.Errorf("invalid fingerprint size %d, expected %d",
|
|
|
|
len(fingerprint), sha512.Size)
|
|
|
|
}
|
|
|
|
|
2021-01-14 12:15:08 -07:00
|
|
|
h.Fingerprint = fingerprint
|
2021-01-13 14:33:48 -07:00
|
|
|
|
|
|
|
unix, err := strconv.ParseInt(string(parts[3]), 10, 0)
|
|
|
|
if err != nil {
|
2021-01-25 10:02:09 -07:00
|
|
|
return fmt.Errorf("invalid unix timestamp: %w", err)
|
2021-01-13 14:33:48 -07:00
|
|
|
}
|
|
|
|
|
2021-01-14 12:15:08 -07:00
|
|
|
h.Expires = time.Unix(unix, 0)
|
2021-01-13 14:33:48 -07:00
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func scanFingerprint(data []byte, atEOF bool) (advance int, token []byte, err error) {
|
|
|
|
if atEOF && len(data) == 0 {
|
|
|
|
return 0, nil, nil
|
|
|
|
}
|
|
|
|
if i := bytes.IndexByte(data, ':'); i >= 0 {
|
|
|
|
// We have a full newline-terminated line.
|
|
|
|
return i + 1, data[0:i], nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// If we're at EOF, we have a final, non-terminated hex byte
|
|
|
|
if atEOF {
|
|
|
|
return len(data), data, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Request more data.
|
|
|
|
return 0, nil, nil
|
|
|
|
}
|
2021-01-14 14:14:40 -07:00
|
|
|
|
|
|
|
// Fingerprint represents a fingerprint.
|
|
|
|
type Fingerprint []byte
|
|
|
|
|
|
|
|
// String returns a string representation of the fingerprint.
|
|
|
|
func (f Fingerprint) String() string {
|
|
|
|
var sb strings.Builder
|
|
|
|
|
|
|
|
for i, b := range f {
|
|
|
|
if i > 0 {
|
|
|
|
sb.WriteByte(':')
|
|
|
|
}
|
|
|
|
|
|
|
|
fmt.Fprintf(&sb, "%02X", b)
|
|
|
|
}
|
|
|
|
|
|
|
|
return sb.String()
|
|
|
|
}
|