-
Notifications
You must be signed in to change notification settings - Fork 71
/
rotate-keys.go
289 lines (230 loc) · 7.14 KB
/
rotate-keys.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
package main
import (
"fmt"
"path/filepath"
"time"
"github.com/foxboron/go-uefi/efi"
"github.com/foxboron/go-uefi/efi/signature"
"github.com/foxboron/go-uefi/efi/util"
"github.com/foxboron/sbctl"
"github.com/foxboron/sbctl/fs"
"github.com/foxboron/sbctl/hierarchy"
"github.com/foxboron/sbctl/logging"
"github.com/foxboron/sbctl/stringset"
"github.com/spf13/cobra"
)
type RotateKeysCmdOptions struct {
BackupDir string
NewKeysDir string
Partial stringset.StringSet
KeyFile string
CertFile string
}
var (
rotateKeysCmdOptions = RotateKeysCmdOptions{
Partial: stringset.StringSet{Allowed: []string{hierarchy.PK.String(), hierarchy.KEK.String(), hierarchy.Db.String()}},
}
rotateKeysCmd = &cobra.Command{
Use: "rotate-keys",
Short: "Rotate secure boot keys with new keys.",
RunE: RunRotateKeys,
}
)
type KeyCertPair struct {
Key []byte
Cert []byte
}
type Keys struct {
PK *KeyCertPair
KEK *KeyCertPair
Db *KeyCertPair
}
func ReadKeysFromDir(src string) (*Keys, error) {
k := Keys{}
var err error
k.PK, err = ReadPair(src, hierarchy.PK)
if err != nil {
return &k, err
}
k.KEK, err = ReadPair(src, hierarchy.KEK)
if err != nil {
return &k, err
}
k.Db, err = ReadPair(src, hierarchy.Db)
if err != nil {
return &k, err
}
return &k, err
}
func ReadPair(src string, hierarchy hierarchy.Hierarchy) (*KeyCertPair, error) {
var (
k KeyCertPair
err error
)
k.Key, err = fs.ReadFile(filepath.Join(src, hierarchy.String(), fmt.Sprintf("%s.key", hierarchy.String())))
if err != nil {
return &k, err
}
k.Cert, err = fs.ReadFile(filepath.Join(src, hierarchy.String(), fmt.Sprintf("%s.pem", hierarchy.String())))
if err != nil {
return &k, err
}
return &k, err
}
func rotateCerts(hiera hierarchy.Hierarchy, oldCert, newCert []byte, keyCertPair *KeyCertPair) error {
var (
sl *signature.SignatureDatabase
err error
)
switch hiera {
case hierarchy.PK:
sl, err = efi.GetPK()
case hierarchy.KEK:
sl, err = efi.GetKEK()
case hierarchy.Db:
sl, err = efi.Getdb()
}
if err != nil {
return err
}
uuid, err := sbctl.GetGUID()
if err != nil {
return err
}
guid := util.StringToGUID(uuid.String())
cert, err := util.ReadCert(oldCert)
if err != nil {
return err
}
if err = sl.Remove(signature.CERT_X509_GUID, *guid, cert.Raw); err != nil {
return err
}
sl.Append(signature.CERT_X509_GUID, *guid, newCert)
return sbctl.Enroll(sl, keyCertPair.Key, keyCertPair.Cert, hiera.Efivar())
}
func RunRotateKeys(cmd *cobra.Command, args []string) error {
partial := rotateKeysCmdOptions.Partial.Value
// rotate all keys if no specific key should be replaced
if partial == "" {
if err := rotateAllKeys(rotateKeysCmdOptions.BackupDir, rotateKeysCmdOptions.NewKeysDir); err != nil {
return err
}
return nil
}
return rotateKey(partial, rotateKeysCmdOptions.KeyFile, rotateKeysCmdOptions.CertFile)
}
func rotateAllKeys(backupDir, newKeysDir string) error {
oldKeys, err := ReadKeysFromDir(sbctl.KeysPath)
if err != nil {
return fmt.Errorf("can't read old keys from dir: %v", err)
}
if backupDir == "" {
backupDir = filepath.Join("/var/tmp", fmt.Sprintf("sbctl_backup_keys_%d", time.Now().Unix()))
}
if err := sbctl.CopyDirectory(sbctl.KeysPath, backupDir); err != nil {
return err
}
logging.Print("Backed up keys to %s\n", backupDir)
if err := fs.Fs.RemoveAll(sbctl.KeysPath); err != nil {
return fmt.Errorf("failed removing old keys: %v", err)
}
var newKeys *Keys
if newKeysDir == "" {
logging.Print("Creating secure boot keys...")
if err = sbctl.InitializeSecureBootKeys(sbctl.KeysPath); err != nil {
logging.NotOk("")
return fmt.Errorf("couldn't initialize secure boot: %w", err)
}
logging.Ok("")
logging.Println("Secure boot keys created!")
} else {
logging.Print("Importing new secure boot keys from %s...", newKeysDir)
if err := ImportKeysFromDirectory(newKeysDir); err != nil {
logging.NotOk("")
return fmt.Errorf("couldn't import secure boot: %w", err)
}
logging.Ok("")
logging.Println("Secure boot keys updated!")
}
newKeys, err = ReadKeysFromDir(sbctl.KeysPath)
if err != nil {
return fmt.Errorf("can't read new keys from dir: %v", err)
}
if err := rotateCerts(hierarchy.PK, oldKeys.PK.Cert, newKeys.PK.Cert, oldKeys.PK); err != nil {
return fmt.Errorf("could not rotate PK: %v", err)
}
if err := rotateCerts(hierarchy.KEK, oldKeys.KEK.Cert, newKeys.KEK.Cert, newKeys.PK); err != nil {
return fmt.Errorf("could not rotate KEK: %v", err)
}
if err := rotateCerts(hierarchy.Db, oldKeys.Db.Cert, newKeys.Db.Cert, newKeys.KEK); err != nil {
return fmt.Errorf("could not rotate db: %v", err)
}
logging.Ok("Enrolled new keys into UEFI!")
if err := SignAll(); err != nil {
return fmt.Errorf("failed resigning files: %v", err)
}
return nil
}
func rotateKey(hiera string, keyPath, certPath string) error {
if keyPath == "" {
return fmt.Errorf("a new key needs to be provided for a partial reset of %s", hiera)
}
if certPath == "" {
return fmt.Errorf("a new certificate needs to be provided for a partial reset of %s", hiera)
}
oldKeys, err := ReadKeysFromDir(sbctl.KeysPath)
if err != nil {
return fmt.Errorf("can't read old keys from dir: %v", err)
}
newCert, err := fs.ReadFile(certPath)
if err != nil {
return fmt.Errorf("can't read new certificate from path %s: %v", certPath, err)
}
var (
importKeyDst string
importCertDst string
)
switch hiera {
case hierarchy.PK.String():
if err := rotateCerts(hierarchy.PK, oldKeys.PK.Cert, newCert, oldKeys.PK); err != nil {
return fmt.Errorf("could not rotate PK: %v", err)
}
importKeyDst = sbctl.PKKey
importCertDst = sbctl.PKCert
case hierarchy.KEK.String():
if err := rotateCerts(hierarchy.KEK, oldKeys.KEK.Cert, newCert, oldKeys.PK); err != nil {
return fmt.Errorf("could not rotate KEK: %v", err)
}
importKeyDst = sbctl.KEKKey
importCertDst = sbctl.KEKCert
case hierarchy.Db.String():
if err := rotateCerts(hierarchy.Db, oldKeys.Db.Cert, newCert, oldKeys.KEK); err != nil {
return fmt.Errorf("could not rotate db: %v", err)
}
importKeyDst = sbctl.DBKey
importCertDst = sbctl.DBCert
}
logging.Ok("Enrolled new key of hierarchy %s into UEFI!", hiera)
// import new key and certificate
if err = Import(keyPath, importKeyDst); err != nil {
return fmt.Errorf("could not replace key: %s", err)
}
if err = Import(certPath, importCertDst); err != nil {
return fmt.Errorf("could not replace certificate: %s", err)
}
return nil
}
func rotateKeysCmdFlags(cmd *cobra.Command) {
f := cmd.Flags()
f.StringVarP(&rotateKeysCmdOptions.BackupDir, "backup-dir", "b", "", "Backup keys to directory")
f.StringVarP(&rotateKeysCmdOptions.NewKeysDir, "new-keys-dir", "n", "", "Provide new keys to enroll by directory")
f.VarPF(&rotateKeysCmdOptions.Partial, "partial", "p", "rotate a key of a specific hierarchy")
f.StringVarP(&rotateKeysCmdOptions.KeyFile, "key-file", "k", "", "key file to replace (only with partial flag)")
f.StringVarP(&rotateKeysCmdOptions.CertFile, "cert-file", "c", "", "certificate file to replace (only with partial flag)")
}
func init() {
rotateKeysCmdFlags(rotateKeysCmd)
CliCommands = append(CliCommands, cliCommand{
Cmd: rotateKeysCmd,
})
}