demo / network-computer
Public
Copy of github.com/askrobots/network-computer (MIT): a desk you reach from anything. The original lives on GitHub.
GitStable demo
README: say this is a copy and where the original is
cde82c2
13 hours, 42 minutes ago
History
tlspin.go · 1.7 KB · 51 lines
| 1 | // Package tlspin makes HTTP clients that trust exactly one certificate, |
| 2 | // identified by the SHA-256 of its DER encoding. Used with a rendezvous that |
| 3 | // runs a self-signed cert: no certificate authority and no domain, and still |
| 4 | // protected against a man in the middle, because only that one key is accepted. |
| 5 | package tlspin |
| 6 | |
| 7 | import ( |
| 8 | "crypto/sha256" |
| 9 | "crypto/tls" |
| 10 | "encoding/hex" |
| 11 | "errors" |
| 12 | "fmt" |
| 13 | "net/http" |
| 14 | "strings" |
| 15 | ) |
| 16 | |
| 17 | // Normalize accepts "AB:CD:...", "abcd...", or "sha256 abcd..." and returns |
| 18 | // lowercase hex with no separators. |
| 19 | func Normalize(fp string) string { |
| 20 | fp = strings.ToLower(strings.TrimSpace(fp)) |
| 21 | fp = strings.TrimPrefix(fp, "sha256") |
| 22 | fp = strings.TrimLeft(fp, ":/= ") |
| 23 | return strings.NewReplacer(":", "", " ", "").Replace(fp) |
| 24 | } |
| 25 | |
| 26 | // Client returns an http.Client pinned to fp. An empty fp returns a normal |
| 27 | // client that verifies certificates against the system roots. |
| 28 | func Client(fp string) *http.Client { |
| 29 | fp = Normalize(fp) |
| 30 | if fp == "" { |
| 31 | return http.DefaultClient |
| 32 | } |
| 33 | t := http.DefaultTransport.(*http.Transport).Clone() |
| 34 | t.TLSClientConfig = &tls.Config{ |
| 35 | MinVersion: tls.VersionTLS12, |
| 36 | // Chain verification is replaced by the exact-key check below. |
| 37 | InsecureSkipVerify: true, |
| 38 | // VerifyConnection runs on every connection, resumed ones included. |
| 39 | VerifyConnection: func(cs tls.ConnectionState) error { |
| 40 | if len(cs.PeerCertificates) == 0 { |
| 41 | return errors.New("tlspin: server sent no certificate") |
| 42 | } |
| 43 | sum := sha256.Sum256(cs.PeerCertificates[0].Raw) |
| 44 | if got := hex.EncodeToString(sum[:]); got != fp { |
| 45 | return fmt.Errorf("tlspin: certificate fingerprint mismatch (got %s)", got) |
| 46 | } |
| 47 | return nil |
| 48 | }, |
| 49 | } |
| 50 | return &http.Client{Transport: t} |
| 51 | } |