summaryrefslogtreecommitdiff
path: root/tls.go
blob: 22a248e1c5d2face9ac61a3232117c16e3f62bcf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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
}