-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
issue_cert.go
240 lines (202 loc) · 5.96 KB
/
issue_cert.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
/*
Copyright 2020 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package nodetasks
import (
"bytes"
"crypto/x509/pkix"
"fmt"
"hash/fnv"
"io"
"net"
"path/filepath"
"sort"
"time"
"k8s.io/klog/v2"
"k8s.io/kops/pkg/pki"
"k8s.io/kops/upup/pkg/fi"
)
// PKIXName is a simplified form of pkix.Name, for better golden test output
type PKIXName struct {
fi.NotADependency
CommonName string
Organization []string `json:",omitempty"`
}
func (n *PKIXName) toPKIXName() pkix.Name {
return pkix.Name{
CommonName: n.CommonName,
Organization: n.Organization,
}
}
type IssueCert struct {
Name string
Signer string `json:"signer"`
KeypairID string `json:"keypairID"`
Type string `json:"type"`
Subject PKIXName `json:"subject"`
AlternateNames []string `json:"alternateNames,omitempty"`
// IncludeRootCertificate will force the certificate data to include the full chain, not just the leaf
IncludeRootCertificate bool `json:"includeRootCertificate,omitempty"`
cert *fi.TaskDependentResource
key *fi.TaskDependentResource
ca *fi.TaskDependentResource
}
var _ fi.Task = &IssueCert{}
var _ fi.HasName = &IssueCert{}
func (i *IssueCert) GetName() *string {
return &i.Name
}
// String returns a string representation, implementing the Stringer interface
func (i *IssueCert) String() string {
return fmt.Sprintf("IssueCert: %s", i.Name)
}
func (i *IssueCert) GetResources() (certResource, keyResource, caResource *fi.TaskDependentResource) {
if i.cert == nil {
i.cert = &fi.TaskDependentResource{Task: i}
i.key = &fi.TaskDependentResource{Task: i}
i.ca = &fi.TaskDependentResource{Task: i}
}
return i.cert, i.key, i.ca
}
func (i *IssueCert) AddFileTasks(c *fi.ModelBuilderContext, dir string, name string, caName string, owner *string) error {
certResource, keyResource, caResource := i.GetResources()
err := c.EnsureTask(&File{
Path: dir,
Type: FileType_Directory,
Mode: fi.String("0755"),
})
if err != nil {
return err
}
c.AddTask(&File{
Path: filepath.Join(dir, name+".crt"),
Contents: certResource,
Type: FileType_File,
Mode: fi.String("0644"),
Owner: owner,
})
c.AddTask(&File{
Path: filepath.Join(dir, name+".key"),
Contents: keyResource,
Type: FileType_File,
Mode: fi.String("0600"),
Owner: owner,
})
if caName != "" {
err = c.EnsureTask(&File{
Path: filepath.Join(dir, caName+".crt"),
Contents: caResource,
Type: FileType_File,
Mode: fi.String("0644"),
Owner: owner,
})
if err != nil {
return nil
}
}
return nil
}
func (e *IssueCert) Run(c *fi.Context) error {
// Skew the certificate lifetime by up to 30 days based on information about the generating node.
// This is so that different nodes created at the same time have the certificates they generated
// expire at different times, but all certificates on a given node expire around the same time.
hash := fnv.New32()
addrs, err := net.InterfaceAddrs()
sort.Slice(addrs, func(i, j int) bool {
return addrs[i].String() < addrs[j].String()
})
if err == nil {
for _, addr := range addrs {
_, _ = hash.Write([]byte(addr.String()))
}
} else {
klog.Warningf("cannot skew certificate lifetime: failed to get interface addresses: %v", err)
}
validHours := (455 * 24) + (hash.Sum32() % (30 * 24))
req := &pki.IssueCertRequest{
Signer: e.Signer,
Type: e.Type,
Subject: e.Subject.toPKIXName(),
AlternateNames: e.AlternateNames,
Validity: time.Hour * time.Duration(validHours),
}
keystore, err := newStaticKeystore(e.Signer, e.KeypairID, c.Keystore)
if err != nil {
return err
}
klog.Infof("signing certificate for %q", e.Name)
certificate, privateKey, caCertificate, err := pki.IssueCert(req, keystore)
if err != nil {
return err
}
certResource, keyResource, caResource := e.GetResources()
certResource.Resource = &asBytesResource{certificate}
keyResource.Resource = &asBytesResource{privateKey}
caResource.Resource = &asBytesResource{caCertificate}
if e.IncludeRootCertificate {
var b bytes.Buffer
if _, err := certificate.WriteTo(&b); err != nil {
return err
}
b.WriteString("\n")
if _, err := caCertificate.WriteTo(&b); err != nil {
return err
}
certResource.Resource = fi.NewBytesResource(b.Bytes())
}
return nil
}
type hasAsBytes interface {
AsBytes() ([]byte, error)
}
type asBytesResource struct {
hasAsBytes
}
func (a asBytesResource) Open() (io.Reader, error) {
data, err := a.AsBytes()
if err != nil {
return nil, err
}
return bytes.NewReader(data), nil
}
type staticKeystore struct {
keyset string
certificate *pki.Certificate
key *pki.PrivateKey
}
func (s staticKeystore) FindPrimaryKeypair(name string) (*pki.Certificate, *pki.PrivateKey, error) {
if name != s.keyset {
return nil, nil, fmt.Errorf("wrong signer: expected %q got %q", s.keyset, name)
}
return s.certificate, s.key, nil
}
func newStaticKeystore(signer string, keypairID string, keystore fi.Keystore) (pki.Keystore, error) {
if signer == "" {
return nil, nil
}
if keypairID == "" {
return nil, fmt.Errorf("missing keypairID for %s", signer)
}
keyset, err := keystore.FindKeyset(signer)
if err != nil {
return nil, fmt.Errorf("reading keyset for %s: %v", signer, err)
}
item := keyset.Items[keypairID]
if item == nil {
return nil, fmt.Errorf("no keypair with id %s for %s", keypairID, signer)
}
return &staticKeystore{
keyset: signer,
certificate: item.Certificate,
key: item.PrivateKey,
}, nil
}