Compare commits
21 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ff6c95930b | ||
|
|
a5712c7705 | ||
|
|
520d0a7fb1 | ||
|
|
bf185e4091 | ||
|
|
8101fbe473 | ||
|
|
b76080c863 | ||
|
|
53390dad6b | ||
|
|
cec1f118fb | ||
|
|
95716296b4 | ||
|
|
1490bf6a75 | ||
|
|
610c6fc533 | ||
|
|
01670647d2 | ||
|
|
5b3194695f | ||
|
|
b6475aa7d9 | ||
|
|
cc372e8768 | ||
|
|
8e442146c3 | ||
|
|
e4dea6f2c8 | ||
|
|
b57ea57fec | ||
|
|
c3fc9a4e9f | ||
|
|
22d57dfc9e | ||
|
|
12bdb2f997 |
76
cert.go
76
cert.go
@@ -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"
|
||||
@@ -26,7 +28,7 @@ type CertificateStore struct {
|
||||
|
||||
// Add adds a certificate for the given scope to the store.
|
||||
// It tries to parse the certificate if it is not already parsed.
|
||||
func (c *CertificateStore) Add(scope string, cert tls.Certificate) {
|
||||
func (c *CertificateStore) Add(scope string, cert tls.Certificate) error {
|
||||
if c.store == nil {
|
||||
c.store = map[string]tls.Certificate{}
|
||||
}
|
||||
@@ -39,27 +41,20 @@ func (c *CertificateStore) Add(scope string, cert tls.Certificate) {
|
||||
}
|
||||
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)
|
||||
return err
|
||||
}
|
||||
}
|
||||
c.store[scope] = cert
|
||||
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 +82,31 @@ func (c *CertificateStore) Load(path string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// CertificateOptions configures how a certificate is created.
|
||||
// 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
|
||||
DNSNames []string
|
||||
Duration time.Duration
|
||||
|
||||
// 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 +124,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)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
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
|
||||
}
|
||||
} 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
|
||||
}
|
||||
public := priv.Public()
|
||||
|
||||
// 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 +165,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
|
||||
}
|
||||
|
||||
49
client.go
49
client.go
@@ -4,6 +4,7 @@ import (
|
||||
"bufio"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"errors"
|
||||
"net"
|
||||
"net/url"
|
||||
"path"
|
||||
@@ -39,8 +40,7 @@ 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
|
||||
@@ -125,9 +125,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 +139,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 {
|
||||
@@ -150,21 +151,19 @@ func (c *Client) do(req *Request, via []*Request) (*Response, error) {
|
||||
if err != nil {
|
||||
return resp, err
|
||||
}
|
||||
|
||||
target = req.URL.ResolveReference(target)
|
||||
redirect, err := NewRequestFromURL(target)
|
||||
if err != nil {
|
||||
return resp, err
|
||||
if target.Scheme != "" && target.Scheme != "gemini" {
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
return c.do(redirect, via)
|
||||
}
|
||||
|
||||
resp.Request = req
|
||||
@@ -180,11 +179,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 {
|
||||
return cert, err
|
||||
}
|
||||
if err == ErrCertificateExpired {
|
||||
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, nil
|
||||
}
|
||||
break
|
||||
}
|
||||
scope = path.Dir(scope)
|
||||
@@ -211,10 +213,10 @@ 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) {
|
||||
@@ -226,7 +228,12 @@ func (c *Client) verifyConnection(req *Request, cs tls.ConnectionState) error {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return ErrCertificateNotTrusted
|
||||
return errors.New("gemini: certificate not trusted")
|
||||
}
|
||||
return err
|
||||
|
||||
fingerprint := NewFingerprint(cert)
|
||||
if knownHost.Hex == fingerprint.Hex {
|
||||
return nil
|
||||
}
|
||||
return errors.New("gemini: fingerprint does not match")
|
||||
}
|
||||
|
||||
@@ -3,9 +3,12 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"git.sr.ht/~adnano/go-gemini"
|
||||
)
|
||||
@@ -44,6 +47,15 @@ func main() {
|
||||
if err := server.Certificates.Load("/var/lib/gemini/certs"); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
server.CreateCertificate = func(hostname string) (tls.Certificate, error) {
|
||||
return gemini.CreateCertificate(gemini.CertificateOptions{
|
||||
Subject: pkix.Name{
|
||||
CommonName: hostname,
|
||||
},
|
||||
DNSNames: []string{hostname},
|
||||
Duration: time.Hour,
|
||||
})
|
||||
}
|
||||
server.Register("localhost", &mux)
|
||||
|
||||
if err := server.ListenAndServe(); err != nil {
|
||||
@@ -51,41 +63,43 @@ func main() {
|
||||
}
|
||||
}
|
||||
|
||||
func getSession(crt *x509.Certificate) (*session, bool) {
|
||||
fingerprint := gemini.Fingerprint(crt)
|
||||
session, ok := sessions[fingerprint]
|
||||
func getSession(cert *x509.Certificate) (*session, bool) {
|
||||
fingerprint := gemini.NewFingerprint(cert)
|
||||
session, ok := sessions[fingerprint.Hex]
|
||||
return session, ok
|
||||
}
|
||||
|
||||
func login(w *gemini.ResponseWriter, r *gemini.Request) {
|
||||
cert, ok := gemini.Certificate(w, r)
|
||||
if !ok {
|
||||
if r.Certificate == nil {
|
||||
w.WriteStatus(gemini.StatusCertificateRequired)
|
||||
return
|
||||
}
|
||||
username, ok := gemini.Input(w, r, "Username")
|
||||
username, ok := gemini.Input(r)
|
||||
if !ok {
|
||||
w.WriteHeader(gemini.StatusInput, "Username")
|
||||
return
|
||||
}
|
||||
fingerprint := gemini.Fingerprint(cert)
|
||||
sessions[fingerprint] = &session{
|
||||
fingerprint := gemini.NewFingerprint(r.Certificate.Leaf)
|
||||
sessions[fingerprint.Hex] = &session{
|
||||
username: username,
|
||||
}
|
||||
w.WriteHeader(gemini.StatusRedirect, "/password")
|
||||
}
|
||||
|
||||
func loginPassword(w *gemini.ResponseWriter, r *gemini.Request) {
|
||||
cert, ok := gemini.Certificate(w, r)
|
||||
if !ok {
|
||||
if r.Certificate == nil {
|
||||
w.WriteStatus(gemini.StatusCertificateRequired)
|
||||
return
|
||||
}
|
||||
session, ok := getSession(cert)
|
||||
session, ok := getSession(r.Certificate.Leaf)
|
||||
if !ok {
|
||||
w.WriteStatus(gemini.StatusCertificateNotAuthorized)
|
||||
return
|
||||
}
|
||||
|
||||
password, ok := gemini.SensitiveInput(w, r, "Password")
|
||||
password, ok := gemini.Input(r)
|
||||
if !ok {
|
||||
w.WriteHeader(gemini.StatusSensitiveInput, "Password")
|
||||
return
|
||||
}
|
||||
expected := logins[session.username].password
|
||||
@@ -93,26 +107,27 @@ func loginPassword(w *gemini.ResponseWriter, r *gemini.Request) {
|
||||
session.authorized = true
|
||||
w.WriteHeader(gemini.StatusRedirect, "/profile")
|
||||
} else {
|
||||
gemini.SensitiveInput(w, r, "Wrong password. Try again")
|
||||
w.WriteHeader(gemini.StatusSensitiveInput, "Password")
|
||||
}
|
||||
}
|
||||
|
||||
func logout(w *gemini.ResponseWriter, r *gemini.Request) {
|
||||
cert, ok := gemini.Certificate(w, r)
|
||||
if !ok {
|
||||
if r.Certificate == nil {
|
||||
w.WriteStatus(gemini.StatusCertificateRequired)
|
||||
return
|
||||
}
|
||||
fingerprint := gemini.Fingerprint(cert)
|
||||
delete(sessions, fingerprint)
|
||||
fingerprint := gemini.NewFingerprint(r.Certificate.Leaf)
|
||||
delete(sessions, fingerprint.Hex)
|
||||
fmt.Fprintln(w, "Successfully logged out.")
|
||||
fmt.Fprintln(w, "=> / Index")
|
||||
}
|
||||
|
||||
func profile(w *gemini.ResponseWriter, r *gemini.Request) {
|
||||
cert, ok := gemini.Certificate(w, r)
|
||||
if !ok {
|
||||
if r.Certificate == nil {
|
||||
w.WriteStatus(gemini.StatusCertificateRequired)
|
||||
return
|
||||
}
|
||||
session, ok := getSession(cert)
|
||||
session, ok := getSession(r.Certificate.Leaf)
|
||||
if !ok {
|
||||
w.WriteStatus(gemini.StatusCertificateNotAuthorized)
|
||||
return
|
||||
@@ -124,11 +139,11 @@ func profile(w *gemini.ResponseWriter, r *gemini.Request) {
|
||||
}
|
||||
|
||||
func admin(w *gemini.ResponseWriter, r *gemini.Request) {
|
||||
cert, ok := gemini.Certificate(w, r)
|
||||
if !ok {
|
||||
if r.Certificate == nil {
|
||||
w.WriteStatus(gemini.StatusCertificateRequired)
|
||||
return
|
||||
}
|
||||
session, ok := getSession(cert)
|
||||
session, ok := getSession(r.Certificate.Leaf)
|
||||
if !ok {
|
||||
w.WriteStatus(gemini.StatusCertificateNotAuthorized)
|
||||
return
|
||||
|
||||
@@ -3,10 +3,7 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/pem"
|
||||
"crypto/x509/pkix"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
@@ -26,6 +23,9 @@ func main() {
|
||||
log.Fatal(err)
|
||||
}
|
||||
options := gemini.CertificateOptions{
|
||||
Subject: pkix.Name{
|
||||
CommonName: host,
|
||||
},
|
||||
DNSNames: []string{host},
|
||||
Duration: duration,
|
||||
}
|
||||
@@ -33,63 +33,9 @@ func main() {
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
if err := writeCertificate(host, cert); err != nil {
|
||||
certPath := host + ".crt"
|
||||
keyPath := host + ".key"
|
||||
if err := gemini.WriteCertificate(cert, certPath, keyPath); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// writeCertificate writes the provided certificate and private key
|
||||
// to path.crt and path.key respectively.
|
||||
func writeCertificate(path string, cert tls.Certificate) error {
|
||||
crt, err := marshalX509Certificate(cert.Leaf.Raw)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
key, err := marshalPrivateKey(cert.PrivateKey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Write the certificate
|
||||
crtPath := path + ".crt"
|
||||
crtOut, err := os.OpenFile(crtPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := crtOut.Write(crt); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Write the private key
|
||||
keyPath := path + ".key"
|
||||
keyOut, err := os.OpenFile(keyPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := keyOut.Write(key); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// marshalX509Certificate returns a PEM-encoded version of the given raw certificate.
|
||||
func marshalX509Certificate(cert []byte) ([]byte, error) {
|
||||
var b bytes.Buffer
|
||||
if err := pem.Encode(&b, &pem.Block{Type: "CERTIFICATE", Bytes: cert}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return b.Bytes(), nil
|
||||
}
|
||||
|
||||
// marshalPrivateKey returns PEM encoded versions of the given certificate and private key.
|
||||
func marshalPrivateKey(priv interface{}) ([]byte, error) {
|
||||
var b bytes.Buffer
|
||||
privBytes, err := x509.MarshalPKCS8PrivateKey(priv)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := pem.Encode(&b, &pem.Block{Type: "PRIVATE KEY", Bytes: privBytes}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return b.Bytes(), nil
|
||||
}
|
||||
|
||||
@@ -30,10 +30,11 @@ var (
|
||||
)
|
||||
|
||||
func init() {
|
||||
client.Timeout = 2 * time.Minute
|
||||
client.Timeout = 30 * time.Second
|
||||
client.KnownHosts.LoadDefault()
|
||||
client.TrustCertificate = func(hostname string, cert *x509.Certificate) gemini.Trust {
|
||||
fmt.Printf(trustPrompt, hostname, gemini.Fingerprint(cert))
|
||||
fingerprint := gemini.NewFingerprint(cert)
|
||||
fmt.Printf(trustPrompt, hostname, fingerprint.Hex)
|
||||
scanner.Scan()
|
||||
switch scanner.Text() {
|
||||
case "t":
|
||||
|
||||
@@ -37,11 +37,10 @@ func textToHTML(text gemini.Text) string {
|
||||
list = false
|
||||
fmt.Fprint(&b, "</ul>\n")
|
||||
}
|
||||
switch l.(type) {
|
||||
switch l := l.(type) {
|
||||
case gemini.LineLink:
|
||||
link := l.(gemini.LineLink)
|
||||
url := html.EscapeString(link.URL)
|
||||
name := html.EscapeString(link.Name)
|
||||
url := html.EscapeString(l.URL)
|
||||
name := html.EscapeString(l.Name)
|
||||
if name == "" {
|
||||
name = url
|
||||
}
|
||||
@@ -54,29 +53,22 @@ func textToHTML(text gemini.Text) string {
|
||||
fmt.Fprint(&b, "</pre>\n")
|
||||
}
|
||||
case gemini.LinePreformattedText:
|
||||
text := string(l.(gemini.LinePreformattedText))
|
||||
fmt.Fprintf(&b, "%s\n", html.EscapeString(text))
|
||||
fmt.Fprintf(&b, "%s\n", html.EscapeString(string(l)))
|
||||
case gemini.LineHeading1:
|
||||
text := string(l.(gemini.LineHeading1))
|
||||
fmt.Fprintf(&b, "<h1>%s</h1>\n", html.EscapeString(text))
|
||||
fmt.Fprintf(&b, "<h1>%s</h1>\n", html.EscapeString(string(l)))
|
||||
case gemini.LineHeading2:
|
||||
text := string(l.(gemini.LineHeading2))
|
||||
fmt.Fprintf(&b, "<h2>%s</h2>\n", html.EscapeString(text))
|
||||
fmt.Fprintf(&b, "<h2>%s</h2>\n", html.EscapeString(string(l)))
|
||||
case gemini.LineHeading3:
|
||||
text := string(l.(gemini.LineHeading3))
|
||||
fmt.Fprintf(&b, "<h3>%s</h3>\n", html.EscapeString(text))
|
||||
fmt.Fprintf(&b, "<h3>%s</h3>\n", html.EscapeString(string(l)))
|
||||
case gemini.LineListItem:
|
||||
text := string(l.(gemini.LineListItem))
|
||||
fmt.Fprintf(&b, "<li>%s</li>\n", html.EscapeString(text))
|
||||
fmt.Fprintf(&b, "<li>%s</li>\n", html.EscapeString(string(l)))
|
||||
case gemini.LineQuote:
|
||||
text := string(l.(gemini.LineQuote))
|
||||
fmt.Fprintf(&b, "<blockquote>%s</blockquote>\n", html.EscapeString(text))
|
||||
fmt.Fprintf(&b, "<blockquote>%s</blockquote>\n", html.EscapeString(string(l)))
|
||||
case gemini.LineText:
|
||||
text := string(l.(gemini.LineText))
|
||||
if text == "" {
|
||||
if l == "" {
|
||||
fmt.Fprint(&b, "<br>\n")
|
||||
} else {
|
||||
fmt.Fprintf(&b, "<p>%s</p>\n", html.EscapeString(text))
|
||||
fmt.Fprintf(&b, "<p>%s</p>\n", html.EscapeString(string(l)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ package main
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"crypto/x509/pkix"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
@@ -12,13 +13,16 @@ import (
|
||||
|
||||
func main() {
|
||||
var server gemini.Server
|
||||
server.ReadTimeout = 1 * time.Minute
|
||||
server.WriteTimeout = 2 * time.Minute
|
||||
server.ReadTimeout = 30 * time.Second
|
||||
server.WriteTimeout = 1 * time.Minute
|
||||
if err := server.Certificates.Load("/var/lib/gemini/certs"); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
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
|
||||
})
|
||||
|
||||
4
fs.go
4
fs.go
@@ -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
|
||||
|
||||
30
gemini.go
30
gemini.go
@@ -9,44 +9,30 @@ var crlf = []byte("\r\n")
|
||||
|
||||
// Errors.
|
||||
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")
|
||||
ErrInvalidURL = errors.New("gemini: invalid URL")
|
||||
ErrInvalidResponse = errors.New("gemini: invalid response")
|
||||
ErrBodyNotAllowed = errors.New("gemini: response body not allowed")
|
||||
)
|
||||
|
||||
// DefaultClient is the default client. It is used by Get and Do.
|
||||
//
|
||||
// On the first request, DefaultClient loads the default list of known hosts.
|
||||
var DefaultClient Client
|
||||
// defaultClient is the default client. It is used by Get and Do.
|
||||
var defaultClient Client
|
||||
|
||||
// Get performs a Gemini request for the given url.
|
||||
//
|
||||
// Get is a wrapper around DefaultClient.Get.
|
||||
func Get(url string) (*Response, error) {
|
||||
setupDefaultClientOnce()
|
||||
return DefaultClient.Get(url)
|
||||
return defaultClient.Get(url)
|
||||
}
|
||||
|
||||
// Do performs a Gemini request and returns a Gemini response.
|
||||
//
|
||||
// Do is a wrapper around DefaultClient.Do.
|
||||
func Do(req *Request) (*Response, error) {
|
||||
setupDefaultClientOnce()
|
||||
return DefaultClient.Do(req)
|
||||
return defaultClient.Do(req)
|
||||
}
|
||||
|
||||
var defaultClientOnce sync.Once
|
||||
|
||||
func setupDefaultClientOnce() {
|
||||
defaultClientOnce.Do(func() {
|
||||
DefaultClient.KnownHosts.LoadDefault()
|
||||
defaultClient.KnownHosts.LoadDefault()
|
||||
})
|
||||
}
|
||||
|
||||
13
request.go
13
request.go
@@ -19,7 +19,9 @@ type Request struct {
|
||||
|
||||
// Certificate specifies the TLS certificate to use for the request.
|
||||
// Request certificates take precedence over client certificates.
|
||||
// This field is ignored by the server.
|
||||
//
|
||||
// On the server side, if the client provided a certificate then
|
||||
// Certificate.Leaf is guaranteed to be non-nil.
|
||||
Certificate *tls.Certificate
|
||||
|
||||
// RemoteAddr allows servers and other software to record the network
|
||||
@@ -39,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"
|
||||
@@ -55,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.
|
||||
|
||||
105
server.go
105
server.go
@@ -3,7 +3,7 @@ package gemini
|
||||
import (
|
||||
"bufio"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"errors"
|
||||
"log"
|
||||
"net"
|
||||
"net/url"
|
||||
@@ -32,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
|
||||
@@ -118,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
|
||||
}
|
||||
@@ -146,22 +151,24 @@ 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.Add(hostname, cert); err != nil {
|
||||
s.logf("gemini: Failed to add 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.
|
||||
@@ -199,10 +206,24 @@ func (s *Server) respond(conn net.Conn) {
|
||||
if url.Scheme == "" {
|
||||
url.Scheme = "gemini"
|
||||
}
|
||||
|
||||
// Store information about the TLS connection
|
||||
connState := conn.(*tls.Conn).ConnectionState()
|
||||
var cert *tls.Certificate
|
||||
if len(connState.PeerCertificates) > 0 {
|
||||
peerCert := connState.PeerCertificates[0]
|
||||
// Store the TLS certificate
|
||||
cert = &tls.Certificate{
|
||||
Certificate: [][]byte{peerCert.Raw},
|
||||
Leaf: peerCert,
|
||||
}
|
||||
}
|
||||
|
||||
req := &Request{
|
||||
URL: url,
|
||||
RemoteAddr: conn.RemoteAddr(),
|
||||
TLS: conn.(*tls.Conn).ConnectionState(),
|
||||
URL: url,
|
||||
RemoteAddr: conn.RemoteAddr(),
|
||||
TLS: connState,
|
||||
Certificate: cert,
|
||||
}
|
||||
resp := s.responder(req)
|
||||
if resp != nil {
|
||||
@@ -228,6 +249,14 @@ 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
|
||||
@@ -304,41 +333,29 @@ type Responder interface {
|
||||
Respond(*ResponseWriter, *Request)
|
||||
}
|
||||
|
||||
// Input returns the request query.
|
||||
// If no input is provided, it responds with StatusInput.
|
||||
func Input(w *ResponseWriter, r *Request, prompt string) (string, bool) {
|
||||
if r.URL.ForceQuery || r.URL.RawQuery != "" {
|
||||
query, err := url.QueryUnescape(r.URL.RawQuery)
|
||||
return query, err == nil
|
||||
}
|
||||
w.WriteHeader(StatusInput, prompt)
|
||||
return "", false
|
||||
}
|
||||
|
||||
// SensitiveInput returns the request query.
|
||||
// If no input is provided, it responds with StatusSensitiveInput.
|
||||
func SensitiveInput(w *ResponseWriter, r *Request, prompt string) (string, bool) {
|
||||
if r.URL.ForceQuery || r.URL.RawQuery != "" {
|
||||
query, err := url.QueryUnescape(r.URL.RawQuery)
|
||||
return query, err == nil
|
||||
}
|
||||
w.WriteHeader(StatusSensitiveInput, prompt)
|
||||
return "", false
|
||||
}
|
||||
|
||||
// Certificate returns the request certificate. If one is not provided,
|
||||
// it returns nil and responds with StatusCertificateRequired.
|
||||
func Certificate(w *ResponseWriter, r *Request) (*x509.Certificate, bool) {
|
||||
if len(r.TLS.PeerCertificates) == 0 {
|
||||
w.WriteStatus(StatusCertificateRequired)
|
||||
return nil, false
|
||||
}
|
||||
return r.TLS.PeerCertificates[0], true
|
||||
}
|
||||
|
||||
// ResponderFunc is a wrapper around a bare function that implements Responder.
|
||||
type ResponderFunc func(*ResponseWriter, *Request)
|
||||
|
||||
func (f ResponderFunc) Respond(w *ResponseWriter, r *Request) {
|
||||
f(w, r)
|
||||
}
|
||||
|
||||
// Input returns the request query.
|
||||
// If the query is invalid or no query is provided, ok will be false.
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// input, ok := gemini.Input(req)
|
||||
// if !ok {
|
||||
// w.WriteHeader(gemini.StatusInput, "Prompt")
|
||||
// return
|
||||
// }
|
||||
// // ...
|
||||
//
|
||||
func Input(r *Request) (query string, ok bool) {
|
||||
if r.URL.ForceQuery || r.URL.RawQuery != "" {
|
||||
query, err := url.QueryUnescape(r.URL.RawQuery)
|
||||
return query, err == nil
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
74
tofu.go
74
tofu.go
@@ -10,7 +10,6 @@ import (
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Trust represents the trustworthiness of a certificate.
|
||||
@@ -25,7 +24,7 @@ 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
|
||||
hosts map[string]Fingerprint
|
||||
file *os.File
|
||||
}
|
||||
|
||||
@@ -80,47 +79,28 @@ func (k *KnownHosts) AddTemporary(hostname string, cert *x509.Certificate) {
|
||||
|
||||
func (k *KnownHosts) add(hostname string, cert *x509.Certificate, write bool) {
|
||||
if k.hosts == nil {
|
||||
k.hosts = map[string]certInfo{}
|
||||
k.hosts = map[string]Fingerprint{}
|
||||
}
|
||||
info := certInfo{
|
||||
Algorithm: "SHA-512",
|
||||
Fingerprint: Fingerprint(cert),
|
||||
Expires: cert.NotAfter.Unix(),
|
||||
}
|
||||
k.hosts[hostname] = info
|
||||
fingerprint := NewFingerprint(cert)
|
||||
k.hosts[hostname] = fingerprint
|
||||
// Append to the file
|
||||
if write && k.file != nil {
|
||||
appendKnownHost(k.file, hostname, info)
|
||||
appendKnownHost(k.file, hostname, fingerprint)
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
// 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
|
||||
}
|
||||
|
||||
// Parse parses the provided reader and adds the parsed known hosts to the list.
|
||||
// Invalid lines 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,15 +116,16 @@ 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{
|
||||
Algorithm: algorithm,
|
||||
Fingerprint: fingerprint,
|
||||
Expires: expires,
|
||||
k.hosts[hostname] = Fingerprint{
|
||||
Algorithm: algorithm,
|
||||
Hex: fingerprint,
|
||||
Expires: expires,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -156,18 +137,19 @@ func (k *KnownHosts) Write(w io.Writer) {
|
||||
}
|
||||
}
|
||||
|
||||
type certInfo 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
|
||||
func appendKnownHost(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)
|
||||
}
|
||||
|
||||
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 represents a fingerprint using a certain algorithm.
|
||||
type Fingerprint struct {
|
||||
Algorithm string // fingerprint algorithm e.g. SHA-512
|
||||
Hex string // fingerprint in hexadecimal, with ':' between each octet
|
||||
Expires int64 // unix time of the fingerprint expiration date
|
||||
}
|
||||
|
||||
// Fingerprint returns the SHA-512 fingerprint of the provided certificate.
|
||||
func Fingerprint(cert *x509.Certificate) string {
|
||||
// NewFingerprint returns the SHA-512 fingerprint of the provided certificate.
|
||||
func NewFingerprint(cert *x509.Certificate) Fingerprint {
|
||||
sum512 := sha512.Sum512(cert.Raw)
|
||||
var b strings.Builder
|
||||
for i, f := range sum512 {
|
||||
@@ -176,7 +158,11 @@ func Fingerprint(cert *x509.Certificate) string {
|
||||
}
|
||||
fmt.Fprintf(&b, "%02X", f)
|
||||
}
|
||||
return b.String()
|
||||
return Fingerprint{
|
||||
Algorithm: "SHA-512",
|
||||
Hex: b.String(),
|
||||
Expires: cert.NotAfter.Unix(),
|
||||
}
|
||||
}
|
||||
|
||||
// defaultKnownHostsPath returns the default known_hosts path.
|
||||
|
||||
Reference in New Issue
Block a user