/
attestation.go
590 lines (521 loc) · 17.1 KB
/
attestation.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
//go:build !ghmcli
// +build !ghmcli
package main
import (
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"github.com/HermitMatrixNetwork/HermitMatrixNetwork/go-cosmwasm/api"
reg "github.com/HermitMatrixNetwork/HermitMatrixNetwork/x/registration"
ra "github.com/HermitMatrixNetwork/HermitMatrixNetwork/x/registration/remote_attestation"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/server"
"github.com/cosmos/cosmos-sdk/x/genutil"
genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types"
"github.com/spf13/cobra"
"io/ioutil"
"os"
"path/filepath"
)
const flagReset = "reset"
const flagPulsar = "pulsar"
const flagCustomRegistrationService = "registration-service"
const flagLegacyRegistrationNode = "registration-node"
const flagLegacyBootstrapNode = "node"
//const mainnetRegistrationService = "https://mainnet-register.scrtlabs.com/api/registernode"
//const pulsarRegistrationService = "https://testnet-register.scrtlabs.com/api/registernode"
func InitAttestation() *cobra.Command {
cmd := &cobra.Command{
Use: "init-enclave [output-file]",
Short: "Perform remote attestation of the enclave",
Long: `Create attestation report, signed by Intel which is used in the registation process of
the node to the chain. This process, if successful, will output a certificate which is used to authenticate with the
blockchain. Writes the certificate in DER format to ~/attestation_cert
`,
Args: cobra.ExactArgs(0),
RunE: func(cmd *cobra.Command, args []string) error {
sgxSecretsDir := os.Getenv("GHM_SGX_STORAGE")
if sgxSecretsDir == "" {
sgxSecretsDir = os.ExpandEnv("/opt/ghm/.sgx_ghms")
}
// create sgx secrets dir if it doesn't exist
if _, err := os.Stat(sgxSecretsDir); !os.IsNotExist(err) {
err := os.MkdirAll(sgxSecretsDir, 0777)
if err != nil {
return err
}
}
sgxSecretsPath := sgxSecretsDir + string(os.PathSeparator) + reg.EnclaveRegistrationKey
resetFlag, err := cmd.Flags().GetBool(flagReset)
if err != nil {
return fmt.Errorf("error with reset flag: %s", err)
}
if !resetFlag {
if _, err := os.Stat(sgxSecretsPath); os.IsNotExist(err) {
fmt.Println("Creating new enclave registration key")
_, err := api.KeyGen()
if err != nil {
return fmt.Errorf("failed to initialize enclave: %w", err)
}
} else {
fmt.Println("Enclave key already exists. If you wish to overwrite and reset the node, use the --reset flag")
}
} else {
fmt.Println("Reset enclave flag set, generating new enclave registration key. You must now re-register the node")
_, err := api.KeyGen()
if err != nil {
return fmt.Errorf("failed to initialize enclave: %w", err)
}
}
spidFile, err := Asset("spid.txt")
if err != nil {
return fmt.Errorf("failed to initialize enclave: %w", err)
}
apiKeyFile, err := Asset("api_key.txt")
if err != nil {
return fmt.Errorf("failed to initialize enclave: %w", err)
}
_, err = api.CreateAttestationReport(spidFile, apiKeyFile)
if err != nil {
return fmt.Errorf("failed to create attestation report: %w", err)
}
return nil
},
}
cmd.Flags().Bool(flagReset, false, "Optional flag to regenerate the enclave registration key")
return cmd
}
func InitBootstrapCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "init-bootstrap [node-exchange-file] [io-exchange-file]",
Short: "Perform bootstrap initialization",
Long: `Create attestation report, signed by Intel which is used in the registration process of
the node to the chain. This process, if successful, will output a certificate which is used to authenticate with the
blockchain. Writes the certificate in DER format to ~/attestation_cert
`,
Args: cobra.MaximumNArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
clientCtx := client.GetClientContextFromCmd(cmd)
depCdc := clientCtx.Codec
cdc := depCdc.(codec.Codec)
serverCtx := server.GetServerContextFromCmd(cmd)
config := serverCtx.Config
genFile := config.GenesisFile()
appState, genDoc, err := genutiltypes.GenesisStateFromGenFile(genFile)
if err != nil {
return fmt.Errorf("failed to unmarshal genesis state: %w", err)
}
regGenState := reg.GetGenesisStateFromAppState(cdc, appState)
spidFile, err := Asset("spid.txt")
if err != nil {
return fmt.Errorf("failed to initialize enclave: %w", err)
}
apiKeyFile, err := Asset("api_key.txt")
if err != nil {
return fmt.Errorf("failed to initialize enclave: %w", err)
}
// the master key of the generated certificate is returned here
masterKey, err := api.InitBootstrap(spidFile, apiKeyFile)
if err != nil {
return fmt.Errorf("failed to initialize enclave: %w", err)
}
userHome, _ := os.UserHomeDir()
// Load consensus_seed_exchange_pubkey
cert := []byte(nil)
if len(args) >= 1 {
cert, err = ioutil.ReadFile(args[0])
if err != nil {
return err
}
} else {
cert, err = ioutil.ReadFile(filepath.Join(userHome, reg.NodeExchMasterCertPath))
if err != nil {
return err
}
}
pubkey, err := ra.VerifyRaCert(cert)
if err != nil {
return err
}
fmt.Println(fmt.Sprintf("%s", hex.EncodeToString(pubkey)))
fmt.Println(fmt.Sprintf("%s", hex.EncodeToString(masterKey)))
// sanity check - make sure the certificate we're using matches the generated key
if hex.EncodeToString(pubkey) != hex.EncodeToString(masterKey) {
return fmt.Errorf("invalid certificate for master public key")
}
regGenState.NodeExchMasterCertificate.Bytes = cert
// Load consensus_io_exchange_pubkey
if len(args) == 2 {
cert, err = ioutil.ReadFile(args[1])
if err != nil {
return err
}
} else {
cert, err = ioutil.ReadFile(filepath.Join(userHome, reg.IoExchMasterCertPath))
if err != nil {
return err
}
}
regGenState.IoMasterCertificate.Bytes = cert
// Create genesis state from certificates
regGenStateBz, err := cdc.MarshalJSON(®GenState)
if err != nil {
return fmt.Errorf("failed to marshal auth genesis state: %w", err)
}
appState[reg.ModuleName] = regGenStateBz
appStateJSON, err := json.Marshal(appState)
if err != nil {
return fmt.Errorf("failed to marshal application genesis state: %w", err)
}
genDoc.AppState = appStateJSON
return genutil.ExportGenesisFile(genDoc, genFile)
},
}
return cmd
}
func ParseCert() *cobra.Command {
cmd := &cobra.Command{
Use: "parse [cert file]",
Short: "Verify and parse a certificate file",
Long: "Helper to verify generated credentials, and extract the public key of the secret node, which is used to" +
"register the node, during node initialization",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
// parse coins trying to be sent
cert, err := ioutil.ReadFile(args[0])
if err != nil {
return err
}
pubkey, err := ra.VerifyRaCert(cert)
if err != nil {
return err
}
fmt.Println(fmt.Sprintf("0x%s", hex.EncodeToString(pubkey)))
return nil
},
}
return cmd
}
func ConfigureSecret() *cobra.Command {
cmd := &cobra.Command{
Use: "configure-secret [master-cert] [seed]",
Short: "After registration is successful, configure the secret node with the credentials file and the encrypted " +
"seed that was written on-chain",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
cert, err := ioutil.ReadFile(args[0])
if err != nil {
return err
}
// We expect seed to be 48 bytes of encrypted data (aka 96 hex chars) [32 bytes + 12 IV]
seed := args[1]
if len(seed) != reg.EncryptedKeyLength || !reg.IsHexString(seed) {
return fmt.Errorf("invalid encrypted seed format (requires hex string of length 96 without 0x prefix)")
}
cfg := reg.SeedConfig{
EncryptedKey: seed,
MasterCert: base64.StdEncoding.EncodeToString(cert),
}
cfgBytes, err := json.Marshal(&cfg)
if err != nil {
return err
}
homeDir, err := cmd.Flags().GetString(flags.FlagHome)
if err != nil {
return err
}
// Create .ghmd/.node directory if it doesn't exist
nodeDir := filepath.Join(homeDir, reg.SecretNodeCfgFolder)
err = os.MkdirAll(nodeDir, os.ModePerm)
if err != nil {
return err
}
seedFilePath := filepath.Join(nodeDir, reg.SecretNodeSeedConfig)
err = ioutil.WriteFile(seedFilePath, cfgBytes, 0664)
if err != nil {
return err
}
return nil
},
}
return cmd
}
func HealthCheck() *cobra.Command {
cmd := &cobra.Command{
Use: "check-enclave",
Short: "Test enclave status",
Long: "Help diagnose issues by performing a basic sanity test that SGX is working properly",
Args: cobra.ExactArgs(0),
RunE: func(cmd *cobra.Command, args []string) error {
res, err := api.HealthCheck()
if err != nil {
return fmt.Errorf("failed to start enclave. Enclave returned: %s", err)
}
fmt.Println(fmt.Sprintf("SGX enclave health status: %s", res))
return nil
},
}
return cmd
}
func ResetEnclave() *cobra.Command {
cmd := &cobra.Command{
Use: "reset-enclave",
Short: "Reset registration & enclave parameters",
Long: "This will delete all registration and enclave parameters. Use when something goes wrong and you want to start fresh." +
"You will have to go through registration again to be able to start the node",
Args: cobra.ExactArgs(0),
RunE: func(cmd *cobra.Command, args []string) error {
homeDir, err := cmd.Flags().GetString(flags.FlagHome)
if err != nil {
return err
}
// Remove .ghmd/.node/seed.json
path := filepath.Join(homeDir, reg.SecretNodeCfgFolder, reg.SecretNodeSeedConfig)
if _, err := os.Stat(path); !os.IsNotExist(err) {
fmt.Printf("Removing %s\n", path)
err = os.Remove(path)
if err != nil {
return err
}
} else {
if err != nil {
println(err.Error())
}
}
// remove sgx_secrets
sgxSecretsDir := os.Getenv("GHM_SGX_STORAGE")
if sgxSecretsDir == "" {
sgxSecretsDir = os.ExpandEnv("/opt/ghm/.sgx_ghms")
}
if _, err := os.Stat(sgxSecretsDir); !os.IsNotExist(err) {
fmt.Printf("Removing %s\n", sgxSecretsDir)
err = os.RemoveAll(sgxSecretsDir)
if err != nil {
return err
}
err := os.MkdirAll(sgxSecretsDir, 0777)
if err != nil {
return err
}
} else {
if err != nil {
println(err.Error())
}
}
return nil
},
}
return cmd
}
type OkayResponse struct {
Status string `json:"status"`
Details KeyVal `json:"details"`
RegistrationKey string `json:"registration_key"`
}
type KeyVal struct {
Key string `json:"key"`
Value string `json:"value"`
}
type ErrorResponse struct {
Status string `json:"status"`
Details string `json:"details"`
}
// AutoRegisterNode *** EXPERIMENTAL ***
func AutoRegisterNode() *cobra.Command {
cmd := &cobra.Command{
Use: "auto-register",
Short: "Perform remote attestation of the enclave",
Long: `Automatically handles all registration processes. ***EXPERIMENTAL***
Please report any issues with this command
`,
Args: cobra.ExactArgs(0),
RunE: func(cmd *cobra.Command, args []string) error {
//sgxSecretsFolder := os.Getenv("GHM_SGX_STORAGE")
//if sgxSecretsFolder == "" {
// sgxSecretsFolder = os.ExpandEnv("/opt/ghm/.sgx_ghms")
//}
//
//sgxEnclaveKeyPath := filepath.Join(sgxSecretsFolder, reg.EnclaveRegistrationKey)
//sgxAttestationCert := filepath.Join(sgxSecretsFolder, reg.AttestationCertPath)
//
//resetFlag, err := cmd.Flags().GetBool(flagReset)
//if err != nil {
// return fmt.Errorf("error with reset flag: %s", err)
//}
//
//if !resetFlag {
// if _, err := os.Stat(sgxEnclaveKeyPath); os.IsNotExist(err) {
// fmt.Println("Creating new enclave registration key")
// _, err := api.KeyGen()
// if err != nil {
// return fmt.Errorf("failed to initialize enclave: %w", err)
// }
// } else {
// fmt.Println("Enclave key already exists. If you wish to overwrite and reset the node, use the --reset flag")
// return nil
// }
//} else {
// fmt.Println("Reset enclave flag set, generating new enclave registration key. You must now re-register the node")
// _, err := api.KeyGen()
// if err != nil {
// return fmt.Errorf("failed to initialize enclave: %w", err)
// }
//}
//
//spidFile, err := Asset("spid.txt")
//if err != nil {
// return fmt.Errorf("failed to initialize enclave: %w", err)
//}
//
//apiKeyFile, err := Asset("api_key.txt")
//if err != nil {
// return fmt.Errorf("failed to initialize enclave: %w", err)
//}
//
//_, err = api.CreateAttestationReport(spidFile, apiKeyFile)
//if err != nil {
// return fmt.Errorf("failed to create attestation report: %w", err)
//}
//
//// read the attestation certificate that we just created
//cert, err := ioutil.ReadFile(sgxAttestationCert)
//if err != nil {
// _ = os.Remove(sgxAttestationCert)
// return err
//}
//
//_ = os.Remove(sgxAttestationCert)
//
//// verify certificate
//_, err = ra.VerifyRaCert(cert)
//if err != nil {
// return err
//}
//
//regUrl := mainnetRegistrationService
//
//pulsarFlag, err := cmd.Flags().GetBool(flagPulsar)
//if err != nil {
// return fmt.Errorf("error with testnet flag: %s", err)
//}
//
//// register the node
//customRegUrl, err := cmd.Flags().GetString(flagCustomRegistrationService)
//if err != nil {
// return err
//}
//
//if pulsarFlag {
// regUrl = pulsarRegistrationService
// log.Println("Registering node on Pulsar testnet")
//} else if customRegUrl != "" {
// regUrl = customRegUrl
// log.Println("Registering node with custom registration service")
//} else {
// log.Println("Registering node on mainnet")
//}
//
//// call registration service to register us
//data := []byte(fmt.Sprintf(`{
// "certificate": "%s"
//}`, base64.StdEncoding.EncodeToString(cert)))
//
//resp, err := http.Post(fmt.Sprintf(`%s`, regUrl), "application/json", bytes.NewBuffer(data))
//defer resp.Body.Close()
//
//body, err := ioutil.ReadAll(resp.Body)
//if err != nil {
// log.Fatalln(err)
//}
//
//if resp.StatusCode != http.StatusOK {
// errDetails := ErrorResponse{}
// err := json.Unmarshal(body, &errDetails)
// if err != nil {
// return fmt.Errorf(fmt.Sprintf("Registration TX was not successful - %s", err))
// }
// return fmt.Errorf(fmt.Sprintf("Registration TX was not successful - %s", errDetails.Details))
//}
//
//details := OkayResponse{}
//err = json.Unmarshal(body, &details)
//if err != nil {
// return fmt.Errorf(fmt.Sprintf("Error getting seed from registration service - %s", err))
//}
//
//seed := details.Details.Value
//log.Printf(fmt.Sprintf(`seed: %s`, seed))
//
//if len(seed) > 2 {
// seed = seed[2:]
//}
//
//if len(seed) != reg.EncryptedKeyLength || !reg.IsHexString(seed) {
// return fmt.Errorf("invalid encrypted seed format (requires hex string of length 96 without 0x prefix)")
//}
//
//regPublicKey := details.RegistrationKey
//
//// We expect seed to be 48 bytes of encrypted data (aka 96 hex chars) [32 bytes + 12 IV]
//
//cfg := reg.SeedConfig{
// EncryptedKey: seed,
// MasterCert: regPublicKey,
//}
//
//cfgBytes, err := json.Marshal(&cfg)
//if err != nil {
// return err
//}
//
//homeDir, err := cmd.Flags().GetString(flags.FlagHome)
//if err != nil {
// return err
//}
//
//seedCfgFile := filepath.Join(homeDir, reg.SecretNodeCfgFolder, reg.SecretNodeSeedConfig)
//seedCfgDir := filepath.Join(homeDir, reg.SecretNodeCfgFolder)
//
//// create seed directory if it doesn't exist
//_, err = os.Stat(seedCfgDir)
//if os.IsNotExist(err) {
// err = os.MkdirAll(seedCfgDir, 0777)
// if err != nil {
// return fmt.Errorf("failed to create directory '%s': %w", seedCfgDir, err)
// }
//}
//
//// write seed to file - if file doesn't exist, write it. If it does, delete the existing one and create this
//_, err = os.Stat(seedCfgFile)
//if os.IsNotExist(err) {
// err = ioutil.WriteFile(seedCfgFile, cfgBytes, 0644)
// if err != nil {
// return err
// }
//} else {
// err = os.Remove(seedCfgFile)
// if err != nil {
// return fmt.Errorf("failed to modify file '%s': %w", seedCfgFile, err)
// }
//
// err = ioutil.WriteFile(seedCfgFile, cfgBytes, 0644)
// if err != nil {
// return fmt.Errorf("failed to create file '%s': %w", seedCfgFile, err)
// }
//}
//
//fmt.Println("Done registering! Ready to start...")
println(" todo impl ... ")
return nil
},
}
cmd.Flags().Bool(flagReset, false, "Optional flag to regenerate the enclave registration key")
cmd.Flags().Bool(flagPulsar, false, "Set --pulsar flag if registering with the Pulsar testnet")
cmd.Flags().String(flagCustomRegistrationService, "", "Use this flag if you wish to specify a custom registration service")
cmd.Flags().String(flagLegacyBootstrapNode, "", "DEPRECATED: This flag is no longer required or in use")
cmd.Flags().String(flagLegacyRegistrationNode, "", "DEPRECATED: This flag is no longer required or in use")
return cmd
}