-
Notifications
You must be signed in to change notification settings - Fork 280
/
certs.go
79 lines (70 loc) · 1.54 KB
/
certs.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package config
import (
"crypto/x509"
"strings"
)
type certUsage byte
type certsIndex map[string]map[string]certUsage
const (
certUsageServerAuth = certUsage(1 << iota)
certUsageClientAuth
)
func splitDomainName(name string) (prefix, suffix string) {
dot := strings.IndexRune(name, '.')
if dot < 0 {
dot = 0 // i.e. `localhost`
}
return name[0:dot], name[dot:]
}
func getCertUsage(cert *x509.Certificate) certUsage {
var usage certUsage
for _, ex := range cert.ExtKeyUsage {
switch ex {
case x509.ExtKeyUsageClientAuth:
usage |= certUsageClientAuth
case x509.ExtKeyUsageServerAuth:
usage |= certUsageServerAuth
}
}
return usage
}
func (c certsIndex) addCert(cert *x509.Certificate) {
usage := getCertUsage(cert)
for _, name := range cert.DNSNames {
c.add(name, usage)
}
}
func (c certsIndex) matchCert(cert *x509.Certificate) (bool, string) {
usage := getCertUsage(cert)
for _, name := range cert.DNSNames {
if c.match(name, usage) {
return true, name
}
}
return false, ""
}
func (c certsIndex) add(name string, usage certUsage) {
prefix, suffix := splitDomainName(name)
names := c[suffix]
if names == nil {
names = make(map[string]certUsage)
c[suffix] = names
}
names[prefix] = usage
}
func (c certsIndex) match(name string, usage certUsage) bool {
prefix, suffix := splitDomainName(name)
names := c[suffix]
if names == nil {
return false
}
if prefix != "*" {
return names["*"]&usage != 0 || names[prefix]&usage != 0
}
for _, u := range names {
if u&usage != 0 {
return true
}
}
return false
}