forked from cockroachdb/cockroach
-
Notifications
You must be signed in to change notification settings - Fork 0
/
certificate_loader.go
342 lines (293 loc) · 9.52 KB
/
certificate_loader.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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
// Copyright 2017 The Cockroach 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.
//
// Author: Marc Berhault (marc@cockroachlabs.com)
package security
import (
"io/ioutil"
"os"
"path/filepath"
"runtime"
"strings"
"golang.org/x/net/context"
"github.com/cockroachdb/cockroach/pkg/util/envutil"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/pkg/errors"
)
func init() {
if runtime.GOOS == "windows" {
// File modes on windows default to 0666 for r/w files:
// https://golang.org/src/os/types_windows.go?#L31
// This would fail any attempt to load keys, so we need to disable permission checks.
skipPermissionChecks = true
} else {
skipPermissionChecks = envutil.EnvOrDefaultBool("COCKROACH_SKIP_KEY_PERMISSION_CHECK", false)
}
}
var skipPermissionChecks bool
// AssetLoader describes the functions necessary to read certificate and key files.
type AssetLoader struct {
ReadDir func(dirname string) ([]os.FileInfo, error)
ReadFile func(filename string) ([]byte, error)
Stat func(name string) (os.FileInfo, error)
}
// defaultAssetLoader uses real filesystem calls.
var defaultAssetLoader = AssetLoader{
ReadDir: ioutil.ReadDir,
ReadFile: ioutil.ReadFile,
Stat: os.Stat,
}
// assetLoaderImpl is used to list/read/stat security assets.
var assetLoaderImpl = defaultAssetLoader
// SetAssetLoader overrides the asset loader with the passed-in one.
func SetAssetLoader(al AssetLoader) {
assetLoaderImpl = al
}
// ResetAssetLoader restores the asset loader to the default value.
func ResetAssetLoader() {
assetLoaderImpl = defaultAssetLoader
}
type pemUsage uint32
const (
_ pemUsage = iota
// CAPem describes a CA certificate.
CAPem
// NodePem describes a combined server/client certificate for user Node.
NodePem
// ClientPem describes a client certificate.
ClientPem
// Maximum allowable permissions.
maxKeyPermissions os.FileMode = 0700
// Filename extenstions.
certExtension = `.crt`
keyExtension = `.key`
// Certificate directory permissions.
defaultCertsDirPerm = 0700
)
func (p pemUsage) String() string {
switch p {
case CAPem:
return "Certificate Authority"
case NodePem:
return "Node"
case ClientPem:
return "Client"
default:
return "unknown"
}
}
// CertInfo describe a certificate file and optional key file.
// To obtain the full path, Filename and KeyFilename must be joined
// with the certs directory.
// The key may not be present if this is a CA certificate.
// If Err != nil, the CertInfo must NOT be used.
type CertInfo struct {
// FileUsage describes the use of this certificate.
FileUsage pemUsage
// Filename is the base filename of the certificate.
Filename string
// FileContents is the raw cert file data.
FileContents []byte
// KeyFilename is the base filename of the key, blank if not found (CA certs only).
KeyFilename string
// KeyFileContents is the raw key file data.
KeyFileContents []byte
// Name is the blob in the middle of the filename. eg: username for client certs.
Name string
// Error is any error encountered when loading the certificate/key pair.
// For example: bad permissions on the key will be stored here.
Error error
}
func exceedsPermissions(objectMode, allowedMode os.FileMode) bool {
mask := os.FileMode(0777) ^ allowedMode
return mask&objectMode != 0
}
func isCertificateFile(filename string) bool {
return strings.HasSuffix(filename, certExtension)
}
// CertificateLoader searches for certificates and keys in the certs directory.
type CertificateLoader struct {
certsDir string
skipPermissionChecks bool
certificates []*CertInfo
}
// Certificates returns the loaded certificates.
func (cl *CertificateLoader) Certificates() []*CertInfo {
return cl.certificates
}
// NewCertificateLoader creates a new instance of the certificate loader.
func NewCertificateLoader(certsDir string) *CertificateLoader {
return &CertificateLoader{
certsDir: certsDir,
skipPermissionChecks: skipPermissionChecks,
certificates: make([]*CertInfo, 0),
}
}
// MaybeCreateCertsDir creates the certificate directory if it does not
// exist. Returns an error if we could not stat or create the directory.
func (cl *CertificateLoader) MaybeCreateCertsDir() error {
dirInfo, err := os.Stat(cl.certsDir)
if err == nil {
if !dirInfo.IsDir() {
return errors.Errorf("certs directory %s exists but is not a directory", cl.certsDir)
}
return nil
}
if !os.IsNotExist(err) {
return errors.Wrapf(err, "could not stat certs directory %s", cl.certsDir)
}
if err := os.Mkdir(cl.certsDir, defaultCertsDirPerm); err != nil {
return errors.Wrapf(err, "could not create certs directory %s", cl.certsDir)
}
return nil
}
// TestDisablePermissionChecks turns off permissions checks.
// Used by tests only.
func (cl *CertificateLoader) TestDisablePermissionChecks() {
cl.skipPermissionChecks = true
}
// Load examines all .crt files in the certs directory, determines their
// usage, and looks for their keys.
// It populates the certificates field.
func (cl *CertificateLoader) Load() error {
fileInfos, err := assetLoaderImpl.ReadDir(cl.certsDir)
if err != nil {
if os.IsNotExist(err) {
// Directory does not exist.
if log.V(3) {
log.Infof(context.Background(), "missing certs directory %s", cl.certsDir)
}
return nil
}
return err
}
if log.V(3) {
log.Infof(context.Background(), "scanning certs directory %s", cl.certsDir)
}
// Walk the directory contents.
for _, info := range fileInfos {
filename := info.Name()
fullPath := filepath.Join(cl.certsDir, filename)
if info.IsDir() {
// Skip subdirectories.
if log.V(3) {
log.Infof(context.Background(), "skipping sub-directory %s", fullPath)
}
continue
}
if !isCertificateFile(filename) {
if log.V(3) {
log.Infof(context.Background(), "skipping non-certificate file %s", filename)
}
continue
}
// Build the info struct from the filename.
ci, err := cl.certInfoFromFilename(filename)
if err != nil {
log.Warningf(context.Background(), "bad filename %s: %v", fullPath, err)
continue
}
// Look for the associated key.
// Any errors are kept for better visibility later.
if err := cl.findKey(ci); err != nil {
log.Warningf(context.Background(), "error finding key for %s: %v", fullPath, err)
ci.Error = err
} else if log.V(3) {
log.Infof(context.Background(), "found certificate %s", ci.Filename)
}
cl.certificates = append(cl.certificates, ci)
}
return nil
}
// certInfoFromFilename takes a filename and attempts to determine the
// certificate usage (ca, node, etc..).
func (cl *CertificateLoader) certInfoFromFilename(filename string) (*CertInfo, error) {
parts := strings.Split(filename, `.`)
numParts := len(parts)
if numParts < 2 {
return nil, errors.New("not enough parts found")
}
var pu pemUsage
var name string
prefix := parts[0]
switch parts[0] {
case `ca`:
pu = CAPem
if numParts != 2 {
return nil, errors.Errorf("CA certificate filename should match ca%s", certExtension)
}
case `node`:
pu = NodePem
if numParts != 2 {
return nil, errors.Errorf("node certificate filename should match node%s", certExtension)
}
case `client`:
pu = ClientPem
// strip prefix and suffix and re-join middle parts.
name = strings.Join(parts[1:numParts-1], `.`)
if len(name) == 0 {
return nil, errors.Errorf("client certificate filename should match client.<user>%s", certExtension)
}
default:
return nil, errors.Errorf("unknown prefix %q", prefix)
}
// Read cert file contents.
fullCertPath := filepath.Join(cl.certsDir, filename)
certPEMBlock, err := assetLoaderImpl.ReadFile(fullCertPath)
if err != nil {
return nil, errors.Errorf("could not read certificate file: %v", err)
}
return &CertInfo{
FileUsage: pu,
Filename: filename,
FileContents: certPEMBlock,
Name: name,
}, nil
}
// findKey takes a CertInfo and looks for the corresponding key file.
// If found, sets the 'keyFilename' and returns nil, returns error otherwise.
// Does not load CA keys.
func (cl *CertificateLoader) findKey(ci *CertInfo) error {
if ci.FileUsage == CAPem {
return nil
}
keyFilename := strings.TrimSuffix(ci.Filename, certExtension) + keyExtension
fullKeyPath := filepath.Join(cl.certsDir, keyFilename)
// Stat the file. This follows symlinks.
info, err := assetLoaderImpl.Stat(fullKeyPath)
if err != nil {
return errors.Errorf("could not stat key file %s: %v", fullKeyPath, err)
}
// Only regular files are supported (after following symlinks).
fileMode := info.Mode()
if !fileMode.IsRegular() {
return errors.Errorf("key file %s is not a regular file", fullKeyPath)
}
if !cl.skipPermissionChecks {
// Check permissions bits.
filePerm := fileMode.Perm()
if exceedsPermissions(filePerm, maxKeyPermissions) {
return errors.Errorf("key file %s has permissions %s, exceeds %s",
fullKeyPath, filePerm, maxKeyPermissions)
}
}
// Read key file.
keyPEMBlock, err := assetLoaderImpl.ReadFile(fullKeyPath)
if err != nil {
return errors.Errorf("could not read key file %s: %v", fullKeyPath, err)
}
ci.KeyFilename = keyFilename
ci.KeyFileContents = keyPEMBlock
return nil
}