Polish example client

This commit is contained in:
adnano 2020-09-27 19:45:48 -04:00
parent 4cbc591c3e
commit 9f1a38a0dd
4 changed files with 77 additions and 88 deletions

View File

@ -75,35 +75,8 @@ client.TrustCertificate = func(hostname string, cert *x509.Certificate, knownHos
} }
``` ```
Advanced clients can prompt the user for what to do when encountering an unknown certificate: Advanced clients can prompt the user for what to do when encountering an unknown
certificate. See `examples/client` for an example.
```go
client.TrustCertificate = func(hostname string, cert *x509.Certificate, knownHosts *gemini.KnownHosts) error {
err := knownHosts.Lookup(cert)
if err != nil {
switch err {
case gemini.ErrCertificateNotTrusted:
// Alert the user that the certificate is not trusted
fmt.Printf("Warning: certificate for %s is not trusted!\n", hostname)
fmt.Println("This could indicate a Man-in-the-Middle attack.")
case gemini.ErrCertificateUnknown:
// Prompt the user to trust the certificate
if userTrustsCertificateTemporarily() {
// Temporarily trust the certificate
knownHosts.AddTemporary(hostname, cert)
return nil
} else if userTrustsCertificatePermanently() {
// Add the certificate to the known hosts file
knownHosts.Add(cert)
return nil
}
}
}
return err
}
```
See `examples/client` for an example client.
## Client Authentication ## Client Authentication

View File

@ -201,6 +201,9 @@ func (c *Client) Send(req *Request) (*Response, error) {
return cert, nil return cert, nil
} }
} }
if req.Certificate == nil {
return &tls.Certificate{}, nil
}
return req.Certificate, nil return req.Certificate, nil
}, },
VerifyPeerCertificate: func(rawCerts [][]byte, _ [][]*x509.Certificate) error { VerifyPeerCertificate: func(rawCerts [][]byte, _ [][]*x509.Certificate) error {

View File

@ -106,7 +106,7 @@ func loginPassword(rw *gemini.ResponseWriter, req *gemini.Request) {
session.authorized = true session.authorized = true
rw.WriteHeader(gemini.StatusRedirectTemporary, "gemini://localhost/profile") rw.WriteHeader(gemini.StatusRedirectTemporary, "gemini://localhost/profile")
} else { } else {
rw.WriteHeader(gemini.StatusInput, "Wrong password. Please try again.\nPassword:") rw.WriteHeader(gemini.StatusInput, "Wrong password. Please try again")
} }
} }
} else { } else {
@ -123,6 +123,10 @@ func logout(rw *gemini.ResponseWriter, req *gemini.Request) {
rw.Write([]byte("Successfully logged out.\n")) rw.Write([]byte("Successfully logged out.\n"))
} }
func badLogin(rw *gemini.ResponseWriter, req *gemini.Request) {
}
func profile(rw *gemini.ResponseWriter, req *gemini.Request) { func profile(rw *gemini.ResponseWriter, req *gemini.Request) {
if len(req.TLS.PeerCertificates) > 0 { if len(req.TLS.PeerCertificates) > 0 {
session, ok := getSession(req.TLS.PeerCertificates[0]) session, ok := getSession(req.TLS.PeerCertificates[0])

View File

@ -4,39 +4,39 @@ package main
import ( import (
"bufio" "bufio"
"crypto/tls"
"crypto/x509" "crypto/x509"
"fmt" "fmt"
"log"
"os" "os"
"git.sr.ht/~adnano/go-gemini" "git.sr.ht/~adnano/go-gemini"
) )
var ( var (
client *gemini.Client scanner = bufio.NewScanner(os.Stdin)
cert tls.Certificate client *gemini.Client
) )
func init() { func init() {
// Initialize the client
client = &gemini.Client{} client = &gemini.Client{}
client.KnownHosts.Load() client.KnownHosts.Load() // Load known hosts
client.TrustCertificate = func(hostname string, cert *x509.Certificate, knownHosts *gemini.KnownHosts) error { client.TrustCertificate = func(hostname string, cert *x509.Certificate, knownHosts *gemini.KnownHosts) error {
err := knownHosts.Lookup(hostname, cert) err := knownHosts.Lookup(hostname, cert)
if err != nil { if err != nil {
switch err { switch err {
case gemini.ErrCertificateNotTrusted: case gemini.ErrCertificateNotTrusted:
// Alert the user that the certificate is not trusted // Alert the user that the certificate is not trusted
fmt.Printf("Warning: certificate for %s is not trusted!\n", hostname) fmt.Printf("Warning: Certificate for %s is not trusted!\n", hostname)
fmt.Println("This could indicate a Man-in-the-Middle attack.") fmt.Println("This could indicate a Man-in-the-Middle attack.")
case gemini.ErrCertificateUnknown: case gemini.ErrCertificateUnknown:
// Prompt the user to trust the certificate // Prompt the user to trust the certificate
if userTrustsCertificateTemporarily() { trust := trustCertificate(cert)
switch trust {
case trustOnce:
// Temporarily trust the certificate // Temporarily trust the certificate
knownHosts.AddTemporary(hostname, cert) knownHosts.AddTemporary(hostname, cert)
return nil return nil
} else if userTrustsCertificatePermanently() { case trustAlways:
// Add the certificate to the known hosts file // Add the certificate to the known hosts file
knownHosts.Add(hostname, cert) knownHosts.Add(hostname, cert)
return nil return nil
@ -45,79 +45,88 @@ func init() {
} }
return err return err
} }
client.GetCertificate = func(req *gemini.Request, store *gemini.CertificateStore) *tls.Certificate {
return &cert
}
// Configure a client side certificate.
// To generate a TLS key pair, run:
//
// go run -tags=example ../cert
var err error
cert, err = tls.LoadX509KeyPair("examples/client/localhost.crt", "examples/client/localhost.key")
if err != nil {
log.Fatal(err)
}
} }
func makeRequest(url string) { // sendRequest sends a request to the given url.
req, err := gemini.NewRequest(url) func sendRequest(req *gemini.Request) error {
if err != nil {
log.Fatal(err)
}
req.Certificate = &cert
resp, err := client.Send(req) resp, err := client.Send(req)
if err != nil { if err != nil {
log.Fatal(err) return err
} }
fmt.Println("Status code:", resp.Status)
fmt.Println("Meta:", resp.Meta)
switch resp.Status / 10 { switch resp.Status / 10 {
case gemini.StatusClassInput: case gemini.StatusClassInput:
scanner := bufio.NewScanner(os.Stdin)
fmt.Printf("%s: ", resp.Meta) fmt.Printf("%s: ", resp.Meta)
scanner.Scan() scanner.Scan()
query := scanner.Text() req.URL.RawQuery = scanner.Text()
makeRequest(url + "?" + query) return sendRequest(req)
return
case gemini.StatusClassSuccess: case gemini.StatusClassSuccess:
fmt.Print("Body:\n", string(resp.Body)) fmt.Print(string(resp.Body))
return nil
case gemini.StatusClassRedirect: case gemini.StatusClassRedirect:
log.Print("Redirecting to ", resp.Meta) fmt.Println("Redirecting to ", resp.Meta)
makeRequest(resp.Meta) req, err := gemini.NewRequest(resp.Meta)
return if err != nil {
return err
}
return sendRequest(req)
case gemini.StatusClassTemporaryFailure: case gemini.StatusClassTemporaryFailure:
log.Fatal("Temporary failure") return fmt.Errorf("Temporary failure: %s", resp.Meta)
case gemini.StatusClassPermanentFailure: case gemini.StatusClassPermanentFailure:
log.Fatal("Permanent failure") return fmt.Errorf("Permanent failure: %s", resp.Meta)
case gemini.StatusClassClientCertificateRequired: case gemini.StatusClassClientCertificateRequired:
log.Fatal("Client certificate required") fmt.Println("Generating client certificate for", req.Hostname())
return nil // TODO: Generate and store client certificate
default: default:
log.Fatal("Protocol error") return fmt.Errorf("Protocol error: Server sent an invalid response")
} }
} }
func userTrustsCertificateTemporarily() bool { type trust int
fmt.Print("Do you want to trust the certificate temporarily? (y/n) ")
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
return scanner.Text() == "y"
}
func userTrustsCertificatePermanently() bool { const (
fmt.Print("How about permanently? (y/n) ") trustAbort trust = iota
scanner := bufio.NewScanner(os.Stdin) trustOnce
trustAlways
)
const trustPrompt = `The certificate offered by this server is of unknown trust. Its fingerprint is:
%s
If you knew the fingerprint to expect in advance, verify that this matches.
Otherwise, this should be safe to trust.
[t]rust always; trust [o]nce; [a]bort
=> `
func trustCertificate(cert *x509.Certificate) trust {
fmt.Printf(trustPrompt, gemini.Fingerprint(cert))
scanner.Scan() scanner.Scan()
return scanner.Text() == "y" switch scanner.Text() {
case "t":
return trustAlways
case "o":
return trustOnce
default:
return trustAbort
}
} }
func main() { func main() {
if len(os.Args) < 2 { if len(os.Args) < 2 {
log.Fatalf("usage: %s gemini://...", os.Args[0]) fmt.Println("usage: %s gemini://...", os.Args[0])
os.Exit(1)
}
url := os.Args[1]
req, err := gemini.NewRequest(url)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
if err := sendRequest(req); err != nil {
fmt.Println(err)
os.Exit(1)
} }
makeRequest(os.Args[1])
} }