Compare commits
14 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
611a7d54c0 | ||
|
|
16739d20d0 | ||
|
|
24e488a4cb | ||
|
|
e0ac1685d2 | ||
|
|
82688746dd | ||
|
|
3b9cc7f168 | ||
|
|
3c7940f153 | ||
|
|
8ee55ee009 | ||
|
|
7ee0ea8b7f | ||
|
|
ab1db34f02 | ||
|
|
35e984fbba | ||
|
|
cab23032c0 | ||
|
|
4b653032e4 | ||
|
|
0c75e5d5ad |
39
cert.go
39
cert.go
@@ -18,19 +18,22 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
// CertificateStore maps certificate scopes to certificates.
|
// CertificateDir maps certificate scopes to certificates.
|
||||||
// The zero value of CertificateStore is an empty store ready to use.
|
type CertificateStore map[string]tls.Certificate
|
||||||
type CertificateStore struct {
|
|
||||||
store map[string]tls.Certificate
|
// CertificateDir represents a certificate store optionally loaded from a directory.
|
||||||
dir bool
|
// The zero value of CertificateDir is an empty store ready to use.
|
||||||
path string
|
type CertificateDir struct {
|
||||||
|
CertificateStore
|
||||||
|
dir bool
|
||||||
|
path string
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add adds a certificate for the given scope to the store.
|
// Add adds a certificate for the given scope to the store.
|
||||||
// It tries to parse the certificate if it is not already parsed.
|
// It tries to parse the certificate if it is not already parsed.
|
||||||
func (c *CertificateStore) Add(scope string, cert tls.Certificate) {
|
func (c *CertificateDir) Add(scope string, cert tls.Certificate) {
|
||||||
if c.store == nil {
|
if c.CertificateStore == nil {
|
||||||
c.store = map[string]tls.Certificate{}
|
c.CertificateStore = CertificateStore{}
|
||||||
}
|
}
|
||||||
// Parse certificate if not already parsed
|
// Parse certificate if not already parsed
|
||||||
if cert.Leaf == nil {
|
if cert.Leaf == nil {
|
||||||
@@ -39,12 +42,14 @@ func (c *CertificateStore) Add(scope string, cert tls.Certificate) {
|
|||||||
cert.Leaf = parsed
|
cert.Leaf = parsed
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
c.store[scope] = cert
|
c.CertificateStore[scope] = cert
|
||||||
}
|
}
|
||||||
|
|
||||||
// Write writes the provided certificate to the certificate directory.
|
// Write writes the provided certificate to the certificate directory.
|
||||||
func (c *CertificateStore) Write(scope string, cert tls.Certificate) error {
|
func (c *CertificateDir) Write(scope string, cert tls.Certificate) error {
|
||||||
if c.dir {
|
if c.dir {
|
||||||
|
// Escape slash character
|
||||||
|
scope = strings.ReplaceAll(scope, "/", ":")
|
||||||
certPath := filepath.Join(c.path, scope+".crt")
|
certPath := filepath.Join(c.path, scope+".crt")
|
||||||
keyPath := filepath.Join(c.path, scope+".key")
|
keyPath := filepath.Join(c.path, scope+".key")
|
||||||
if err := WriteCertificate(cert, certPath, keyPath); err != nil {
|
if err := WriteCertificate(cert, certPath, keyPath); err != nil {
|
||||||
@@ -55,8 +60,8 @@ func (c *CertificateStore) Write(scope string, cert tls.Certificate) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Lookup returns the certificate for the given scope.
|
// Lookup returns the certificate for the given scope.
|
||||||
func (c *CertificateStore) Lookup(scope string) (tls.Certificate, bool) {
|
func (c *CertificateDir) Lookup(scope string) (tls.Certificate, bool) {
|
||||||
cert, ok := c.store[scope]
|
cert, ok := c.CertificateStore[scope]
|
||||||
return cert, ok
|
return cert, ok
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -66,7 +71,7 @@ func (c *CertificateStore) Lookup(scope string) (tls.Certificate, bool) {
|
|||||||
// For example, the hostname "localhost" would have the corresponding files
|
// For example, the hostname "localhost" would have the corresponding files
|
||||||
// localhost.crt (certificate) and localhost.key (private key).
|
// localhost.crt (certificate) and localhost.key (private key).
|
||||||
// New certificates will be written to this directory.
|
// New certificates will be written to this directory.
|
||||||
func (c *CertificateStore) Load(path string) error {
|
func (c *CertificateDir) Load(path string) error {
|
||||||
matches, err := filepath.Glob(filepath.Join(path, "*.crt"))
|
matches, err := filepath.Glob(filepath.Join(path, "*.crt"))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -78,6 +83,8 @@ func (c *CertificateStore) Load(path string) error {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
scope := strings.TrimSuffix(filepath.Base(crtPath), ".crt")
|
scope := strings.TrimSuffix(filepath.Base(crtPath), ".crt")
|
||||||
|
// Unescape slash character
|
||||||
|
scope = strings.ReplaceAll(scope, ":", "/")
|
||||||
c.Add(scope, cert)
|
c.Add(scope, cert)
|
||||||
}
|
}
|
||||||
c.dir = true
|
c.dir = true
|
||||||
@@ -85,8 +92,8 @@ func (c *CertificateStore) Load(path string) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetOutput sets the directory that new certificates will be written to.
|
// SetDir sets the directory that new certificates will be written to.
|
||||||
func (c *CertificateStore) SetOutput(path string) {
|
func (c *CertificateDir) SetDir(path string) {
|
||||||
c.dir = true
|
c.dir = true
|
||||||
c.path = path
|
c.path = path
|
||||||
}
|
}
|
||||||
|
|||||||
29
client.go
29
client.go
@@ -9,16 +9,19 @@ import (
|
|||||||
"net/url"
|
"net/url"
|
||||||
"path"
|
"path"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Client is a Gemini client.
|
// Client is a Gemini client.
|
||||||
|
//
|
||||||
|
// Clients are safe for concurrent use by multiple goroutines.
|
||||||
type Client struct {
|
type Client struct {
|
||||||
// KnownHosts is a list of known hosts.
|
// KnownHosts is a list of known hosts.
|
||||||
KnownHosts KnownHosts
|
KnownHosts KnownHostsFile
|
||||||
|
|
||||||
// Certificates stores client-side certificates.
|
// Certificates stores client-side certificates.
|
||||||
Certificates CertificateStore
|
Certificates CertificateDir
|
||||||
|
|
||||||
// Timeout specifies a time limit for requests made by this
|
// Timeout specifies a time limit for requests made by this
|
||||||
// Client. The timeout includes connection time and reading
|
// Client. The timeout includes connection time and reading
|
||||||
@@ -59,6 +62,8 @@ type Client struct {
|
|||||||
// If TrustCertificate returns TrustAlways, the certificate will also be
|
// If TrustCertificate returns TrustAlways, the certificate will also be
|
||||||
// written to the known hosts file.
|
// written to the known hosts file.
|
||||||
TrustCertificate func(hostname string, cert *x509.Certificate) Trust
|
TrustCertificate func(hostname string, cert *x509.Certificate) Trust
|
||||||
|
|
||||||
|
mu sync.Mutex
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get performs a Gemini request for the given url.
|
// Get performs a Gemini request for the given url.
|
||||||
@@ -72,10 +77,20 @@ func (c *Client) Get(url string) (*Response, error) {
|
|||||||
|
|
||||||
// Do performs a Gemini request and returns a Gemini response.
|
// Do performs a Gemini request and returns a Gemini response.
|
||||||
func (c *Client) Do(req *Request) (*Response, error) {
|
func (c *Client) Do(req *Request) (*Response, error) {
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
|
||||||
return c.do(req, nil)
|
return c.do(req, nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) do(req *Request, via []*Request) (*Response, error) {
|
func (c *Client) do(req *Request, via []*Request) (*Response, error) {
|
||||||
|
// Extract hostname
|
||||||
|
colonPos := strings.LastIndex(req.Host, ":")
|
||||||
|
if colonPos == -1 {
|
||||||
|
colonPos = len(req.Host)
|
||||||
|
}
|
||||||
|
hostname := req.Host[:colonPos]
|
||||||
|
|
||||||
// Connect to the host
|
// Connect to the host
|
||||||
config := &tls.Config{
|
config := &tls.Config{
|
||||||
InsecureSkipVerify: true,
|
InsecureSkipVerify: true,
|
||||||
@@ -86,11 +101,13 @@ func (c *Client) do(req *Request, via []*Request) (*Response, error) {
|
|||||||
VerifyConnection: func(cs tls.ConnectionState) error {
|
VerifyConnection: func(cs tls.ConnectionState) error {
|
||||||
return c.verifyConnection(req, cs)
|
return c.verifyConnection(req, cs)
|
||||||
},
|
},
|
||||||
|
ServerName: hostname,
|
||||||
}
|
}
|
||||||
conn, err := tls.Dial("tcp", req.Host, config)
|
netConn, err := (&net.Dialer{}).DialContext(req.Context, "tcp", req.Host)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
conn := tls.Client(netConn, config)
|
||||||
// Set connection deadline
|
// Set connection deadline
|
||||||
if d := c.Timeout; d != 0 {
|
if d := c.Timeout; d != 0 {
|
||||||
conn.SetDeadline(time.Now().Add(d))
|
conn.SetDeadline(time.Now().Add(d))
|
||||||
@@ -126,6 +143,7 @@ func (c *Client) do(req *Request, via []*Request) (*Response, error) {
|
|||||||
return resp, err
|
return resp, err
|
||||||
}
|
}
|
||||||
c.Certificates.Add(hostname+path, cert)
|
c.Certificates.Add(hostname+path, cert)
|
||||||
|
c.Certificates.Write(hostname+path, cert)
|
||||||
req.Certificate = &cert
|
req.Certificate = &cert
|
||||||
return c.do(req, via)
|
return c.do(req, via)
|
||||||
}
|
}
|
||||||
@@ -136,7 +154,7 @@ func (c *Client) do(req *Request, via []*Request) (*Response, error) {
|
|||||||
input, ok := c.GetInput(resp.Meta, resp.Status == StatusSensitiveInput)
|
input, ok := c.GetInput(resp.Meta, resp.Status == StatusSensitiveInput)
|
||||||
if ok {
|
if ok {
|
||||||
req.URL.ForceQuery = true
|
req.URL.ForceQuery = true
|
||||||
req.URL.RawQuery = url.QueryEscape(input)
|
req.URL.RawQuery = QueryEscape(input)
|
||||||
return c.do(req, via)
|
return c.do(req, via)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -155,6 +173,7 @@ func (c *Client) do(req *Request, via []*Request) (*Response, error) {
|
|||||||
target = req.URL.ResolveReference(target)
|
target = req.URL.ResolveReference(target)
|
||||||
|
|
||||||
redirect := NewRequestFromURL(target)
|
redirect := NewRequestFromURL(target)
|
||||||
|
redirect.Context = req.Context
|
||||||
if c.CheckRedirect != nil {
|
if c.CheckRedirect != nil {
|
||||||
if err := c.CheckRedirect(redirect, via); err != nil {
|
if err := c.CheckRedirect(redirect, via); err != nil {
|
||||||
return resp, err
|
return resp, err
|
||||||
@@ -212,7 +231,7 @@ func (c *Client) verifyConnection(req *Request, cs tls.ConnectionState) error {
|
|||||||
|
|
||||||
// Check the known hosts
|
// Check the known hosts
|
||||||
knownHost, ok := c.KnownHosts.Lookup(hostname)
|
knownHost, ok := c.KnownHosts.Lookup(hostname)
|
||||||
if !ok || time.Now().Unix() >= knownHost.Expires {
|
if !ok || !time.Now().Before(knownHost.Expires) {
|
||||||
// See if the client trusts the certificate
|
// See if the client trusts the certificate
|
||||||
if c.TrustCertificate != nil {
|
if c.TrustCertificate != nil {
|
||||||
switch c.TrustCertificate(hostname, cert) {
|
switch c.TrustCertificate(hostname, cert) {
|
||||||
|
|||||||
119
examples/auth.go
119
examples/auth.go
@@ -3,6 +3,7 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"crypto/sha512"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"crypto/x509"
|
"crypto/x509"
|
||||||
"crypto/x509/pkix"
|
"crypto/x509/pkix"
|
||||||
@@ -13,35 +14,19 @@ import (
|
|||||||
"git.sr.ht/~adnano/go-gemini"
|
"git.sr.ht/~adnano/go-gemini"
|
||||||
)
|
)
|
||||||
|
|
||||||
type user struct {
|
type User struct {
|
||||||
password string // TODO: use hashes
|
Name string
|
||||||
admin bool
|
|
||||||
}
|
|
||||||
|
|
||||||
type session struct {
|
|
||||||
username string
|
|
||||||
authorized bool // whether or not the password was supplied
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var (
|
var (
|
||||||
// Map of usernames to user data
|
// Map of certificate hashes to users
|
||||||
logins = map[string]user{
|
users = map[string]*User{}
|
||||||
"admin": {"p@ssw0rd", true}, // NOTE: These are bad passwords!
|
|
||||||
"user1": {"password1", false},
|
|
||||||
"user2": {"password2", false},
|
|
||||||
}
|
|
||||||
|
|
||||||
// Map of certificate fingerprints to sessions
|
|
||||||
sessions = map[string]*session{}
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
var mux gemini.ServeMux
|
var mux gemini.ServeMux
|
||||||
mux.HandleFunc("/", login)
|
mux.HandleFunc("/", profile)
|
||||||
mux.HandleFunc("/password", loginPassword)
|
mux.HandleFunc("/username", changeUsername)
|
||||||
mux.HandleFunc("/profile", profile)
|
|
||||||
mux.HandleFunc("/admin", admin)
|
|
||||||
mux.HandleFunc("/logout", logout)
|
|
||||||
|
|
||||||
var server gemini.Server
|
var server gemini.Server
|
||||||
if err := server.Certificates.Load("/var/lib/gemini/certs"); err != nil {
|
if err := server.Certificates.Load("/var/lib/gemini/certs"); err != nil {
|
||||||
@@ -63,65 +48,9 @@ func main() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func getSession(cert *x509.Certificate) (*session, bool) {
|
func fingerprint(cert *x509.Certificate) string {
|
||||||
fingerprint := gemini.NewFingerprint(cert.Raw, cert.NotAfter)
|
b := sha512.Sum512(cert.Raw)
|
||||||
session, ok := sessions[fingerprint.Hex]
|
return string(b[:])
|
||||||
return session, ok
|
|
||||||
}
|
|
||||||
|
|
||||||
func login(w *gemini.ResponseWriter, r *gemini.Request) {
|
|
||||||
if r.Certificate == nil {
|
|
||||||
w.WriteStatus(gemini.StatusCertificateRequired)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
username, ok := gemini.Input(r)
|
|
||||||
if !ok {
|
|
||||||
w.WriteHeader(gemini.StatusInput, "Username")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
cert := r.Certificate.Leaf
|
|
||||||
fingerprint := gemini.NewFingerprint(cert.Raw, cert.NotAfter)
|
|
||||||
sessions[fingerprint.Hex] = &session{
|
|
||||||
username: username,
|
|
||||||
}
|
|
||||||
w.WriteHeader(gemini.StatusRedirect, "/password")
|
|
||||||
}
|
|
||||||
|
|
||||||
func loginPassword(w *gemini.ResponseWriter, r *gemini.Request) {
|
|
||||||
if r.Certificate == nil {
|
|
||||||
w.WriteStatus(gemini.StatusCertificateRequired)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
session, ok := getSession(r.Certificate.Leaf)
|
|
||||||
if !ok {
|
|
||||||
w.WriteStatus(gemini.StatusCertificateNotAuthorized)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
password, ok := gemini.Input(r)
|
|
||||||
if !ok {
|
|
||||||
w.WriteHeader(gemini.StatusSensitiveInput, "Password")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
expected := logins[session.username].password
|
|
||||||
if password == expected {
|
|
||||||
session.authorized = true
|
|
||||||
w.WriteHeader(gemini.StatusRedirect, "/profile")
|
|
||||||
} else {
|
|
||||||
w.WriteHeader(gemini.StatusSensitiveInput, "Password")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func logout(w *gemini.ResponseWriter, r *gemini.Request) {
|
|
||||||
if r.Certificate == nil {
|
|
||||||
w.WriteStatus(gemini.StatusCertificateRequired)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
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) {
|
func profile(w *gemini.ResponseWriter, r *gemini.Request) {
|
||||||
@@ -129,31 +58,27 @@ func profile(w *gemini.ResponseWriter, r *gemini.Request) {
|
|||||||
w.WriteStatus(gemini.StatusCertificateRequired)
|
w.WriteStatus(gemini.StatusCertificateRequired)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
session, ok := getSession(r.Certificate.Leaf)
|
fingerprint := fingerprint(r.Certificate.Leaf)
|
||||||
|
user, ok := users[fingerprint]
|
||||||
if !ok {
|
if !ok {
|
||||||
w.WriteStatus(gemini.StatusCertificateNotAuthorized)
|
user = &User{}
|
||||||
return
|
users[fingerprint] = user
|
||||||
}
|
}
|
||||||
user := logins[session.username]
|
fmt.Fprintln(w, "Username:", user.Name)
|
||||||
fmt.Fprintln(w, "Username:", session.username)
|
fmt.Fprintln(w, "=> /username Change username")
|
||||||
fmt.Fprintln(w, "Admin:", user.admin)
|
|
||||||
fmt.Fprintln(w, "=> /logout Logout")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func admin(w *gemini.ResponseWriter, r *gemini.Request) {
|
func changeUsername(w *gemini.ResponseWriter, r *gemini.Request) {
|
||||||
if r.Certificate == nil {
|
if r.Certificate == nil {
|
||||||
w.WriteStatus(gemini.StatusCertificateRequired)
|
w.WriteStatus(gemini.StatusCertificateRequired)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
session, ok := getSession(r.Certificate.Leaf)
|
|
||||||
|
username, ok := gemini.Input(r)
|
||||||
if !ok {
|
if !ok {
|
||||||
w.WriteStatus(gemini.StatusCertificateNotAuthorized)
|
w.WriteHeader(gemini.StatusInput, "Username")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
user := logins[session.username]
|
users[fingerprint(r.Certificate.Leaf)].Name = username
|
||||||
if !user.admin {
|
w.WriteHeader(gemini.StatusRedirect, "/")
|
||||||
w.WriteStatus(gemini.StatusCertificateNotAuthorized)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
fmt.Fprintln(w, "Welcome to the admin portal.")
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ func main() {
|
|||||||
CommonName: hostname,
|
CommonName: hostname,
|
||||||
},
|
},
|
||||||
DNSNames: []string{hostname},
|
DNSNames: []string{hostname},
|
||||||
Duration: time.Minute, // for testing purposes
|
Duration: 365 * 24 * time.Hour,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
17
query.go
Normal file
17
query.go
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
package gemini
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// QueryEscape properly escapes a string for use in a Gemini URL query.
|
||||||
|
// It is like url.PathEscape except that it also replaces plus signs with their percent-encoded counterpart.
|
||||||
|
func QueryEscape(query string) string {
|
||||||
|
return strings.ReplaceAll(url.PathEscape(query), "+", "%2B")
|
||||||
|
}
|
||||||
|
|
||||||
|
// QueryUnescape is identical to url.PathUnescape.
|
||||||
|
func QueryUnescape(query string) (string, error) {
|
||||||
|
return url.PathUnescape(query)
|
||||||
|
}
|
||||||
13
request.go
13
request.go
@@ -2,6 +2,7 @@ package gemini
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bufio"
|
"bufio"
|
||||||
|
"context"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"net"
|
"net"
|
||||||
"net/url"
|
"net/url"
|
||||||
@@ -33,6 +34,10 @@ type Request struct {
|
|||||||
// connection on which the request was received.
|
// connection on which the request was received.
|
||||||
// This field is ignored by the client.
|
// This field is ignored by the client.
|
||||||
TLS tls.ConnectionState
|
TLS tls.ConnectionState
|
||||||
|
|
||||||
|
// Context specifies the context to use for client requests.
|
||||||
|
// Context must not be nil.
|
||||||
|
Context context.Context
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewRequest returns a new request. The host is inferred from the URL.
|
// NewRequest returns a new request. The host is inferred from the URL.
|
||||||
@@ -46,14 +51,18 @@ func NewRequest(rawurl string) (*Request, error) {
|
|||||||
|
|
||||||
// NewRequestFromURL returns a new request for the given URL.
|
// NewRequestFromURL returns a new request for the given URL.
|
||||||
// The host is inferred from the URL.
|
// The host is inferred from the URL.
|
||||||
|
//
|
||||||
|
// Callers should be careful that the URL query is properly escaped.
|
||||||
|
// See the documentation for QueryEscape for more information.
|
||||||
func NewRequestFromURL(url *url.URL) *Request {
|
func NewRequestFromURL(url *url.URL) *Request {
|
||||||
host := url.Host
|
host := url.Host
|
||||||
if url.Port() == "" {
|
if url.Port() == "" {
|
||||||
host += ":1965"
|
host += ":1965"
|
||||||
}
|
}
|
||||||
return &Request{
|
return &Request{
|
||||||
URL: url,
|
URL: url,
|
||||||
Host: host,
|
Host: host,
|
||||||
|
Context: context.Background(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ type Server struct {
|
|||||||
WriteTimeout time.Duration
|
WriteTimeout time.Duration
|
||||||
|
|
||||||
// Certificates contains the certificates used by the server.
|
// Certificates contains the certificates used by the server.
|
||||||
Certificates CertificateStore
|
Certificates CertificateDir
|
||||||
|
|
||||||
// CreateCertificate, if not nil, will be called to create a new certificate
|
// CreateCertificate, if not nil, will be called to create a new certificate
|
||||||
// if the current one is expired or missing.
|
// if the current one is expired or missing.
|
||||||
@@ -203,11 +203,6 @@ func (s *Server) respond(conn net.Conn) {
|
|||||||
// Note that we return an error status if User is specified in the URL
|
// Note that we return an error status if User is specified in the URL
|
||||||
w.WriteStatus(StatusBadRequest)
|
w.WriteStatus(StatusBadRequest)
|
||||||
} else {
|
} else {
|
||||||
// If no scheme is specified, assume a default scheme of gemini://
|
|
||||||
if url.Scheme == "" {
|
|
||||||
url.Scheme = "gemini"
|
|
||||||
}
|
|
||||||
|
|
||||||
// Store information about the TLS connection
|
// Store information about the TLS connection
|
||||||
connState := conn.(*tls.Conn).ConnectionState()
|
connState := conn.(*tls.Conn).ConnectionState()
|
||||||
var cert *tls.Certificate
|
var cert *tls.Certificate
|
||||||
|
|||||||
62
tofu.go
62
tofu.go
@@ -20,43 +20,46 @@ const (
|
|||||||
TrustAlways // The certificate is trusted always.
|
TrustAlways // The certificate is trusted always.
|
||||||
)
|
)
|
||||||
|
|
||||||
// KnownHosts represents a list of known hosts.
|
// KnownHosts maps hosts to fingerprints.
|
||||||
// The zero value for KnownHosts is an empty list ready to use.
|
type KnownHosts map[string]Fingerprint
|
||||||
type KnownHosts struct {
|
|
||||||
hosts map[string]Fingerprint
|
// KnownHostsFile represents a list of known hosts optionally loaded from a file.
|
||||||
out io.Writer
|
// The zero value for KnownHostsFile represents an empty list ready to use.
|
||||||
|
type KnownHostsFile struct {
|
||||||
|
KnownHosts
|
||||||
|
out io.Writer
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetOutput sets the output to which new known hosts will be written to.
|
// SetOutput sets the output to which new known hosts will be written to.
|
||||||
func (k *KnownHosts) SetOutput(w io.Writer) {
|
func (k *KnownHostsFile) SetOutput(w io.Writer) {
|
||||||
k.out = w
|
k.out = w
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add adds a known host to the list of known hosts.
|
// Add adds a known host to the list of known hosts.
|
||||||
func (k *KnownHosts) Add(hostname string, fingerprint Fingerprint) {
|
func (k *KnownHostsFile) Add(hostname string, fingerprint Fingerprint) {
|
||||||
if k.hosts == nil {
|
if k.KnownHosts == nil {
|
||||||
k.hosts = map[string]Fingerprint{}
|
k.KnownHosts = KnownHosts{}
|
||||||
}
|
}
|
||||||
k.hosts[hostname] = fingerprint
|
k.KnownHosts[hostname] = fingerprint
|
||||||
}
|
}
|
||||||
|
|
||||||
// Lookup returns the fingerprint of the certificate corresponding to
|
// Lookup returns the fingerprint of the certificate corresponding to
|
||||||
// the given hostname.
|
// the given hostname.
|
||||||
func (k *KnownHosts) Lookup(hostname string) (Fingerprint, bool) {
|
func (k *KnownHostsFile) Lookup(hostname string) (Fingerprint, bool) {
|
||||||
c, ok := k.hosts[hostname]
|
c, ok := k.KnownHosts[hostname]
|
||||||
return c, ok
|
return c, ok
|
||||||
}
|
}
|
||||||
|
|
||||||
// Write writes a known hosts entry to the configured output.
|
// Write writes a known hosts entry to the configured output.
|
||||||
func (k *KnownHosts) Write(hostname string, fingerprint Fingerprint) {
|
func (k *KnownHostsFile) Write(hostname string, fingerprint Fingerprint) {
|
||||||
if k.out != nil {
|
if k.out != nil {
|
||||||
k.writeKnownHost(k.out, hostname, fingerprint)
|
k.writeKnownHost(k.out, hostname, fingerprint)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// WriteAll writes all of the known hosts to the provided io.Writer.
|
// WriteAll writes all of the known hosts to the provided io.Writer.
|
||||||
func (k *KnownHosts) WriteAll(w io.Writer) error {
|
func (k *KnownHostsFile) WriteAll(w io.Writer) error {
|
||||||
for h, c := range k.hosts {
|
for h, c := range k.KnownHosts {
|
||||||
if _, err := k.writeKnownHost(w, h, c); err != nil {
|
if _, err := k.writeKnownHost(w, h, c); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -65,14 +68,14 @@ func (k *KnownHosts) WriteAll(w io.Writer) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// writeKnownHost writes a known host to the provided io.Writer.
|
// writeKnownHost writes a known host to the provided io.Writer.
|
||||||
func (k *KnownHosts) writeKnownHost(w io.Writer, hostname string, f Fingerprint) (int, error) {
|
func (k *KnownHostsFile) 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)
|
return fmt.Fprintf(w, "%s %s %s %d\n", hostname, f.Algorithm, f.Hex, f.Expires.Unix())
|
||||||
}
|
}
|
||||||
|
|
||||||
// Load loads the known hosts from the provided path.
|
// Load loads the known hosts from the provided path.
|
||||||
// It creates the file if it does not exist.
|
// It creates the file if it does not exist.
|
||||||
// New known hosts will be appended to the file.
|
// New known hosts will be appended to the file.
|
||||||
func (k *KnownHosts) Load(path string) error {
|
func (k *KnownHostsFile) Load(path string) error {
|
||||||
f, err := os.OpenFile(path, os.O_CREATE|os.O_RDONLY, 0644)
|
f, err := os.OpenFile(path, os.O_CREATE|os.O_RDONLY, 0644)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -90,9 +93,9 @@ func (k *KnownHosts) Load(path string) error {
|
|||||||
|
|
||||||
// Parse parses the provided reader and adds the parsed known hosts to the list.
|
// Parse parses the provided reader and adds the parsed known hosts to the list.
|
||||||
// Invalid entries are ignored.
|
// Invalid entries are ignored.
|
||||||
func (k *KnownHosts) Parse(r io.Reader) {
|
func (k *KnownHostsFile) Parse(r io.Reader) {
|
||||||
if k.hosts == nil {
|
if k.KnownHosts == nil {
|
||||||
k.hosts = map[string]Fingerprint{}
|
k.KnownHosts = map[string]Fingerprint{}
|
||||||
}
|
}
|
||||||
scanner := bufio.NewScanner(r)
|
scanner := bufio.NewScanner(r)
|
||||||
for scanner.Scan() {
|
for scanner.Scan() {
|
||||||
@@ -107,16 +110,17 @@ func (k *KnownHosts) Parse(r io.Reader) {
|
|||||||
if algorithm != "SHA-512" {
|
if algorithm != "SHA-512" {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
fingerprint := parts[2]
|
hex := parts[2]
|
||||||
|
|
||||||
expires, err := strconv.ParseInt(parts[3], 10, 0)
|
unix, err := strconv.ParseInt(parts[3], 10, 0)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
expires := time.Unix(unix, 0)
|
||||||
|
|
||||||
k.hosts[hostname] = Fingerprint{
|
k.KnownHosts[hostname] = Fingerprint{
|
||||||
Algorithm: algorithm,
|
Algorithm: algorithm,
|
||||||
Hex: fingerprint,
|
Hex: hex,
|
||||||
Expires: expires,
|
Expires: expires,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -124,9 +128,9 @@ func (k *KnownHosts) Parse(r io.Reader) {
|
|||||||
|
|
||||||
// Fingerprint represents a fingerprint using a certain algorithm.
|
// Fingerprint represents a fingerprint using a certain algorithm.
|
||||||
type Fingerprint struct {
|
type Fingerprint struct {
|
||||||
Algorithm string // fingerprint algorithm e.g. SHA-512
|
Algorithm string // fingerprint algorithm e.g. SHA-512
|
||||||
Hex string // fingerprint in hexadecimal, with ':' between each octet
|
Hex string // fingerprint in hexadecimal, with ':' between each octet
|
||||||
Expires int64 // unix time of the fingerprint expiration date
|
Expires time.Time // unix time of the fingerprint expiration date
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewFingerprint returns the SHA-512 fingerprint of the provided raw data.
|
// NewFingerprint returns the SHA-512 fingerprint of the provided raw data.
|
||||||
@@ -142,6 +146,6 @@ func NewFingerprint(raw []byte, expires time.Time) Fingerprint {
|
|||||||
return Fingerprint{
|
return Fingerprint{
|
||||||
Algorithm: "SHA-512",
|
Algorithm: "SHA-512",
|
||||||
Hex: b.String(),
|
Hex: b.String(),
|
||||||
Expires: expires.Unix(),
|
Expires: expires,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user