23 Commits

Author SHA1 Message Date
Adnan Maolood
f6b0443a62 Update KnownHosts documentation 2020-11-09 13:57:30 -05:00
Adnan Maolood
3dee6dcff3 Add (*CertificateStore).Write function 2020-11-09 13:54:15 -05:00
Adnan Maolood
85f8e84bd5 Rename (*ResponseWriter).SetMimetype to SetMediaType 2020-11-09 13:44:42 -05:00
Adnan Maolood
9338681256 Add (*KnownHosts).SetOutput function 2020-11-09 12:26:08 -05:00
Adnan Maolood
f2a1510375 Move documentation to gemini.go 2020-11-09 12:07:49 -05:00
Adnan Maolood
46cbcfcaa4 Remove top-level Get and Do functions 2020-11-09 12:04:53 -05:00
Adnan Maolood
76dfe257f1 Remove (*KnownHosts).LoadDefault function 2020-11-09 09:28:44 -05:00
Adnan Maolood
5332dc6280 Don't guarantee that (*Response).Body is always non-nil 2020-11-08 18:38:08 -05:00
Adnan Maolood
6b3cf1314b Fix relative redirects 2020-11-07 23:43:07 -05:00
Adnan Maolood
fe92db1e9c Allow redirects to non-gemini schemes 2020-11-06 11:18:58 -05:00
Adnan Maolood
ff6c95930b Fix TOFU 2020-11-05 22:30:13 -05:00
Adnan Maolood
a5712c7705 Don't check if certificate is expired 2020-11-05 18:35:25 -05:00
Adnan Maolood
520d0a7fb1 Don't redirect by default 2020-11-05 15:44:01 -05:00
Adnan Maolood
bf185e4091 update examples/cert.go 2020-11-05 15:38:41 -05:00
Adnan Maolood
8101fbe473 Update examples/auth.go 2020-11-05 15:37:46 -05:00
Adnan Maolood
b76080c863 Refactor KnownHosts 2020-11-05 15:27:12 -05:00
Adnan Maolood
53390dad6b Document CertificateOptions 2020-11-05 00:04:58 -05:00
Adnan Maolood
cec1f118fb Remove some unnecessary errors 2020-11-04 23:46:05 -05:00
Adnan Maolood
95716296b4 Use ECDSA keys by default 2020-11-03 19:43:04 -05:00
Adnan Maolood
1490bf6a75 Update examples/auth.go 2020-11-03 16:29:39 -05:00
Adnan Maolood
610c6fc533 Add ErrorLog field to Server 2020-11-03 16:11:31 -05:00
Adnan Maolood
01670647d2 Add Subject option in CertificateOptions 2020-11-02 23:11:46 -05:00
Adnan Maolood
5b3194695f Store request certificate to prevent infinite loop 2020-11-02 13:47:07 -05:00
13 changed files with 280 additions and 307 deletions

89
cert.go
View File

@@ -2,12 +2,14 @@ package gemini
import (
"crypto"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"log"
"math/big"
"net"
"os"
@@ -37,29 +39,25 @@ func (c *CertificateStore) Add(scope string, cert tls.Certificate) {
cert.Leaf = parsed
}
}
if c.dir {
// Write certificates
log.Printf("gemini: Writing certificate for %s to %s", scope, c.path)
certPath := filepath.Join(c.path, scope+".crt")
keyPath := filepath.Join(c.path, scope+".key")
if err := WriteCertificate(cert, certPath, keyPath); err != nil {
log.Printf("gemini: Failed to write certificate for %s: %s", scope, err)
}
}
c.store[scope] = cert
}
// Write writes the provided certificate to the certificate directory.
func (c *CertificateStore) Write(scope string, cert tls.Certificate) error {
if c.dir {
certPath := filepath.Join(c.path, scope+".crt")
keyPath := filepath.Join(c.path, scope+".key")
if err := WriteCertificate(cert, certPath, keyPath); err != nil {
return err
}
}
return nil
}
// Lookup returns the certificate for the given scope.
func (c *CertificateStore) Lookup(scope string) (*tls.Certificate, error) {
func (c *CertificateStore) Lookup(scope string) (tls.Certificate, bool) {
cert, ok := c.store[scope]
if !ok {
return nil, ErrCertificateNotFound
}
// Ensure that the certificate is not expired
if cert.Leaf != nil && cert.Leaf.NotAfter.Before(time.Now()) {
return &cert, ErrCertificateExpired
}
return &cert, nil
return cert, ok
}
// Load loads certificates from the given path.
@@ -87,11 +85,37 @@ func (c *CertificateStore) Load(path string) error {
return nil
}
// CertificateOptions configures how a certificate is created.
// SetOutput sets the directory that new certificates will be written to.
func (c *CertificateStore) SetOutput(path string) {
c.dir = true
c.path = path
}
// CertificateOptions configures the creation of a certificate.
type CertificateOptions struct {
// Subject Alternate Name values.
// Should contain the IP addresses that the certificate is valid for.
IPAddresses []net.IP
// Subject Alternate Name values.
// Should contain the DNS names that this certificate is valid for.
// E.g. example.com, *.example.com
DNSNames []string
// Subject specifies the certificate Subject.
//
// Subject.CommonName can contain the DNS name that this certificate
// is valid for. Server certificates should specify both a Subject
// and a Subject Alternate Name.
Subject pkix.Name
// Duration specifies the amount of time that the certificate is valid for.
Duration time.Duration
// Ed25519 specifies whether to generate an Ed25519 key pair.
// If false, an ECDSA key will be generated instead.
// Ed25519 is not as widely supported as ECDSA.
Ed25519 bool
}
// CreateCertificate creates a new TLS certificate.
@@ -109,15 +133,27 @@ func CreateCertificate(options CertificateOptions) (tls.Certificate, error) {
// newX509KeyPair creates and returns a new certificate and private key.
func newX509KeyPair(options CertificateOptions) (*x509.Certificate, crypto.PrivateKey, error) {
// Generate an ED25519 private key
_, priv, err := ed25519.GenerateKey(rand.Reader)
var pub crypto.PublicKey
var priv crypto.PrivateKey
if options.Ed25519 {
// Generate an Ed25519 private key
var err error
pub, priv, err = ed25519.GenerateKey(rand.Reader)
if err != nil {
return nil, nil, err
}
public := priv.Public()
} else {
// Generate an ECDSA private key
private, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return nil, nil, err
}
priv = private
pub = &private.PublicKey
}
// ED25519 keys should have the DigitalSignature KeyUsage bits set
// in the x509.Certificate template
// ECDSA and Ed25519 keys should have the DigitalSignature KeyUsage bits
// set in the x509.Certificate template
keyUsage := x509.KeyUsageDigitalSignature
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
@@ -138,9 +174,10 @@ func newX509KeyPair(options CertificateOptions) (*x509.Certificate, crypto.Priva
BasicConstraintsValid: true,
IPAddresses: options.IPAddresses,
DNSNames: options.DNSNames,
Subject: options.Subject,
}
crt, err := x509.CreateCertificate(rand.Reader, &template, &template, public, priv)
crt, err := x509.CreateCertificate(rand.Reader, &template, &template, pub, priv)
if err != nil {
return nil, nil, err
}

View File

@@ -4,6 +4,7 @@ import (
"bufio"
"crypto/tls"
"crypto/x509"
"errors"
"net"
"net/url"
"path"
@@ -39,15 +40,14 @@ type Client struct {
GetInput func(prompt string, sensitive bool) (input string, ok bool)
// CheckRedirect determines whether to follow a redirect.
// If CheckRedirect is nil, a default policy of no more than 5 consecutive
// redirects will be enforced.
// If CheckRedirect is nil, redirects will not be followed.
CheckRedirect func(req *Request, via []*Request) error
// CreateCertificate is called to generate a certificate upon
// the request of a server.
// If CreateCertificate is nil or the returned error is not nil,
// the request will not be sent again and the response will be returned.
CreateCertificate func(hostname, path string) (tls.Certificate, error)
CreateCertificate func(scope, path string) (tls.Certificate, error)
// TrustCertificate is called to determine whether the client
// should trust a certificate it has not seen before.
@@ -108,6 +108,7 @@ func (c *Client) do(req *Request, via []*Request) (*Response, error) {
if err := resp.read(conn); err != nil {
return nil, err
}
resp.Request = req
// Store connection state
resp.TLS = conn.ConnectionState()
@@ -125,9 +126,10 @@ func (c *Client) do(req *Request, via []*Request) (*Response, error) {
return resp, err
}
c.Certificates.Add(hostname+path, cert)
req.Certificate = &cert
return c.do(req, via)
}
return resp, ErrCertificateRequired
return resp, nil
case resp.Status.Class() == StatusClassInput:
if c.GetInput != nil {
@@ -138,7 +140,7 @@ func (c *Client) do(req *Request, via []*Request) (*Response, error) {
return c.do(req, via)
}
}
return resp, ErrInputRequired
return resp, nil
case resp.Status.Class() == StatusClassRedirect:
if via == nil {
@@ -151,23 +153,16 @@ func (c *Client) do(req *Request, via []*Request) (*Response, error) {
return resp, err
}
target = req.URL.ResolveReference(target)
redirect, err := NewRequestFromURL(target)
if err != nil {
return resp, err
}
redirect := NewRequestFromURL(target)
if c.CheckRedirect != nil {
if err := c.CheckRedirect(redirect, via); err != nil {
return resp, err
}
} else if len(via) > 5 {
// Default policy of no more than 5 redirects
return resp, ErrTooManyRedirects
}
return c.do(redirect, via)
}
}
resp.Request = req
return resp, nil
}
@@ -180,13 +175,14 @@ func (c *Client) getClientCertificate(req *Request) (*tls.Certificate, error) {
// Search recursively for the certificate
scope := req.URL.Hostname() + strings.TrimSuffix(req.URL.Path, "/")
for {
cert, err := c.Certificates.Lookup(scope)
if err == nil {
cert, ok := c.Certificates.Lookup(scope)
if ok {
// Ensure that the certificate is not expired
if cert.Leaf != nil && !time.Now().After(cert.Leaf.NotAfter) {
// Store the certificate
req.Certificate = cert
return cert, err
req.Certificate = &cert
return &cert, nil
}
if err == ErrCertificateExpired {
break
}
scope = path.Dir(scope)
@@ -213,22 +209,30 @@ func (c *Client) verifyConnection(req *Request, cs tls.ConnectionState) error {
if c.InsecureSkipTrust {
return nil
}
// Check the known hosts
err := c.KnownHosts.Lookup(hostname, cert)
switch err {
case ErrCertificateExpired, ErrCertificateNotFound:
knownHost, ok := c.KnownHosts.Lookup(hostname)
if !ok || time.Now().Unix() >= knownHost.Expires {
// See if the client trusts the certificate
if c.TrustCertificate != nil {
switch c.TrustCertificate(hostname, cert) {
case TrustOnce:
c.KnownHosts.AddTemporary(hostname, cert)
fingerprint := NewFingerprint(cert.Raw, cert.NotAfter)
c.KnownHosts.Add(hostname, fingerprint)
return nil
case TrustAlways:
c.KnownHosts.Add(hostname, cert)
fingerprint := NewFingerprint(cert.Raw, cert.NotAfter)
c.KnownHosts.Add(hostname, fingerprint)
c.KnownHosts.Write(hostname, fingerprint)
return nil
}
}
return ErrCertificateNotTrusted
return errors.New("gemini: certificate not trusted")
}
return err
fingerprint := NewFingerprint(cert.Raw, cert.NotAfter)
if knownHost.Hex == fingerprint.Hex {
return nil
}
return errors.New("gemini: fingerprint does not match")
}

55
doc.go
View File

@@ -1,55 +0,0 @@
/*
Package gemini implements the Gemini protocol.
Get makes a Gemini request:
resp, err := gemini.Get("gemini://example.com")
if err != nil {
// handle error
}
defer resp.Body.Close()
// ...
For control over client behavior, create a Client:
client := &gemini.Client{}
resp, err := client.Get("gemini://example.com")
if err != nil {
// handle error
}
// ...
Server is a Gemini server.
server := &gemini.Server{
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
}
Servers should be configured with certificates:
err := server.Certificates.Load("/var/lib/gemini/certs")
if err != nil {
// handle error
}
Servers can accept requests for multiple hosts and schemes:
server.RegisterFunc("example.com", func(w *gemini.ResponseWriter, r *gemini.Request) {
fmt.Fprint(w, "Welcome to example.com")
})
server.RegisterFunc("example.org", func(w *gemini.ResponseWriter, r *gemini.Request) {
fmt.Fprint(w, "Welcome to example.org")
})
server.RegisterFunc("http://example.net", func(w *gemini.ResponseWriter, r *gemini.Request) {
fmt.Fprint(w, "Proxied content from http://example.net")
})
To start the server, call ListenAndServe:
err := server.ListenAndServe()
if err != nil {
// handle error
}
*/
package gemini

View File

@@ -5,6 +5,7 @@ package main
import (
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"fmt"
"log"
"time"
@@ -48,6 +49,9 @@ func main() {
}
server.CreateCertificate = func(hostname string) (tls.Certificate, error) {
return gemini.CreateCertificate(gemini.CertificateOptions{
Subject: pkix.Name{
CommonName: hostname,
},
DNSNames: []string{hostname},
Duration: time.Hour,
})
@@ -60,8 +64,8 @@ func main() {
}
func getSession(cert *x509.Certificate) (*session, bool) {
fingerprint := gemini.Fingerprint(cert)
session, ok := sessions[fingerprint]
fingerprint := gemini.NewFingerprint(cert.Raw, cert.NotAfter)
session, ok := sessions[fingerprint.Hex]
return session, ok
}
@@ -75,8 +79,9 @@ func login(w *gemini.ResponseWriter, r *gemini.Request) {
w.WriteHeader(gemini.StatusInput, "Username")
return
}
fingerprint := gemini.Fingerprint(r.Certificate.Leaf)
sessions[fingerprint] = &session{
cert := r.Certificate.Leaf
fingerprint := gemini.NewFingerprint(cert.Raw, cert.NotAfter)
sessions[fingerprint.Hex] = &session{
username: username,
}
w.WriteHeader(gemini.StatusRedirect, "/password")
@@ -103,7 +108,7 @@ func loginPassword(w *gemini.ResponseWriter, r *gemini.Request) {
session.authorized = true
w.WriteHeader(gemini.StatusRedirect, "/profile")
} else {
w.WriteHeader(gemini.StatusSensitiveInput, "Wrong password. Try again")
w.WriteHeader(gemini.StatusSensitiveInput, "Password")
}
}
@@ -112,9 +117,11 @@ func logout(w *gemini.ResponseWriter, r *gemini.Request) {
w.WriteStatus(gemini.StatusCertificateRequired)
return
}
fingerprint := gemini.Fingerprint(r.Certificate.Leaf)
delete(sessions, fingerprint)
cert := r.Certificate.Leaf
fingerprint := gemini.NewFingerprint(cert.Raw, cert.NotAfter)
delete(sessions, fingerprint.Hex)
fmt.Fprintln(w, "Successfully logged out.")
fmt.Fprintln(w, "=> / Index")
}
func profile(w *gemini.ResponseWriter, r *gemini.Request) {

View File

@@ -3,6 +3,7 @@
package main
import (
"crypto/x509/pkix"
"fmt"
"log"
"os"
@@ -22,6 +23,9 @@ func main() {
log.Fatal(err)
}
options := gemini.CertificateOptions{
Subject: pkix.Name{
CommonName: host,
},
DNSNames: []string{host},
Duration: duration,
}

View File

@@ -10,9 +10,11 @@ import (
"io/ioutil"
"log"
"os"
"path/filepath"
"time"
"git.sr.ht/~adnano/go-gemini"
"git.sr.ht/~adnano/go-xdg"
)
const trustPrompt = `The certificate offered by %s is of unknown trust. Its fingerprint is:
@@ -31,9 +33,10 @@ var (
func init() {
client.Timeout = 30 * time.Second
client.KnownHosts.LoadDefault()
client.KnownHosts.Load(filepath.Join(xdg.DataHome(), "gemini", "known_hosts"))
client.TrustCertificate = func(hostname string, cert *x509.Certificate) gemini.Trust {
fmt.Printf(trustPrompt, hostname, gemini.Fingerprint(cert))
fingerprint := gemini.NewFingerprint(cert.Raw, cert.NotAfter)
fmt.Printf(trustPrompt, hostname, fingerprint.Hex)
scanner.Scan()
switch scanner.Text() {
case "t":
@@ -79,9 +82,9 @@ func main() {
fmt.Println(err)
os.Exit(1)
}
defer resp.Body.Close()
if resp.Status.Class() == gemini.StatusClassSuccess {
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)

View File

@@ -4,6 +4,7 @@ package main
import (
"crypto/tls"
"crypto/x509/pkix"
"log"
"time"
@@ -19,6 +20,9 @@ func main() {
}
server.CreateCertificate = func(hostname string) (tls.Certificate, error) {
return gemini.CreateCertificate(gemini.CertificateOptions{
Subject: pkix.Name{
CommonName: hostname,
},
DNSNames: []string{hostname},
Duration: time.Minute, // for testing purposes
})

8
fs.go
View File

@@ -33,7 +33,7 @@ func (fsh fsHandler) Respond(w *ResponseWriter, r *Request) {
// Detect mimetype
ext := path.Ext(p)
mimetype := mime.TypeByExtension(ext)
w.SetMimetype(mimetype)
w.SetMediaType(mimetype)
// Copy file to response writer
io.Copy(w, f)
}
@@ -72,7 +72,7 @@ func ServeFile(w *ResponseWriter, fs FS, name string) {
// Detect mimetype
ext := path.Ext(name)
mimetype := mime.TypeByExtension(ext)
w.SetMimetype(mimetype)
w.SetMediaType(mimetype)
// Copy file to response writer
io.Copy(w, f)
}
@@ -96,9 +96,9 @@ func openFile(p string) (File, error) {
if stat.Mode().IsRegular() {
return f, nil
}
return nil, ErrNotAFile
return nil, os.ErrNotExist
} else if !stat.Mode().IsRegular() {
return nil, ErrNotAFile
return nil, os.ErrNotExist
}
}
return f, nil

View File

@@ -1,8 +1,56 @@
/*
Package gemini implements the Gemini protocol.
Client is a Gemini client.
client := &gemini.Client{}
resp, err := client.Get("gemini://example.com")
if err != nil {
// handle error
}
if resp.Status.Class() == gemini.StatusClassSucess {
defer resp.Body.Close()
// ...
}
// ...
Server is a Gemini server.
server := &gemini.Server{
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
}
Servers should be configured with certificates:
err := server.Certificates.Load("/var/lib/gemini/certs")
if err != nil {
// handle error
}
Servers can accept requests for multiple hosts and schemes:
server.RegisterFunc("example.com", func(w *gemini.ResponseWriter, r *gemini.Request) {
fmt.Fprint(w, "Welcome to example.com")
})
server.RegisterFunc("example.org", func(w *gemini.ResponseWriter, r *gemini.Request) {
fmt.Fprint(w, "Welcome to example.org")
})
server.RegisterFunc("http://example.net", func(w *gemini.ResponseWriter, r *gemini.Request) {
fmt.Fprint(w, "Proxied content from http://example.net")
})
To start the server, call ListenAndServe:
err := server.ListenAndServe()
if err != nil {
// handle error
}
*/
package gemini
import (
"errors"
"sync"
)
var crlf = []byte("\r\n")
@@ -11,36 +59,5 @@ var crlf = []byte("\r\n")
var (
ErrInvalidURL = errors.New("gemini: invalid URL")
ErrInvalidResponse = errors.New("gemini: invalid response")
ErrCertificateExpired = errors.New("gemini: certificate expired")
ErrCertificateNotFound = errors.New("gemini: certificate not found")
ErrCertificateNotTrusted = errors.New("gemini: certificate not trusted")
ErrCertificateRequired = errors.New("gemini: certificate required")
ErrNotAFile = errors.New("gemini: not a file")
ErrNotAGeminiURL = errors.New("gemini: not a Gemini URL")
ErrBodyNotAllowed = errors.New("gemini: response status code does not allow for body")
ErrTooManyRedirects = errors.New("gemini: too many redirects")
ErrInputRequired = errors.New("gemini: input required")
ErrBodyNotAllowed = errors.New("gemini: response body not allowed")
)
// defaultClient is the default client. It is used by Get and Do.
var defaultClient Client
// Get performs a Gemini request for the given url.
func Get(url string) (*Response, error) {
setupDefaultClientOnce()
return defaultClient.Get(url)
}
// Do performs a Gemini request and returns a Gemini response.
func Do(req *Request) (*Response, error) {
setupDefaultClientOnce()
return defaultClient.Do(req)
}
var defaultClientOnce sync.Once
func setupDefaultClientOnce() {
defaultClientOnce.Do(func() {
defaultClient.KnownHosts.LoadDefault()
})
}

View File

@@ -41,15 +41,12 @@ func NewRequest(rawurl string) (*Request, error) {
if err != nil {
return nil, err
}
return NewRequestFromURL(u)
return NewRequestFromURL(u), nil
}
// NewRequestFromURL returns a new request for the given URL.
// The host is inferred from the URL.
func NewRequestFromURL(url *url.URL) (*Request, error) {
if url.Scheme != "" && url.Scheme != "gemini" {
return nil, ErrNotAGeminiURL
}
func NewRequestFromURL(url *url.URL) *Request {
host := url.Host
if url.Port() == "" {
host += ":1965"
@@ -57,7 +54,7 @@ func NewRequestFromURL(url *url.URL) (*Request, error) {
return &Request{
URL: url,
Host: host,
}, nil
}
}
// write writes the Gemini request to the provided buffered writer.

View File

@@ -2,10 +2,8 @@ package gemini
import (
"bufio"
"bytes"
"crypto/tls"
"io"
"io/ioutil"
"strconv"
)
@@ -21,7 +19,6 @@ type Response struct {
Meta string
// Body contains the response body for successful responses.
// Body is guaranteed to be non-nil.
Body io.ReadCloser
// Request is the request that was sent to obtain this response.
@@ -86,8 +83,6 @@ func (resp *Response) read(rc io.ReadCloser) error {
if resp.Status.Class() == StatusClassSuccess {
resp.Body = newReadCloserBody(br, rc)
} else {
resp.Body = ioutil.NopCloser(bytes.NewReader([]byte{}))
}
return nil
}

View File

@@ -3,6 +3,7 @@ package gemini
import (
"bufio"
"crypto/tls"
"errors"
"log"
"net"
"net/url"
@@ -31,6 +32,11 @@ type Server struct {
// if the current one is expired or missing.
CreateCertificate func(hostname string) (tls.Certificate, error)
// ErrorLog specifies an optional logger for errors accepting connections
// and file system errors.
// If nil, logging is done via the log package's standard logger.
ErrorLog *log.Logger
// registered responders
responders map[responderKey]Responder
hosts map[string]bool
@@ -117,7 +123,7 @@ func (s *Server) Serve(l net.Listener) error {
if max := 1 * time.Second; tempDelay > max {
tempDelay = max
}
log.Printf("gemini: Accept error: %v; retrying in %v", err, tempDelay)
s.logf("gemini: Accept error: %v; retrying in %v", err, tempDelay)
time.Sleep(tempDelay)
continue
}
@@ -145,22 +151,25 @@ func (s *Server) getCertificate(h *tls.ClientHelloInfo) (*tls.Certificate, error
func (s *Server) getCertificateFor(hostname string) (*tls.Certificate, error) {
if _, ok := s.hosts[hostname]; !ok {
return nil, ErrCertificateNotFound
return nil, errors.New("hostname not registered")
}
cert, err := s.Certificates.Lookup(hostname)
switch err {
case ErrCertificateNotFound, ErrCertificateExpired:
// Generate a new certificate if it is missing or expired
cert, ok := s.Certificates.Lookup(hostname)
if !ok || cert.Leaf != nil && cert.Leaf.NotAfter.Before(time.Now()) {
if s.CreateCertificate != nil {
cert, err := s.CreateCertificate(hostname)
if err == nil {
s.Certificates.Add(hostname, cert)
if err := s.Certificates.Write(hostname, cert); err != nil {
s.logf("gemini: Failed to write new certificate for %s: %s", hostname, err)
}
}
return &cert, err
}
return nil, errors.New("no certificate")
}
return cert, err
return &cert, nil
}
// respond responds to a connection.
@@ -241,12 +250,20 @@ func (s *Server) responder(r *Request) Responder {
return nil
}
func (s *Server) logf(format string, args ...interface{}) {
if s.ErrorLog != nil {
s.ErrorLog.Printf(format, args...)
} else {
log.Printf(format, args...)
}
}
// ResponseWriter is used by a Gemini handler to construct a Gemini response.
type ResponseWriter struct {
b *bufio.Writer
bodyAllowed bool
wroteHeader bool
mimetype string
mediatype string
}
func newResponseWriter(conn net.Conn) *ResponseWriter {
@@ -285,10 +302,10 @@ func (w *ResponseWriter) WriteStatus(status Status) {
w.WriteHeader(status, status.Message())
}
// SetMimetype sets the mimetype that will be written for a successful response.
// SetMediaType sets the media type that will be written for a successful response.
// If the mimetype is not set, it will default to "text/gemini".
func (w *ResponseWriter) SetMimetype(mimetype string) {
w.mimetype = mimetype
func (w *ResponseWriter) SetMediaType(mediatype string) {
w.mediatype = mediatype
}
// Write writes the response body.
@@ -299,11 +316,11 @@ func (w *ResponseWriter) SetMimetype(mimetype string) {
// with StatusSuccess and the mimetype set in SetMimetype.
func (w *ResponseWriter) Write(b []byte) (int, error) {
if !w.wroteHeader {
mimetype := w.mimetype
if mimetype == "" {
mimetype = "text/gemini"
mediatype := w.mediatype
if mediatype == "" {
mediatype = "text/gemini"
}
w.WriteHeader(StatusSuccess, mimetype)
w.WriteHeader(StatusSuccess, mediatype)
}
if !w.bodyAllowed {
return 0, ErrBodyNotAllowed

175
tofu.go
View File

@@ -3,11 +3,9 @@ package gemini
import (
"bufio"
"crypto/sha512"
"crypto/x509"
"fmt"
"io"
"os"
"path/filepath"
"strconv"
"strings"
"time"
@@ -25,32 +23,56 @@ const (
// KnownHosts represents a list of known hosts.
// The zero value for KnownHosts is an empty list ready to use.
type KnownHosts struct {
hosts map[string]certInfo
file *os.File
hosts map[string]Fingerprint
out io.Writer
}
// LoadDefault loads the known hosts from the default known hosts path, which is
// $XDG_DATA_HOME/gemini/known_hosts.
// It creates the path and any of its parent directories if they do not exist.
// KnownHosts will append to the file whenever a certificate is added.
func (k *KnownHosts) LoadDefault() error {
path, err := defaultKnownHostsPath()
if err != nil {
// SetOutput sets the output to which new known hosts will be written to.
func (k *KnownHosts) SetOutput(w io.Writer) {
k.out = w
}
// Add adds a known host to the list of known hosts.
func (k *KnownHosts) Add(hostname string, fingerprint Fingerprint) {
if k.hosts == nil {
k.hosts = map[string]Fingerprint{}
}
k.hosts[hostname] = fingerprint
}
// Lookup returns the fingerprint of the certificate corresponding to
// the given hostname.
func (k *KnownHosts) Lookup(hostname string) (Fingerprint, bool) {
c, ok := k.hosts[hostname]
return c, ok
}
// Write writes a known hosts entry to the configured output.
func (k *KnownHosts) Write(hostname string, fingerprint Fingerprint) {
if k.out != nil {
k.writeKnownHost(k.out, hostname, fingerprint)
}
}
// WriteAll writes all of the known hosts to the provided io.Writer.
func (k *KnownHosts) WriteAll(w io.Writer) error {
for h, c := range k.hosts {
if _, err := k.writeKnownHost(w, h, c); err != nil {
return err
}
return k.Load(path)
}
return nil
}
// writeKnownHost writes a known host to the provided io.Writer.
func (k *KnownHosts) writeKnownHost(w io.Writer, hostname string, f Fingerprint) (int, error) {
return fmt.Fprintf(w, "%s %s %s %d\n", hostname, f.Algorithm, f.Hex, f.Expires)
}
// Load loads the known hosts from the provided path.
// It creates the path and any of its parent directories if they do not exist.
// KnownHosts will append to the file whenever a certificate is added.
// It creates the file if it does not exist.
// New known hosts will be appended to the file.
func (k *KnownHosts) Load(path string) error {
if dir := filepath.Dir(path); dir != "." {
err := os.MkdirAll(dir, 0755)
if err != nil {
return err
}
}
f, err := os.OpenFile(path, os.O_CREATE|os.O_RDONLY, 0644)
if err != nil {
return err
@@ -62,65 +84,15 @@ func (k *KnownHosts) Load(path string) error {
if err != nil {
return err
}
k.file = f
k.out = f
return nil
}
// Add adds a certificate to the list of known hosts.
// If KnownHosts was loaded from a file, Add will append to the file.
func (k *KnownHosts) Add(hostname string, cert *x509.Certificate) {
k.add(hostname, cert, true)
}
// AddTemporary adds a certificate to the list of known hosts
// without writing it to the known hosts file.
func (k *KnownHosts) AddTemporary(hostname string, cert *x509.Certificate) {
k.add(hostname, cert, false)
}
func (k *KnownHosts) add(hostname string, cert *x509.Certificate, write bool) {
if k.hosts == nil {
k.hosts = map[string]certInfo{}
}
info := certInfo{
Algorithm: "SHA-512",
Fingerprint: Fingerprint(cert),
Expires: cert.NotAfter.Unix(),
}
k.hosts[hostname] = info
// Append to the file
if write && k.file != nil {
appendKnownHost(k.file, hostname, info)
}
}
// Lookup looks for the provided certificate in the list of known hosts.
// If the hostname is not in the list, Lookup returns ErrCertificateNotFound.
// If the fingerprint doesn't match, Lookup returns ErrCertificateNotTrusted.
// Otherwise, Lookup returns nil.
func (k *KnownHosts) Lookup(hostname string, cert *x509.Certificate) error {
now := time.Now().Unix()
fingerprint := Fingerprint(cert)
if c, ok := k.hosts[hostname]; ok {
if c.Expires <= now {
// Certificate is expired
return ErrCertificateExpired
}
if c.Fingerprint != fingerprint {
// Fingerprint does not match
return ErrCertificateNotTrusted
}
// Certificate is found
return nil
}
return ErrCertificateNotFound
}
// Parse parses the provided reader and adds the parsed known hosts to the list.
// Invalid lines are ignored.
// Invalid entries are ignored.
func (k *KnownHosts) Parse(r io.Reader) {
if k.hosts == nil {
k.hosts = map[string]certInfo{}
k.hosts = map[string]Fingerprint{}
}
scanner := bufio.NewScanner(r)
for scanner.Scan() {
@@ -136,39 +108,30 @@ func (k *KnownHosts) Parse(r io.Reader) {
continue
}
fingerprint := parts[2]
expires, err := strconv.ParseInt(parts[3], 10, 0)
if err != nil {
continue
}
k.hosts[hostname] = certInfo{
k.hosts[hostname] = Fingerprint{
Algorithm: algorithm,
Fingerprint: fingerprint,
Hex: fingerprint,
Expires: expires,
}
}
}
// Write writes the known hosts to the provided io.Writer.
func (k *KnownHosts) Write(w io.Writer) {
for h, c := range k.hosts {
appendKnownHost(w, h, c)
}
}
type certInfo struct {
// Fingerprint represents a fingerprint using a certain algorithm.
type Fingerprint struct {
Algorithm string // fingerprint algorithm e.g. SHA-512
Fingerprint string // fingerprint in hexadecimal, with ':' between each octet
Expires int64 // unix time of certificate notAfter date
Hex string // fingerprint in hexadecimal, with ':' between each octet
Expires int64 // unix time of the fingerprint expiration date
}
func appendKnownHost(w io.Writer, hostname string, c certInfo) (int, error) {
return fmt.Fprintf(w, "%s %s %s %d\n", hostname, c.Algorithm, c.Fingerprint, c.Expires)
}
// Fingerprint returns the SHA-512 fingerprint of the provided certificate.
func Fingerprint(cert *x509.Certificate) string {
sum512 := sha512.Sum512(cert.Raw)
// NewFingerprint returns the SHA-512 fingerprint of the provided raw data.
func NewFingerprint(raw []byte, expires time.Time) Fingerprint {
sum512 := sha512.Sum512(raw)
var b strings.Builder
for i, f := range sum512 {
if i > 0 {
@@ -176,29 +139,9 @@ func Fingerprint(cert *x509.Certificate) string {
}
fmt.Fprintf(&b, "%02X", f)
}
return b.String()
}
// defaultKnownHostsPath returns the default known_hosts path.
// The default path is $XDG_DATA_HOME/gemini/known_hosts
func defaultKnownHostsPath() (string, error) {
dataDir, err := userDataDir()
if err != nil {
return "", err
return Fingerprint{
Algorithm: "SHA-512",
Hex: b.String(),
Expires: expires.Unix(),
}
return filepath.Join(dataDir, "gemini", "known_hosts"), nil
}
// userDataDir returns the user data directory.
func userDataDir() (string, error) {
dataDir, ok := os.LookupEnv("XDG_DATA_HOME")
if ok {
return dataDir, nil
}
home, err := os.UserHomeDir()
if err != nil {
return "", err
}
return filepath.Join(home, ".local", "share"), nil
}