-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
tls.go
65 lines (57 loc) · 1.77 KB
/
tls.go
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package main
import (
"crypto/tls"
"crypto/x509"
"fmt"
"log/slog"
"os"
"strings"
)
func (app *application) setupTLSConfig() (*tls.Config, error) {
tlsConfig := &tls.Config{MinVersion: tls.VersionTLS13}
if app.config.Server.RootCA != "" {
caCertPEM, err := os.ReadFile(app.config.Server.RootCA)
if err != nil {
return nil, err
}
roots := x509.NewCertPool()
ok := roots.AppendCertsFromPEM(caCertPEM)
if !ok {
return nil, fmt.Errorf("failed to parse root certificate")
}
tlsConfig.ClientCAs = roots
tlsConfig.ClientAuth = tls.RequireAndVerifyClientCert
}
if app.config.Server.CertSubject != "" {
tlsConfig.VerifyPeerCertificate = func(_ [][]byte, verifiedChains [][]*x509.Certificate) error {
certs := make(map[string]bool)
// only loop over verified chains (matches the rootca)
for _, x := range verifiedChains {
// we need at least one certificate
if len(x) == 0 {
continue
}
// it seems like the first certificate is always the leaf
// only add the leaf to the array as we want to check the leaf's subject only
leafSubject := x[0].Subject.String()
if _, ok := certs[leafSubject]; !ok {
certs[leafSubject] = true
}
for _, y := range x {
app.logger.Debug("Got certificate", slog.String("subject", y.Subject.String()), slog.Int64("serial", y.SerialNumber.Int64()))
}
}
var subjects []string
for subject := range certs {
if subject == app.config.Server.CertSubject {
app.logger.Debug("Allowing certificate", slog.String("subject", subject))
// allow
return nil
}
subjects = append(subjects, subject)
}
return fmt.Errorf("access denied, no valid certificate provided. Got the following subjects: %s", strings.Join(subjects, ", "))
}
}
return tlsConfig, nil
}