-
Notifications
You must be signed in to change notification settings - Fork 0
/
rotate.go
636 lines (581 loc) · 21.5 KB
/
rotate.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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
/*
Copyright 2018 Gravitational, Inc.
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 auth
import (
"crypto/rsa"
"crypto/x509/pkix"
"time"
"github.com/gravitational/teleport/lib/auth/native"
"github.com/gravitational/teleport/lib/defaults"
"github.com/gravitational/teleport/lib/services"
"github.com/gravitational/teleport/lib/tlsca"
"github.com/gravitational/trace"
"github.com/jonboulle/clockwork"
"github.com/pborman/uuid"
"github.com/sirupsen/logrus"
"golang.org/x/crypto/ssh"
)
// RotateRequest is a request to start rotation of the certificate authority.
type RotateRequest struct {
// Type is a certificate authority type, if omitted, both user and host CA
// will be rotated.
Type services.CertAuthType `json:"type"`
// GracePeriod is used to generate cert rotation schedule that defines
// times at which different rotation phases will be applied by the auth server
// in auto mode. It is not used in manual rotation mode.
// If omitted, default value is set, if 0 is supplied, it is interpreted as
// forcing rotation of all certificate authorities with no grace period,
// all existing users and hosts will have to re-login and re-added
// into the cluster.
GracePeriod *time.Duration `json:"grace_period,omitempty"`
// TargetPhase sets desired rotation phase to move to, if not set
// will be set automatically, it is a required argument
// for manual rotation.
TargetPhase string `json:"target_phase,omitempty"`
// Mode sets manual or auto rotation mode.
Mode string `json:"mode"`
// Schedule is an optional rotation schedule,
// autogenerated based on GracePeriod parameter if not set.
Schedule *services.RotationSchedule `json:"schedule"`
}
// Types returns cert authority types requested to be rotated.
func (r *RotateRequest) Types() []services.CertAuthType {
switch r.Type {
case "":
return []services.CertAuthType{services.HostCA, services.UserCA}
case services.HostCA:
return []services.CertAuthType{services.HostCA}
case services.UserCA:
return []services.CertAuthType{services.UserCA}
}
return nil
}
// CheckAndSetDefaults checks and sets default values.
func (r *RotateRequest) CheckAndSetDefaults(clock clockwork.Clock) error {
if r.TargetPhase == "" {
// if phase if not set, imply that the first meaningful phase
// is set as a target phase
r.TargetPhase = services.RotationPhaseInit
}
// if mode is not set, default to manual (as it's safer)
if r.Mode == "" {
r.Mode = services.RotationModeManual
}
switch r.Type {
case "", services.HostCA, services.UserCA:
default:
return trace.BadParameter("unsupported certificate authority type: %q", r.Type)
}
if r.GracePeriod == nil {
period := defaults.RotationGracePeriod
r.GracePeriod = &period
}
if r.Schedule == nil {
var err error
r.Schedule, err = services.GenerateSchedule(clock, *r.GracePeriod)
if err != nil {
return trace.Wrap(err)
}
} else {
if err := r.Schedule.CheckAndSetDefaults(clock); err != nil {
return trace.Wrap(err)
}
}
return nil
}
// rotationReq is an internal rotation requrest
type rotationReq struct {
// clock implements test or real wall clock
clock clockwork.Clock
// ca is a certificate authority to rotate
ca services.CertAuthority
// targetPhase is a target rotation phase to set
targetPhase string
// mode is a rotation mode
mode string
// gracePeriod is a rotation grace period
gracePeriod time.Duration
// schedule is a schedule to set
schedule services.RotationSchedule
// privateKey is passed by tests to supply private key for cert authorities
// instead of generating them on each iteration
privateKey []byte
}
// RotateCertAuthority starts or restarts certificate authority rotation process.
//
// Rotation procedure is based on the state machine approach.
//
// Here are the supported rotation states:
//
// * Standby - the cluster is in standby mode and ready to take action.
// * In-progress - cluster CA rotation is in progress.
//
// In-progress state is split into multiple phases and the cluster
// can traverse between phases using supported transitions.
//
// Here are the supported phases:
//
// * Standby - no action is taken.
//
// * Init - New CAs are issued, but all internal system clients
// and servers are still using the old certificates. New CAs are trusted,
// but are not used. New components that are joining the cluster
// are issued certificates signed by "old" CAs.
//
// This phase is necessary for remote clusters to fetch new certificate authorities,
// otherwise remote clusters will be locked out, because they won't have a chance
// to discover the new certificate authorities to be issued.
//
// * Update Clients - All internal system clients
// have to reconnect and receive the new credentials, but all servers
// TLS, SSH and Proxies will still use old credentials.
// Certs from old CA and new CA are trusted within the system.
// This phase is necessary because old clients should receive new credentials
// from the auth servers. If this phase did not exist, old clients could not
// trust servers serving new credentials, because old clients did not receive
// new information yet. It is possible to transition from this phase to phase
// "Update servers" or "Rollback".
//
// * Update Servers - triggers all internal system components to reload and use
// new credentials both in the internal clients and servers, however
// old CA issued credentials are still trusted. This is done to make it possible
// for old components to be trusted within the system, to make rollback possible.
// It is possible to transition from this phase to "Rollback" or "Standby".
// When transitioning to "Standby" phase, the rotation is considered completed,
// old CA is removed from the system and components reload again,
// but this time they don't trust old CA any more.
//
// * Rollback phase is used to revert any changes. When going to rollback phase
// the newly issued CA is no longer used, but set up as trusted,
// so components can reload and receive credentials issued by "old" CA back.
// This phase is useful when administrator makes a mistake, or there are some
// offline components that will loose the connection in case if rotation
// completes. It is only possible to transition from this phase to "Standby".
// When transitioning to "Standby" phase from "Rollback" phase, all components
// reload again, but the "new" CA is discarded and is no longer trusted,
// cluster goes back to the original state.
//
// Rotation modes
//
// There are two rotation modes supported - manual or automatic.
//
// * Manual mode allows administrators to transition between
// phases explicitly setting a phase on every request.
//
// * Automatic mode performs automatic transition between phases
// on a given schedule. Schedule is a time table
// that specifies exact date when the next phase should take place. If automatic
// transition between any phase fails, the rotation switches back to the manual
// mode and stops execution phases on the schedule. If schedule is not specified,
// it will be auto generated based on the "grace period" duration parameter,
// and time between all phases will be evenly split over the grace period duration.
//
// It is possible to switch from automatic to manual by setting the phase
// to the rollback phase.
//
func (a *AuthServer) RotateCertAuthority(req RotateRequest) error {
if err := req.CheckAndSetDefaults(a.clock); err != nil {
return trace.Wrap(err)
}
clusterName := a.clusterName.GetClusterName()
caTypes := req.Types()
for _, caType := range caTypes {
existing, err := a.GetCertAuthority(services.CertAuthID{
Type: caType,
DomainName: clusterName,
}, true)
if err != nil {
return trace.Wrap(err)
}
rotated, err := processRotationRequest(rotationReq{
ca: existing,
clock: a.clock,
targetPhase: req.TargetPhase,
schedule: *req.Schedule,
gracePeriod: *req.GracePeriod,
mode: req.Mode,
privateKey: a.privateKey,
})
if err != nil {
return trace.Wrap(err)
}
if err := a.CompareAndSwapCertAuthority(rotated, existing); err != nil {
return trace.Wrap(err)
}
rotation := rotated.GetRotation()
switch rotation.State {
case services.RotationStateInProgress:
log.WithFields(logrus.Fields{"type": caType}).Infof("Updated rotation state, set current phase to: %q.", rotation.Phase)
case services.RotationStateStandby:
log.WithFields(logrus.Fields{"type": caType}).Infof("Updated and completed rotation.")
}
}
return nil
}
// RotateExternalCertAuthority rotates external certificate authority,
// this method is called by remote trusted cluster and is used to update
// only public keys and certificates of the certificate authority.
func (a *AuthServer) RotateExternalCertAuthority(ca services.CertAuthority) error {
if ca == nil {
return trace.BadParameter("missing certificate authority")
}
// this is just an extra precaution against local admins,
// because this is additionally enforced by RBAC as well
if ca.GetClusterName() == a.clusterName.GetClusterName() {
return trace.BadParameter("can not rotate local certificate authority")
}
existing, err := a.GetCertAuthority(services.CertAuthID{
Type: ca.GetType(),
DomainName: ca.GetClusterName(),
}, false)
if err != nil {
return trace.Wrap(err)
}
updated := existing.Clone()
updated.SetCheckingKeys(ca.GetCheckingKeys())
updated.SetTLSKeyPairs(ca.GetTLSKeyPairs())
updated.SetRotation(ca.GetRotation())
// use compare and swap to protect from concurrent updates
// by trusted cluster API
if err := a.CompareAndSwapCertAuthority(updated, existing); err != nil {
return trace.Wrap(err)
}
return nil
}
// autoRotateCertAuthorities automatically rotates cert authorities,
// does nothing if no rotation parameters were set up
// or it is too early to rotate per schedule
func (a *AuthServer) autoRotateCertAuthorities() error {
clusterName := a.clusterName.GetClusterName()
for _, caType := range []services.CertAuthType{services.HostCA, services.UserCA} {
ca, err := a.GetCertAuthority(services.CertAuthID{
Type: caType,
DomainName: clusterName,
}, true)
if err != nil {
return trace.Wrap(err)
}
if err := a.autoRotate(ca); err != nil {
return trace.Wrap(err)
}
}
return nil
}
func (a *AuthServer) autoRotate(ca services.CertAuthority) error {
rotation := ca.GetRotation()
// rotation mode is not automatic, nothing to do
if rotation.Mode != services.RotationModeAuto {
return nil
}
// rotation is not in progress, there is nothing to do
if rotation.State != services.RotationStateInProgress {
return nil
}
logger := log.WithFields(logrus.Fields{"type": ca.GetType()})
var req *rotationReq
switch rotation.Phase {
case services.RotationPhaseInit:
if rotation.Schedule.UpdateClients.After(a.clock.Now()) {
return nil
}
req = &rotationReq{
clock: a.clock,
ca: ca,
targetPhase: services.RotationPhaseUpdateClients,
mode: services.RotationModeAuto,
gracePeriod: rotation.GracePeriod.Duration,
schedule: rotation.Schedule,
}
case services.RotationPhaseUpdateClients:
if rotation.Schedule.UpdateServers.After(a.clock.Now()) {
return nil
}
req = &rotationReq{
clock: a.clock,
ca: ca,
targetPhase: services.RotationPhaseUpdateServers,
mode: services.RotationModeAuto,
gracePeriod: rotation.GracePeriod.Duration,
schedule: rotation.Schedule,
}
case services.RotationPhaseUpdateServers:
if rotation.Schedule.Standby.After(a.clock.Now()) {
return nil
}
req = &rotationReq{
clock: a.clock,
ca: ca,
targetPhase: services.RotationPhaseStandby,
mode: services.RotationModeAuto,
gracePeriod: rotation.GracePeriod.Duration,
schedule: rotation.Schedule,
}
default:
return trace.BadParameter("phase is not supported: %q", rotation.Phase)
}
logger.Infof("Setting rotation phase to %q", req.targetPhase)
rotated, err := processRotationRequest(*req)
if err != nil {
return trace.Wrap(err)
}
if err := a.CompareAndSwapCertAuthority(rotated, ca); err != nil {
return trace.Wrap(err)
}
logger.Infof("Cert authority rotation request is completed")
return nil
}
// processRotationRequest processes rotation request based on the target and
// current phase and state.
func processRotationRequest(req rotationReq) (services.CertAuthority, error) {
rotation := req.ca.GetRotation()
ca := req.ca.Clone()
switch req.targetPhase {
case services.RotationPhaseInit:
// This is the first stage of the rotation - new certificate authorities
// are being generated, but no components are using them yet
switch rotation.State {
case services.RotationStateStandby, "":
default:
return nil, trace.BadParameter("can not initate rotation while another is in progress")
}
if err := startNewRotation(req, ca); err != nil {
return nil, trace.Wrap(err)
}
return ca, nil
case services.RotationPhaseUpdateClients:
// Update client phase clients will start using new credentials
// and servers will use the existing credentials, but will trust clients
// with both old and new credentials.
if rotation.Phase != services.RotationPhaseInit {
return nil, trace.BadParameter(
"can only switch to phase %v from %v, current phase is %v",
services.RotationPhaseUpdateClients,
services.RotationPhaseInit,
rotation.Phase)
}
if err := updateClients(ca, req.mode); err != nil {
return nil, trace.Wrap(err)
}
return ca, nil
case services.RotationPhaseUpdateServers:
// Update server phase uses the new credentials both for servers
// and clients, but still trusts clients with old credentials.
if rotation.Phase != services.RotationPhaseUpdateClients {
return nil, trace.BadParameter(
"can only switch to phase %v from %v, current phase is %v",
services.RotationPhaseUpdateServers,
services.RotationPhaseUpdateClients,
rotation.Phase)
}
// Signal nodes to restart and start serving new signatures
// by updating the phase.
rotation.Phase = req.targetPhase
rotation.Mode = req.mode
ca.SetRotation(rotation)
return ca, nil
case services.RotationPhaseRollback:
// Rollback moves back both clients and servers to use the old credentials
// but will trust new credentials.
switch rotation.Phase {
case services.RotationPhaseInit, services.RotationPhaseUpdateClients, services.RotationPhaseUpdateServers:
if err := startRollingBackRotation(ca); err != nil {
return nil, trace.Wrap(err)
}
return ca, nil
default:
return nil, trace.BadParameter("can not transition to phase %q from %q phase.", req.targetPhase, rotation.Phase)
}
case services.RotationPhaseStandby:
// Transition to the standby phase moves rotation process
// to standby, servers will only trust one certificate authority.
switch rotation.Phase {
case services.RotationPhaseUpdateServers, services.RotationPhaseRollback:
if err := completeRotation(req.clock, ca); err != nil {
return nil, trace.Wrap(err)
}
return ca, nil
default:
return nil, trace.BadParameter(
"can only switch to phase %v from %v, current phase is %v",
services.RotationPhaseUpdateServers,
services.RotationPhaseUpdateClients,
rotation.Phase)
}
default:
return nil, trace.BadParameter("unsupported phase: %q", req.targetPhase)
}
}
// startNewRotation starts new rotation and updates the certificate
// authority with new CA keys.
func startNewRotation(req rotationReq, ca services.CertAuthority) error {
clock := req.clock
gracePeriod := req.gracePeriod
rotation := ca.GetRotation()
id := uuid.New()
rotation.Mode = req.mode
rotation.Schedule = req.schedule
var sshPrivPEM, sshPubPEM []byte
var keyPEM, certPEM []byte
// generate keys and certificates:
if len(req.privateKey) != 0 {
log.Infof("Generating CA, using pregenerated test private key.")
rsaKey, err := ssh.ParseRawPrivateKey(req.privateKey)
if err != nil {
return trace.Wrap(err)
}
signer, err := ssh.NewSignerFromKey(rsaKey)
if err != nil {
return trace.Wrap(err)
}
sshPubPEM = ssh.MarshalAuthorizedKey(signer.PublicKey())
sshPrivPEM = req.privateKey
keyPEM, certPEM, err = tlsca.GenerateSelfSignedCAWithPrivateKey(rsaKey.(*rsa.PrivateKey), pkix.Name{
CommonName: ca.GetClusterName(),
Organization: []string{ca.GetClusterName()},
}, nil, defaults.CATTL)
if err != nil {
return trace.Wrap(err)
}
} else {
var err error
sshPrivPEM, sshPubPEM, err = native.GenerateKeyPair("")
if err != nil {
return trace.Wrap(err)
}
keyPEM, certPEM, err = tlsca.GenerateSelfSignedCA(pkix.Name{
CommonName: ca.GetClusterName(),
Organization: []string{ca.GetClusterName()},
}, nil, defaults.CATTL)
if err != nil {
return trace.Wrap(err)
}
}
tlsKeyPair := &services.TLSKeyPair{
Cert: certPEM,
Key: keyPEM,
}
// rotate the certificate authority:
rotation.Started = clock.Now().UTC()
rotation.GracePeriod = services.NewDuration(gracePeriod)
rotation.CurrentID = id
signingKeys := ca.GetSigningKeys()
checkingKeys := ca.GetCheckingKeys()
keyPairs := ca.GetTLSKeyPairs()
// Drop old certificate authority without keeping it as trusted.
if gracePeriod == 0 {
signingKeys = [][]byte{sshPrivPEM}
checkingKeys = [][]byte{sshPubPEM}
keyPairs = []services.TLSKeyPair{*tlsKeyPair}
// In case of forced rotation, rotation has been started and completed
// in the same step moving it to standby state.
rotation.State = services.RotationStateStandby
rotation.Phase = services.RotationPhaseStandby
} else {
// Initial phase of rotation keeps old CAs as primary signing key
// pairs, and generates new CAs that are trusted, but not used in the cluster.
signingKeys = [][]byte{signingKeys[0], sshPrivPEM}
checkingKeys = [][]byte{checkingKeys[0], sshPubPEM}
keyPairs = []services.TLSKeyPair{keyPairs[0], *tlsKeyPair}
rotation.State = services.RotationStateInProgress
rotation.Phase = services.RotationPhaseInit
}
ca.SetSigningKeys(signingKeys)
ca.SetCheckingKeys(checkingKeys)
ca.SetTLSKeyPairs(keyPairs)
ca.SetRotation(rotation)
return nil
}
// updateClients swaps old and new cert authorities:
//
// * old CAs exist and are trusted, but are not used for signing
// * the new CAs are now used for signing
// * remote components will reload with new certificates used for client connections
//
func updateClients(ca services.CertAuthority, mode string) error {
rotation := ca.GetRotation()
signingKeys := ca.GetSigningKeys()
checkingKeys := ca.GetCheckingKeys()
keyPairs := ca.GetTLSKeyPairs()
signingKeys = [][]byte{signingKeys[1], signingKeys[0]}
checkingKeys = [][]byte{checkingKeys[1], checkingKeys[0]}
keyPairs = []services.TLSKeyPair{keyPairs[1], keyPairs[0]}
rotation.State = services.RotationStateInProgress
rotation.Phase = services.RotationPhaseUpdateClients
rotation.Mode = mode
ca.SetSigningKeys(signingKeys)
ca.SetCheckingKeys(checkingKeys)
ca.SetTLSKeyPairs(keyPairs)
ca.SetRotation(rotation)
return nil
}
// startRollingBackRotation starts roll back to the original state.
func startRollingBackRotation(ca services.CertAuthority) error {
rotation := ca.GetRotation()
// Rollback always sets rotation to manual mode.
rotation.Mode = services.RotationModeManual
signingKeys := ca.GetSigningKeys()
checkingKeys := ca.GetCheckingKeys()
keyPairs := ca.GetTLSKeyPairs()
// Rotation sets the first key to be the new key
// and keep only public keys/certs for the new CA.
signingKeys = [][]byte{signingKeys[1]}
checkingKeys = [][]byte{checkingKeys[1]}
// Keep the new certificate as trusted
// as during the rollback phase, both types of clients may be present in the cluster.
keyPairs = []services.TLSKeyPair{keyPairs[1], services.TLSKeyPair{Cert: keyPairs[0].Cert}}
rotation.State = services.RotationStateInProgress
rotation.Phase = services.RotationPhaseRollback
ca.SetSigningKeys(signingKeys)
ca.SetCheckingKeys(checkingKeys)
ca.SetTLSKeyPairs(keyPairs)
ca.SetRotation(rotation)
return nil
}
// completeRollingBackRotation completes rollback of the rotation and sets it to the standby state
func completeRollingBackRotation(clock clockwork.Clock, ca services.CertAuthority) error {
rotation := ca.GetRotation()
// clean up the state
rotation.Started = time.Time{}
rotation.State = services.RotationStateStandby
rotation.Phase = services.RotationPhaseStandby
rotation.Mode = ""
rotation.Schedule = services.RotationSchedule{}
keyPairs := ca.GetTLSKeyPairs()
// only keep the original certificate authority as trusted
// and remove everything else.
keyPairs = []services.TLSKeyPair{keyPairs[0]}
ca.SetTLSKeyPairs(keyPairs)
ca.SetRotation(rotation)
return nil
}
// completeRotation completes the certificate authority rotation.
func completeRotation(clock clockwork.Clock, ca services.CertAuthority) error {
rotation := ca.GetRotation()
signingKeys := ca.GetSigningKeys()
checkingKeys := ca.GetCheckingKeys()
keyPairs := ca.GetTLSKeyPairs()
signingKeys = signingKeys[:1]
checkingKeys = checkingKeys[:1]
keyPairs = keyPairs[:1]
rotation.Started = time.Time{}
rotation.State = services.RotationStateStandby
rotation.Phase = services.RotationPhaseStandby
rotation.LastRotated = clock.Now()
rotation.Mode = ""
rotation.Schedule = services.RotationSchedule{}
ca.SetSigningKeys(signingKeys)
ca.SetCheckingKeys(checkingKeys)
ca.SetTLSKeyPairs(keyPairs)
ca.SetRotation(rotation)
return nil
}