14 Commits

Author SHA1 Message Date
Adnan Maolood
611a7d54c0 Revert to using hexadecimal to encode fingerprints 2020-12-16 23:58:02 -05:00
Adnan Maolood
16739d20d0 Fix escaping of queries 2020-11-27 22:27:52 -05:00
Adnan Maolood
24e488a4cb examples/server: Increase certificate duration 2020-11-27 17:54:26 -05:00
Adnan Maolood
e0ac1685d2 Fix server name in TLS connections 2020-11-27 17:45:15 -05:00
Adnan Maolood
82688746dd Add context to requests 2020-11-26 00:42:25 -05:00
Adnan Maolood
3b9cc7f168 Update examples/auth.go 2020-11-25 19:10:01 -05:00
Adnan Maolood
3c7940f153 Fix known hosts expiration timestamps 2020-11-25 14:24:49 -05:00
Adnan Maolood
8ee55ee009 Fix certificate fingerprint check 2020-11-25 14:20:31 -05:00
Adnan Maolood
7ee0ea8b7f Use base64 to encode fingerprints 2020-11-25 14:16:51 -05:00
Adnan Maolood
ab1db34f02 Fix client locking up on redirects 2020-11-24 21:49:24 -05:00
Adnan Maolood
35e984fbba Escape path character in certificate scopes 2020-11-24 20:24:38 -05:00
Adnan Maolood
cab23032c0 Don't assume a default scheme of gemini 2020-11-24 17:13:52 -05:00
Adnan Maolood
4b653032e4 Make Client safe for concurrent use 2020-11-24 16:28:58 -05:00
Adnan Maolood
0c75e5d5ad Expose KnownHosts and CertificateStore internals 2020-11-23 12:17:54 -05:00
8 changed files with 132 additions and 156 deletions

35
cert.go
View File

@@ -18,19 +18,22 @@ import (
"time"
)
// CertificateStore maps certificate scopes to certificates.
// The zero value of CertificateStore is an empty store ready to use.
type CertificateStore struct {
store map[string]tls.Certificate
// CertificateDir maps certificate scopes to certificates.
type CertificateStore map[string]tls.Certificate
// CertificateDir represents a certificate store optionally loaded from a directory.
// The zero value of CertificateDir is an empty store ready to use.
type CertificateDir struct {
CertificateStore
dir bool
path string
}
// 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) {
if c.store == nil {
c.store = map[string]tls.Certificate{}
func (c *CertificateDir) Add(scope string, cert tls.Certificate) {
if c.CertificateStore == nil {
c.CertificateStore = CertificateStore{}
}
// Parse certificate if not already parsed
if cert.Leaf == nil {
@@ -39,12 +42,14 @@ func (c *CertificateStore) Add(scope string, cert tls.Certificate) {
cert.Leaf = parsed
}
}
c.store[scope] = cert
c.CertificateStore[scope] = cert
}
// 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 {
// Escape slash character
scope = strings.ReplaceAll(scope, "/", ":")
certPath := filepath.Join(c.path, scope+".crt")
keyPath := filepath.Join(c.path, scope+".key")
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.
func (c *CertificateStore) Lookup(scope string) (tls.Certificate, bool) {
cert, ok := c.store[scope]
func (c *CertificateDir) Lookup(scope string) (tls.Certificate, bool) {
cert, ok := c.CertificateStore[scope]
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
// localhost.crt (certificate) and localhost.key (private key).
// 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"))
if err != nil {
return err
@@ -78,6 +83,8 @@ func (c *CertificateStore) Load(path string) error {
continue
}
scope := strings.TrimSuffix(filepath.Base(crtPath), ".crt")
// Unescape slash character
scope = strings.ReplaceAll(scope, ":", "/")
c.Add(scope, cert)
}
c.dir = true
@@ -85,8 +92,8 @@ func (c *CertificateStore) Load(path string) error {
return nil
}
// SetOutput sets the directory that new certificates will be written to.
func (c *CertificateStore) SetOutput(path string) {
// SetDir sets the directory that new certificates will be written to.
func (c *CertificateDir) SetDir(path string) {
c.dir = true
c.path = path
}

View File

@@ -9,16 +9,19 @@ import (
"net/url"
"path"
"strings"
"sync"
"time"
)
// Client is a Gemini client.
//
// Clients are safe for concurrent use by multiple goroutines.
type Client struct {
// KnownHosts is a list of known hosts.
KnownHosts KnownHosts
KnownHosts KnownHostsFile
// Certificates stores client-side certificates.
Certificates CertificateStore
Certificates CertificateDir
// Timeout specifies a time limit for requests made by this
// Client. The timeout includes connection time and reading
@@ -59,6 +62,8 @@ type Client struct {
// If TrustCertificate returns TrustAlways, the certificate will also be
// written to the known hosts file.
TrustCertificate func(hostname string, cert *x509.Certificate) Trust
mu sync.Mutex
}
// 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.
func (c *Client) Do(req *Request) (*Response, error) {
c.mu.Lock()
defer c.mu.Unlock()
return c.do(req, nil)
}
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
config := &tls.Config{
InsecureSkipVerify: true,
@@ -86,11 +101,13 @@ func (c *Client) do(req *Request, via []*Request) (*Response, error) {
VerifyConnection: func(cs tls.ConnectionState) error {
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 {
return nil, err
}
conn := tls.Client(netConn, config)
// Set connection deadline
if d := c.Timeout; d != 0 {
conn.SetDeadline(time.Now().Add(d))
@@ -126,6 +143,7 @@ func (c *Client) do(req *Request, via []*Request) (*Response, error) {
return resp, err
}
c.Certificates.Add(hostname+path, cert)
c.Certificates.Write(hostname+path, cert)
req.Certificate = &cert
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)
if ok {
req.URL.ForceQuery = true
req.URL.RawQuery = url.QueryEscape(input)
req.URL.RawQuery = QueryEscape(input)
return c.do(req, via)
}
}
@@ -155,6 +173,7 @@ func (c *Client) do(req *Request, via []*Request) (*Response, error) {
target = req.URL.ResolveReference(target)
redirect := NewRequestFromURL(target)
redirect.Context = req.Context
if c.CheckRedirect != nil {
if err := c.CheckRedirect(redirect, via); err != nil {
return resp, err
@@ -212,7 +231,7 @@ func (c *Client) verifyConnection(req *Request, cs tls.ConnectionState) error {
// Check the known hosts
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
if c.TrustCertificate != nil {
switch c.TrustCertificate(hostname, cert) {

View File

@@ -3,6 +3,7 @@
package main
import (
"crypto/sha512"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
@@ -13,35 +14,19 @@ import (
"git.sr.ht/~adnano/go-gemini"
)
type user struct {
password string // TODO: use hashes
admin bool
}
type session struct {
username string
authorized bool // whether or not the password was supplied
type User struct {
Name string
}
var (
// Map of usernames to user data
logins = 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{}
// Map of certificate hashes to users
users = map[string]*User{}
)
func main() {
var mux gemini.ServeMux
mux.HandleFunc("/", login)
mux.HandleFunc("/password", loginPassword)
mux.HandleFunc("/profile", profile)
mux.HandleFunc("/admin", admin)
mux.HandleFunc("/logout", logout)
mux.HandleFunc("/", profile)
mux.HandleFunc("/username", changeUsername)
var server gemini.Server
if err := server.Certificates.Load("/var/lib/gemini/certs"); err != nil {
@@ -63,65 +48,9 @@ func main() {
}
}
func getSession(cert *x509.Certificate) (*session, bool) {
fingerprint := gemini.NewFingerprint(cert.Raw, cert.NotAfter)
session, ok := sessions[fingerprint.Hex]
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 fingerprint(cert *x509.Certificate) string {
b := sha512.Sum512(cert.Raw)
return string(b[:])
}
func profile(w *gemini.ResponseWriter, r *gemini.Request) {
@@ -129,31 +58,27 @@ func profile(w *gemini.ResponseWriter, r *gemini.Request) {
w.WriteStatus(gemini.StatusCertificateRequired)
return
}
session, ok := getSession(r.Certificate.Leaf)
fingerprint := fingerprint(r.Certificate.Leaf)
user, ok := users[fingerprint]
if !ok {
w.WriteStatus(gemini.StatusCertificateNotAuthorized)
return
user = &User{}
users[fingerprint] = user
}
user := logins[session.username]
fmt.Fprintln(w, "Username:", session.username)
fmt.Fprintln(w, "Admin:", user.admin)
fmt.Fprintln(w, "=> /logout Logout")
fmt.Fprintln(w, "Username:", user.Name)
fmt.Fprintln(w, "=> /username Change username")
}
func admin(w *gemini.ResponseWriter, r *gemini.Request) {
func changeUsername(w *gemini.ResponseWriter, r *gemini.Request) {
if r.Certificate == nil {
w.WriteStatus(gemini.StatusCertificateRequired)
return
}
session, ok := getSession(r.Certificate.Leaf)
username, ok := gemini.Input(r)
if !ok {
w.WriteStatus(gemini.StatusCertificateNotAuthorized)
w.WriteHeader(gemini.StatusInput, "Username")
return
}
user := logins[session.username]
if !user.admin {
w.WriteStatus(gemini.StatusCertificateNotAuthorized)
return
}
fmt.Fprintln(w, "Welcome to the admin portal.")
users[fingerprint(r.Certificate.Leaf)].Name = username
w.WriteHeader(gemini.StatusRedirect, "/")
}

View File

@@ -24,7 +24,7 @@ func main() {
CommonName: hostname,
},
DNSNames: []string{hostname},
Duration: time.Minute, // for testing purposes
Duration: 365 * 24 * time.Hour,
})
}

17
query.go Normal file
View 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)
}

View File

@@ -2,6 +2,7 @@ package gemini
import (
"bufio"
"context"
"crypto/tls"
"net"
"net/url"
@@ -33,6 +34,10 @@ type Request struct {
// connection on which the request was received.
// This field is ignored by the client.
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.
@@ -46,6 +51,9 @@ func NewRequest(rawurl string) (*Request, error) {
// NewRequestFromURL returns a new request for the given 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 {
host := url.Host
if url.Port() == "" {
@@ -54,6 +62,7 @@ func NewRequestFromURL(url *url.URL) *Request {
return &Request{
URL: url,
Host: host,
Context: context.Background(),
}
}

View File

@@ -26,7 +26,7 @@ type Server struct {
WriteTimeout time.Duration
// Certificates contains the certificates used by the server.
Certificates CertificateStore
Certificates CertificateDir
// CreateCertificate, if not nil, will be called to create a new certificate
// 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
w.WriteStatus(StatusBadRequest)
} else {
// If no scheme is specified, assume a default scheme of gemini://
if url.Scheme == "" {
url.Scheme = "gemini"
}
// Store information about the TLS connection
connState := conn.(*tls.Conn).ConnectionState()
var cert *tls.Certificate

56
tofu.go
View File

@@ -20,43 +20,46 @@ const (
TrustAlways // The certificate is trusted always.
)
// 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]Fingerprint
// KnownHosts maps hosts to fingerprints.
type KnownHosts map[string]Fingerprint
// KnownHostsFile represents a list of known hosts optionally loaded from a file.
// 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.
func (k *KnownHosts) SetOutput(w io.Writer) {
func (k *KnownHostsFile) 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{}
func (k *KnownHostsFile) Add(hostname string, fingerprint Fingerprint) {
if k.KnownHosts == nil {
k.KnownHosts = KnownHosts{}
}
k.hosts[hostname] = fingerprint
k.KnownHosts[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]
func (k *KnownHostsFile) Lookup(hostname string) (Fingerprint, bool) {
c, ok := k.KnownHosts[hostname]
return c, ok
}
// 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 {
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 {
func (k *KnownHostsFile) WriteAll(w io.Writer) error {
for h, c := range k.KnownHosts {
if _, err := k.writeKnownHost(w, h, c); err != nil {
return err
}
@@ -65,14 +68,14 @@ func (k *KnownHosts) WriteAll(w io.Writer) error {
}
// 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)
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.Unix())
}
// Load loads the known hosts from the provided path.
// 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 {
func (k *KnownHostsFile) Load(path string) error {
f, err := os.OpenFile(path, os.O_CREATE|os.O_RDONLY, 0644)
if err != nil {
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.
// Invalid entries are ignored.
func (k *KnownHosts) Parse(r io.Reader) {
if k.hosts == nil {
k.hosts = map[string]Fingerprint{}
func (k *KnownHostsFile) Parse(r io.Reader) {
if k.KnownHosts == nil {
k.KnownHosts = map[string]Fingerprint{}
}
scanner := bufio.NewScanner(r)
for scanner.Scan() {
@@ -107,16 +110,17 @@ func (k *KnownHosts) Parse(r io.Reader) {
if algorithm != "SHA-512" {
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 {
continue
}
expires := time.Unix(unix, 0)
k.hosts[hostname] = Fingerprint{
k.KnownHosts[hostname] = Fingerprint{
Algorithm: algorithm,
Hex: fingerprint,
Hex: hex,
Expires: expires,
}
}
@@ -126,7 +130,7 @@ func (k *KnownHosts) Parse(r io.Reader) {
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
Expires time.Time // unix time of the fingerprint expiration date
}
// 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{
Algorithm: "SHA-512",
Hex: b.String(),
Expires: expires.Unix(),
Expires: expires,
}
}