summaryrefslogtreecommitdiff
path: root/tls.go
diff options
context:
space:
mode:
authortjp <tjp@ctrl-c.club>2024-01-05 12:19:40 -0700
committertjp <tjp@ctrl-c.club>2024-01-05 12:24:46 -0700
commit230933ee0e4bce6ddf25e0816fff0bd30e3c8864 (patch)
treeb5e4818d05fa770c6316b41cf57cffb8eb952627 /tls.go
parent65218373fdc7e32ef175425c25ba9e90ac31fac6 (diff)
TOFU certificate validation
Diffstat (limited to 'tls.go')
-rw-r--r--tls.go47
1 files changed, 47 insertions, 0 deletions
diff --git a/tls.go b/tls.go
new file mode 100644
index 0000000..22a248e
--- /dev/null
+++ b/tls.go
@@ -0,0 +1,47 @@
+package main
+
+import (
+ "crypto/sha256"
+ "crypto/tls"
+ "crypto/x509"
+ "encoding/hex"
+ "errors"
+)
+
+func tlsConfig() *tls.Config {
+ return &tls.Config{
+ InsecureSkipVerify: true,
+ VerifyConnection: tofuVerify,
+ }
+}
+
+var tofuStore map[string]string
+
+var ErrTOFUViolation = errors.New("certificate for this domain has changed")
+
+func tofuVerify(connState tls.ConnectionState) error {
+ certhash, err := hashCert(connState.PeerCertificates[0])
+ if err != nil {
+ return err
+ }
+
+ expected, ok := tofuStore[connState.ServerName]
+ if !ok {
+ tofuStore[connState.ServerName] = certhash
+ return saveTofuStore(tofuStore)
+ }
+
+ if certhash != expected {
+ return ErrTOFUViolation
+ }
+ return nil
+}
+
+func hashCert(cert *x509.Certificate) (string, error) {
+ pubkeybytes, err := x509.MarshalPKIXPublicKey(cert.PublicKey)
+ if err != nil {
+ return "", err
+ }
+ hash := sha256.Sum256(pubkeybytes)
+ return hex.EncodeToString(hash[:]), nil
+}