...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package physicalmachine
17
18 import (
19 "crypto"
20 "crypto/x509"
21 "os"
22
23 "github.com/pkg/errors"
24 "github.com/spf13/cobra"
25 )
26
27 type PhysicalMachineGenerateOptions struct {
28 outputPath string
29 caCertFile string
30 caKeyFile string
31 }
32
33 func NewPhysicalMachineGenerateCmd() (*cobra.Command, error) {
34 generateOption := &PhysicalMachineGenerateOptions{}
35
36 generateCmd := &cobra.Command{
37 Use: `generate`,
38 Short: `Generate TLS certs for certain physical machine`,
39 Long: `Generate TLS certs for certain physical machine (please execute this command on the certain physical machine)`,
40 SilenceErrors: true,
41 SilenceUsage: true,
42 RunE: func(cmd *cobra.Command, args []string) error {
43 if err := generateOption.Validate(); err != nil {
44 return err
45 }
46 return generateOption.Run()
47 },
48 }
49 generateCmd.PersistentFlags().StringVar(&generateOption.outputPath, "path", "/etc/chaosd/pki", "path to save generated certs")
50 generateCmd.PersistentFlags().StringVar(&generateOption.caCertFile, "cacert", "", "file path to cacert file")
51 generateCmd.PersistentFlags().StringVar(&generateOption.caKeyFile, "cakey", "", "file path to cakey file")
52 return generateCmd, nil
53 }
54
55 func (o *PhysicalMachineGenerateOptions) Validate() error {
56 if len(o.caCertFile) == 0 {
57 return errors.New("--cacert must be specified")
58 }
59 if len(o.caKeyFile) == 0 {
60 return errors.New("--cakey must be specified")
61 }
62 return nil
63 }
64
65 func (o *PhysicalMachineGenerateOptions) Run() error {
66 caCert, caKey, err := GetChaosdCAFileFromFile(o.caCertFile, o.caKeyFile)
67 if err != nil {
68 return err
69 }
70
71 serverCert, serverKey, err := NewCertAndKey(caCert, caKey)
72 if err != nil {
73 return err
74 }
75
76 return WriteCertAndKey(o.outputPath, ChaosdPkiName, serverCert, serverKey)
77 }
78
79 func GetChaosdCAFileFromFile(caCertFile, caKeyFile string) (*x509.Certificate, crypto.Signer, error) {
80 certData, err := os.ReadFile(caCertFile)
81 if err != nil {
82 return nil, nil, errors.Wrap(err, "cannot read cert file")
83 }
84
85 keyData, err := os.ReadFile(caKeyFile)
86 if err != nil {
87 return nil, nil, errors.Wrap(err, "cannot read private key file")
88 }
89 return ParseCertAndKey(certData, keyData)
90 }
91