forked from smallstep/certificates
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathidentity.go
344 lines (305 loc) · 9.27 KB
/
identity.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
343
344
package identity
import (
"bytes"
"crypto"
"crypto/tls"
"crypto/x509"
"encoding/json"
"encoding/pem"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"github.com/pkg/errors"
"github.com/smallstep/certificates/api"
"go.step.sm/cli-utils/step"
"go.step.sm/crypto/pemutil"
)
// Type represents the different types of identity files.
type Type string
// Disabled represents a disabled identity type
const Disabled Type = ""
// MutualTLS represents the identity using mTLS.
const MutualTLS Type = "mTLS"
// TunnelTLS represents an identity using a (m)TLS tunnel.
//
// TunnelTLS can be optionally configured with client certificates and a root
// file with the CAs to trust. By default it will use the system truststore
// instead of the CA truststore.
const TunnelTLS Type = "tTLS"
// DefaultLeeway is the duration for matching not before claims.
const DefaultLeeway = 1 * time.Minute
var (
identityDir = step.IdentityPath
configDir = step.ConfigPath
// IdentityFile contains a pointer to a function that outputs the location of
// the identity file.
IdentityFile = step.IdentityFile
// DefaultsFile contains a prointer a function that outputs the location of the
// defaults configuration file.
DefaultsFile = step.DefaultsFile
)
// Identity represents the identity file that can be used to authenticate with
// the CA.
type Identity struct {
Type string `json:"type"`
Certificate string `json:"crt"`
Key string `json:"key"`
// Host is the tunnel host for a TunnelTLS (tTLS) identity.
Host string `json:"host,omitempty"`
// Root is the CA bundle of root CAs used in TunnelTLS to trust the
// certificate of the host.
Root string `json:"root,omitempty"`
}
// LoadIdentity loads an identity present in the given filename.
func LoadIdentity(filename string) (*Identity, error) {
b, err := os.ReadFile(filename)
if err != nil {
return nil, errors.Wrapf(err, "error reading %s", filename)
}
identity := new(Identity)
if err := json.Unmarshal(b, &identity); err != nil {
return nil, errors.Wrapf(err, "error unmarshaling %s", filename)
}
return identity, nil
}
// LoadDefaultIdentity loads the default identity.
func LoadDefaultIdentity() (*Identity, error) {
return LoadIdentity(IdentityFile())
}
// WriteDefaultIdentity writes the given certificates and key and the
// identity.json pointing to the new files.
func WriteDefaultIdentity(certChain []api.Certificate, key crypto.PrivateKey) error {
if err := os.MkdirAll(configDir(), 0700); err != nil {
return errors.Wrap(err, "error creating config directory")
}
identityDir := identityDir()
if err := os.MkdirAll(identityDir, 0700); err != nil {
return errors.Wrap(err, "error creating identity directory")
}
certFilename := filepath.Join(identityDir, "identity.crt")
keyFilename := filepath.Join(identityDir, "identity_key")
// Write certificate
if err := writeCertificate(certFilename, certChain); err != nil {
return err
}
// Write key
buf := new(bytes.Buffer)
block, err := pemutil.Serialize(key)
if err != nil {
return err
}
if err := pem.Encode(buf, block); err != nil {
return errors.Wrap(err, "error encoding identity key")
}
if err := os.WriteFile(keyFilename, buf.Bytes(), 0600); err != nil {
return errors.Wrap(err, "error writing identity certificate")
}
// Write identity.json
buf.Reset()
enc := json.NewEncoder(buf)
enc.SetIndent("", " ")
if err := enc.Encode(Identity{
Type: string(MutualTLS),
Certificate: certFilename,
Key: keyFilename,
}); err != nil {
return errors.Wrap(err, "error writing identity json")
}
if err := os.WriteFile(IdentityFile(), buf.Bytes(), 0600); err != nil {
return errors.Wrap(err, "error writing identity certificate")
}
return nil
}
// WriteIdentityCertificate writes the identity certificate to disk.
func WriteIdentityCertificate(certChain []api.Certificate) error {
filename := filepath.Join(identityDir(), "identity.crt")
return writeCertificate(filename, certChain)
}
// writeCertificate writes the given certificate on disk.
func writeCertificate(filename string, certChain []api.Certificate) error {
buf := new(bytes.Buffer)
for _, crt := range certChain {
block := &pem.Block{
Type: "CERTIFICATE",
Bytes: crt.Raw,
}
if err := pem.Encode(buf, block); err != nil {
return errors.Wrap(err, "error encoding certificate")
}
}
if err := os.WriteFile(filename, buf.Bytes(), 0600); err != nil {
return errors.Wrap(err, "error writing certificate")
}
return nil
}
// Kind returns the type for the given identity.
func (i *Identity) Kind() Type {
switch strings.ToLower(i.Type) {
case "":
return Disabled
case "mtls":
return MutualTLS
case "ttls":
return TunnelTLS
default:
return Type(i.Type)
}
}
// Validate validates the identity object.
func (i *Identity) Validate() error {
switch i.Kind() {
case Disabled:
return nil
case MutualTLS:
if i.Certificate == "" {
return errors.New("identity.crt cannot be empty")
}
if i.Key == "" {
return errors.New("identity.key cannot be empty")
}
if err := fileExists(i.Certificate); err != nil {
return err
}
return fileExists(i.Key)
case TunnelTLS:
if i.Host == "" {
return errors.New("tunnel.host cannot be empty")
}
if i.Certificate != "" {
if err := fileExists(i.Certificate); err != nil {
return err
}
if i.Key == "" {
return errors.New("tunnel.key cannot be empty")
}
if err := fileExists(i.Key); err != nil {
return err
}
}
if i.Root != "" {
if err := fileExists(i.Root); err != nil {
return err
}
}
return nil
default:
return errors.Errorf("unsupported identity type %s", i.Type)
}
}
// TLSCertificate returns a tls.Certificate for the identity.
func (i *Identity) TLSCertificate() (tls.Certificate, error) {
fail := func(err error) (tls.Certificate, error) { return tls.Certificate{}, err }
switch i.Kind() {
case Disabled:
return tls.Certificate{}, nil
case MutualTLS, TunnelTLS:
crt, err := tls.LoadX509KeyPair(i.Certificate, i.Key)
if err != nil {
return fail(errors.Wrap(err, "error creating identity certificate"))
}
// Check if certificate is expired.
x509Cert, err := x509.ParseCertificate(crt.Certificate[0])
if err != nil {
return fail(errors.Wrap(err, "error creating identity certificate"))
}
now := time.Now().Truncate(time.Second)
if now.Add(DefaultLeeway).Before(x509Cert.NotBefore) {
return fail(errors.New("certificate is not yet valid"))
}
if now.After(x509Cert.NotAfter) {
return fail(errors.New("certificate is already expired"))
}
return crt, nil
default:
return fail(errors.Errorf("unsupported identity type %s", i.Type))
}
}
// GetClientCertificateFunc returns a method that can be used as the
// GetClientCertificate property in a tls.Config.
func (i *Identity) GetClientCertificateFunc() func(*tls.CertificateRequestInfo) (*tls.Certificate, error) {
return func(*tls.CertificateRequestInfo) (*tls.Certificate, error) {
crt, err := tls.LoadX509KeyPair(i.Certificate, i.Key)
if err != nil {
return nil, errors.Wrap(err, "error loading identity certificate")
}
return &crt, nil
}
}
// GetCertPool returns a x509.CertPool if the identity defines a custom root.
func (i *Identity) GetCertPool() (*x509.CertPool, error) {
if i.Root == "" {
//nolint:nilnil // legacy
return nil, nil
}
b, err := os.ReadFile(i.Root)
if err != nil {
return nil, errors.Wrap(err, "error reading identity root")
}
pool := x509.NewCertPool()
if !pool.AppendCertsFromPEM(b) {
return nil, errors.Errorf("error pasing identity root: %s does not contain any certificate", i.Root)
}
return pool, nil
}
// Renewer is that interface that a renew client must implement.
type Renewer interface {
GetRootCAs() *x509.CertPool
Renew(tr http.RoundTripper) (*api.SignResponse, error)
}
// Renew renews the current identity certificate using a client with a renew
// method.
func (i *Identity) Renew(client Renewer) error {
switch i.Kind() {
case Disabled:
return nil
case MutualTLS, TunnelTLS:
cert, err := i.TLSCertificate()
if err != nil {
return err
}
tr := http.DefaultTransport.(*http.Transport).Clone()
tr.TLSClientConfig = &tls.Config{
Certificates: []tls.Certificate{cert},
RootCAs: client.GetRootCAs(),
MinVersion: tls.VersionTLS12,
PreferServerCipherSuites: true,
}
sign, err := client.Renew(tr)
if err != nil {
return err
}
if sign.CertChainPEM == nil || len(sign.CertChainPEM) == 0 {
sign.CertChainPEM = []api.Certificate{sign.ServerPEM, sign.CaPEM}
}
// Write certificate
buf := new(bytes.Buffer)
for _, crt := range sign.CertChainPEM {
block := &pem.Block{
Type: "CERTIFICATE",
Bytes: crt.Raw,
}
if err := pem.Encode(buf, block); err != nil {
return errors.Wrap(err, "error encoding identity certificate")
}
}
certFilename := filepath.Join(identityDir(), "identity.crt")
if err := os.WriteFile(certFilename, buf.Bytes(), 0600); err != nil {
return errors.Wrap(err, "error writing identity certificate")
}
return nil
default:
return errors.Errorf("unsupported identity type %s", i.Type)
}
}
func fileExists(filename string) error {
info, err := os.Stat(filename)
if err != nil {
return errors.Wrapf(err, "error reading %s", filename)
}
if info.IsDir() {
return errors.Errorf("error reading %s: file is a directory", filename)
}
return nil
}