-
Notifications
You must be signed in to change notification settings - Fork 8
/
tls.go
97 lines (90 loc) · 2.17 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package stock
import (
"crypto/tls"
"crypto/x509"
"io/ioutil"
"github.com/freeconf/yang/node"
"github.com/freeconf/yang/nodeutil"
"github.com/freeconf/yang/val"
)
type Tls struct {
Config tls.Config
CertFile string
KeyFile string
CaCertFile string
}
func TlsNode(config *Tls) node.Node {
return &nodeutil.Extend{
Base: nodeutil.ReflectChild(&config.Config),
OnChild: func(p node.Node, r node.ChildRequest) (node.Node, error) {
switch r.Meta.Ident() {
case "ca":
if r.New {
config.Config.RootCAs = x509.NewCertPool()
// assertion - harmless if not used, but useful if is used.
config.Config.ClientCAs = config.Config.RootCAs
config.Config.ClientAuth = tls.VerifyClientCertIfGiven
}
if config.Config.RootCAs != nil {
return CertificateAuthorityNode(config), nil
}
case "cert":
if r.New {
config.Config.Certificates = make([]tls.Certificate, 1)
}
if len(config.Config.Certificates) > 0 {
return CertificateNode(config), nil
}
}
return p.Child(r)
},
}
}
func CertificateAuthorityNode(config *Tls) node.Node {
n := &nodeutil.Basic{}
n.OnField = func(r node.FieldRequest, hnd *node.ValueHandle) error {
switch r.Meta.Ident() {
case "certFile":
if r.Write {
config.CaCertFile = hnd.Val.String()
pemData, err := ioutil.ReadFile(hnd.Val.String())
if err != nil {
return err
}
config.Config.RootCAs.AppendCertsFromPEM(pemData)
} else {
hnd.Val = val.String(config.CaCertFile)
}
}
return nil
}
return n
}
func CertificateNode(config *Tls) node.Node {
n := &nodeutil.Basic{}
n.OnField = func(r node.FieldRequest, hnd *node.ValueHandle) (err error) {
switch r.Meta.Ident() {
case "certFile":
if r.Write {
config.CertFile = hnd.Val.String()
} else {
hnd.Val = val.String(config.CertFile)
}
case "keyFile":
if r.Write {
config.KeyFile = hnd.Val.String()
} else {
hnd.Val = val.String(config.KeyFile)
}
}
return nil
}
n.OnEndEdit = func(r node.NodeRequest) error {
var err error
if r.New {
config.Config.Certificates[0], err = tls.LoadX509KeyPair(config.CertFile, config.KeyFile)
}
return err
}
return n
}