Compare commits
15 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2144e2c2f2 | ||
|
|
93a606b591 | ||
|
|
b00794f236 | ||
|
|
3da7fe7cee | ||
|
|
dea7600f29 | ||
|
|
7d958a4798 | ||
|
|
a5493b708a | ||
|
|
6e5c2473e7 | ||
|
|
c639233ea1 | ||
|
|
5677440876 | ||
|
|
be3d09d7f4 | ||
|
|
504da9afd8 | ||
|
|
d1cb8967b6 | ||
|
|
107b3a1785 | ||
|
|
e7a06a12bf |
@@ -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)
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@ package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/x509"
|
||||
"errors"
|
||||
@@ -64,10 +63,10 @@ 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 errors.New("error: fingerprint does not match!")
|
||||
return nil
|
||||
}
|
||||
|
||||
fmt.Printf(trustPrompt, hostname, host.Fingerprint)
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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
53
middleware.go
Normal 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
|
||||
}
|
||||
108
tofu/tofu.go
108
tofu/tofu.go
@@ -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
|
||||
@@ -280,20 +287,20 @@ 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
|
||||
Hostname string // hostname
|
||||
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()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user