15 Commits

Author SHA1 Message Date
Adnan Maolood
2144e2c2f2 status: Reintroduce StatusSensitiveInput 2021-03-15 15:19:43 -04:00
Adnan Maolood
93a606b591 certificate.Store: Call os.MkdirAll on Load 2021-03-09 08:59:28 -05:00
Adnan Maolood
b00794f236 tofu: Use stricter file permissions 2021-03-09 08:58:36 -05:00
Noah Kleiner
3da7fe7cee tofu: Create path if not exists
This commit is a follow-up to 56774408 which does not take into account
the case that the parent directory of the known_hosts file does not already exist.
2021-03-09 08:50:42 -05:00
Adnan Maolood
dea7600f29 Remove StatusSensitiveInput 2021-03-08 14:08:45 -05:00
Adnan Maolood
7d958a4798 examples/client: Fix certificate trust check 2021-03-08 14:07:18 -05:00
Adnan Maolood
a5493b708a tofu: Fix known host unmarshaling 2021-03-06 15:49:11 -05:00
Adnan Maolood
6e5c2473e7 tofu: Use base64-encoded sha256 fingerprints 2021-03-06 15:24:15 -05:00
Adnan Maolood
c639233ea1 tofu: Fix format in error message 2021-03-06 15:13:06 -05:00
Adnan Maolood
5677440876 tofu: Automatically create file in KnownHosts.Load 2021-03-06 15:11:30 -05:00
Adnan Maolood
be3d09d7f4 certificate.Store: Don't call os.MkdirAll 2021-03-06 13:11:11 -05:00
Adnan Maolood
504da9afd8 certificate.Store: Don't check parent scopes in Lookup
Limit the scopes of client certificates to hostnames only instead of
hostnames and paths.
2021-03-06 12:59:33 -05:00
Adnan Maolood
d1cb8967b6 certificate.Store: Make 100 years the default duration 2021-03-05 23:29:56 -05:00
Adnan Maolood
107b3a1785 Move LoggingMiddleware out of examples/server.go 2021-03-05 11:35:01 -05:00
Adnan Maolood
e7a06a12bf certificate.Store: Clean scope path in Load
Clean the scope path so that trimming the path from the scope works for
relative paths.
2021-03-05 10:51:55 -05:00
5 changed files with 99 additions and 173 deletions

View File

@@ -6,9 +6,7 @@ import (
"crypto/x509/pkix"
"errors"
"fmt"
"io/fs"
"os"
"path"
"path/filepath"
"strings"
"sync"
@@ -23,8 +21,7 @@ import (
// Servers will most likely use the methods Register, Load and Get.
//
// Store can also be used to store client certificates.
// Clients should provide the hostname and path of a URL as a certificate scope
// (without a trailing slash).
// Clients should provide a hostname as a certificate scope.
// Clients will most likely use the methods Add, Load, and Lookup.
//
// Store is safe for concurrent use by multiple goroutines.
@@ -86,10 +83,6 @@ func (s *Store) write(scope string, cert tls.Certificate) error {
if s.path != "" {
certPath := filepath.Join(s.path, scope+".crt")
keyPath := filepath.Join(s.path, scope+".key")
dir := filepath.Dir(certPath)
os.MkdirAll(dir, 0755)
if err := Write(cert, certPath, keyPath); err != nil {
return err
}
@@ -101,7 +94,7 @@ func (s *Store) write(scope string, cert tls.Certificate) error {
// If no matching scope has been registered, Get returns an error.
// Get generates new certificates as needed and rotates expired certificates.
// It calls CreateCertificate to create a new certificate if it is not nil,
// otherwise it creates certificates with a duration of 250 years.
// otherwise it creates certificates with a duration of 100 years.
//
// Get is suitable for use in a gemini.Server's GetCertificate field.
func (s *Store) Get(hostname string) (*tls.Certificate, error) {
@@ -142,25 +135,10 @@ func (s *Store) Get(hostname string) (*tls.Certificate, error) {
}
// Lookup returns the certificate for the provided scope.
// Lookup also checks for certificates in parent scopes.
// For example, given the scope "example.com/a/b/c", Lookup will first check
// "example.com/a/b/c", then "example.com/a/b", then "example.com/a", and
// finally "example.com" for a certificate. As a result, a certificate with
// scope "example.com" will match all scopes beginning with "example.com".
func (s *Store) Lookup(scope string) (tls.Certificate, bool) {
s.mu.RLock()
defer s.mu.RUnlock()
cert, ok := s.certs[scope]
if !ok {
scope = path.Dir(scope)
for scope != "." {
cert, ok = s.certs[scope]
if ok {
break
}
scope = path.Dir(scope)
}
}
return cert, ok
}
@@ -173,7 +151,7 @@ func (s *Store) createCertificate(scope string) (tls.Certificate, error) {
Subject: pkix.Name{
CommonName: scope,
},
Duration: 250 * 365 * 24 * time.Hour,
Duration: 100 * 365 * 24 * time.Hour,
})
}
@@ -183,7 +161,15 @@ func (s *Store) createCertificate(scope string) (tls.Certificate, error) {
// and private keys named "scope.crt" and "scope.key" respectively,
// where "scope" is the scope of the certificate.
func (s *Store) Load(path string) error {
matches := findCertificates(path)
if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {
return err
}
path = filepath.Clean(path)
matches, err := filepath.Glob(filepath.Join(path, "*.crt"))
if err != nil {
return err
}
for _, crtPath := range matches {
keyPath := strings.TrimSuffix(crtPath, ".crt") + ".key"
cert, err := tls.LoadX509KeyPair(crtPath, keyPath)
@@ -196,20 +182,12 @@ func (s *Store) Load(path string) error {
scope = strings.TrimSuffix(scope, ".crt")
s.Add(scope, cert)
}
s.SetPath(path)
s.mu.Lock()
defer s.mu.Unlock()
s.path = path
return nil
}
func findCertificates(path string) (matches []string) {
filepath.Walk(path, func(path string, _ fs.FileInfo, err error) error {
if filepath.Ext(path) == ".crt" {
matches = append(matches, path)
}
return nil
})
return
}
// Entries returns a map of scopes to certificates.
func (s *Store) Entries() map[string]tls.Certificate {
s.mu.RLock()
@@ -225,5 +203,5 @@ func (s *Store) Entries() map[string]tls.Certificate {
func (s *Store) SetPath(path string) {
s.mu.Lock()
defer s.mu.Unlock()
s.path = path
s.path = filepath.Clean(path)
}

View File

@@ -6,7 +6,6 @@ package main
import (
"bufio"
"bytes"
"context"
"crypto/x509"
"errors"
@@ -64,11 +63,11 @@ func trustCertificate(hostname string, cert *x509.Certificate) error {
knownHost, ok := hosts.Lookup(hostname)
if ok {
// Check fingerprint
if bytes.Equal(knownHost.Fingerprint, host.Fingerprint) {
return nil
}
if knownHost.Fingerprint != host.Fingerprint {
return errors.New("error: fingerprint does not match!")
}
return nil
}
fmt.Printf(trustPrompt, hostname, host.Fingerprint)
scanner.Scan()
@@ -85,7 +84,7 @@ func trustCertificate(hostname string, cert *x509.Certificate) error {
}
}
func getInput(prompt string, sensitive bool) (input string, ok bool) {
func getInput(prompt string) (input string, ok bool) {
fmt.Printf("%s ", prompt)
scanner.Scan()
return scanner.Text(), true
@@ -103,7 +102,7 @@ func do(req *gemini.Request, via []*gemini.Request) (*gemini.Response, error) {
switch resp.Status.Class() {
case gemini.StatusInput:
input, ok := getInput(resp.Meta, resp.Status == gemini.StatusSensitiveInput)
input, ok := getInput(resp.Meta)
if !ok {
break
}

View File

@@ -26,7 +26,7 @@ func main() {
mux.Handle("/", gemini.FileServer(os.DirFS("/var/www")))
server := &gemini.Server{
Handler: LoggingMiddleware(mux),
Handler: gemini.LoggingMiddleware(mux),
ReadTimeout: 30 * time.Second,
WriteTimeout: 1 * time.Minute,
GetCertificate: certificates.Get,
@@ -56,47 +56,3 @@ func main() {
}
}
}
func LoggingMiddleware(h gemini.Handler) gemini.Handler {
return gemini.HandlerFunc(func(ctx context.Context, w gemini.ResponseWriter, r *gemini.Request) {
lw := &logResponseWriter{rw: w}
h.ServeGemini(ctx, lw, r)
host := r.TLS().ServerName
log.Printf("gemini: %s %q %d %d", host, r.URL, lw.Status, lw.Wrote)
})
}
type logResponseWriter struct {
Status gemini.Status
Wrote int
rw gemini.ResponseWriter
mediatype string
wroteHeader bool
}
func (w *logResponseWriter) SetMediaType(mediatype string) {
w.mediatype = mediatype
}
func (w *logResponseWriter) Write(b []byte) (int, error) {
if !w.wroteHeader {
w.WriteHeader(gemini.StatusSuccess, w.mediatype)
}
n, err := w.rw.Write(b)
w.Wrote += n
return n, err
}
func (w *logResponseWriter) WriteHeader(status gemini.Status, meta string) {
if w.wroteHeader {
return
}
w.wroteHeader = true
w.Status = status
w.Wrote += len(meta) + 5
w.rw.WriteHeader(status, meta)
}
func (w *logResponseWriter) Flush() error {
return nil
}

53
middleware.go Normal file
View File

@@ -0,0 +1,53 @@
package gemini
import (
"context"
"log"
)
// LoggingMiddleware returns a handler that wraps h and logs Gemini requests
// and their responses to the log package's standard logger.
// Requests are logged with the format "gemini: {host} {URL} {status code} {bytes written}".
func LoggingMiddleware(h Handler) Handler {
return HandlerFunc(func(ctx context.Context, w ResponseWriter, r *Request) {
lw := &logResponseWriter{rw: w}
h.ServeGemini(ctx, lw, r)
host := r.ServerName()
log.Printf("gemini: %s %q %d %d", host, r.URL, lw.Status, lw.Wrote)
})
}
type logResponseWriter struct {
Status Status
Wrote int
rw ResponseWriter
mediatype string
wroteHeader bool
}
func (w *logResponseWriter) SetMediaType(mediatype string) {
w.mediatype = mediatype
}
func (w *logResponseWriter) Write(b []byte) (int, error) {
if !w.wroteHeader {
w.WriteHeader(StatusSuccess, w.mediatype)
}
n, err := w.rw.Write(b)
w.Wrote += n
return n, err
}
func (w *logResponseWriter) WriteHeader(status Status, meta string) {
if w.wroteHeader {
return
}
w.wroteHeader = true
w.Status = status
w.Wrote += len(meta) + 5
w.rw.WriteHeader(status, meta)
}
func (w *logResponseWriter) Flush() error {
return nil
}

View File

@@ -4,14 +4,14 @@ package tofu
import (
"bufio"
"bytes"
"crypto/sha512"
"crypto/sha256"
"crypto/x509"
"errors"
"encoding/base64"
"fmt"
"io"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
)
@@ -83,7 +83,11 @@ func (k *KnownHosts) WriteTo(w io.Writer) (int64, error) {
// Load loads the known hosts entries from the provided path.
func (k *KnownHosts) Load(path string) error {
f, err := os.Open(path)
if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {
return err
}
f, err := os.OpenFile(path, os.O_CREATE|os.O_RDONLY, 0644)
if err != nil {
return err
}
@@ -132,6 +136,9 @@ func (k *KnownHosts) Parse(r io.Reader) error {
if err != nil {
continue
}
if h.Algorithm != "sha256" {
continue
}
k.hosts[h.Hostname] = h
}
@@ -150,7 +157,7 @@ func (k *KnownHosts) TOFU(hostname string, cert *x509.Certificate) error {
k.Add(host)
return nil
}
if !bytes.Equal(knownHost.Fingerprint, host.Fingerprint) {
if host.Fingerprint != knownHost.Fingerprint {
return fmt.Errorf("fingerprint for %q does not match", hostname)
}
return nil
@@ -267,7 +274,7 @@ func (p *PersistentHosts) TOFU(hostname string, cert *x509.Certificate) error {
if !ok {
return p.Add(host)
}
if !bytes.Equal(knownHost.Fingerprint, host.Fingerprint) {
if host.Fingerprint != knownHost.Fingerprint {
return fmt.Errorf("fingerprint for %q does not match", hostname)
}
return nil
@@ -281,19 +288,19 @@ func (p *PersistentHosts) Close() error {
// Host represents a host entry with a fingerprint using a certain algorithm.
type Host struct {
Hostname string // hostname
Algorithm string // fingerprint algorithm e.g. SHA-512
Fingerprint Fingerprint // fingerprint
Algorithm string // fingerprint algorithm e.g. sha256
Fingerprint string // fingerprint
}
// NewHost returns a new host with a SHA-512 fingerprint of
// NewHost returns a new host with a SHA256 fingerprint of
// the provided raw data.
func NewHost(hostname string, raw []byte) Host {
sum := sha512.Sum512(raw)
sum := sha256.Sum256(raw)
return Host{
Hostname: hostname,
Algorithm: "SHA-512",
Fingerprint: sum[:],
Algorithm: "sha256",
Fingerprint: base64.StdEncoding.EncodeToString(sum[:]),
}
}
@@ -311,86 +318,19 @@ func (h Host) String() string {
b.WriteByte(' ')
b.WriteString(h.Algorithm)
b.WriteByte(' ')
b.WriteString(h.Fingerprint.String())
b.WriteString(h.Fingerprint)
return b.String()
}
// UnmarshalText unmarshals the host from the provided text.
func (h *Host) UnmarshalText(text []byte) error {
const format = "hostname algorithm hex-fingerprint expiry-unix-ts"
parts := bytes.Split(text, []byte(" "))
if len(parts) != 3 {
return fmt.Errorf("expected the format %q", format)
}
if len(parts[0]) == 0 {
return errors.New("empty hostname")
return fmt.Errorf("expected the format 'hostname algorithm fingerprint'")
}
h.Hostname = string(parts[0])
algorithm := string(parts[1])
if algorithm != "SHA-512" {
return fmt.Errorf("unsupported algorithm %q", algorithm)
}
h.Algorithm = algorithm
fingerprint := make([]byte, 0, sha512.Size)
scanner := bufio.NewScanner(bytes.NewReader(parts[2]))
scanner.Split(scanFingerprint)
for scanner.Scan() {
b, err := strconv.ParseUint(scanner.Text(), 16, 8)
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)
}
h.Fingerprint = fingerprint
h.Algorithm = string(parts[1])
h.Fingerprint = string(parts[2])
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
}
// 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()
}