-
Notifications
You must be signed in to change notification settings - Fork 0
/
genCaParent.go
168 lines (137 loc) · 4.62 KB
/
genCaParent.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
package cmd
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"os"
"time"
"github.com/Open-Remote-I-O/cert_gen_cli/utils"
"github.com/spf13/cobra"
"golang.org/x/sync/errgroup"
)
var (
ParentCertPath string
ParentKeyPath string
ParentCertName string
CaCertFilePath string
CaKeyFilePath string
OrganizationName string
)
func parseCaCertificate() (*x509.Certificate, error) {
rawPemCert, err := os.ReadFile(CaCertFilePath)
if err != nil {
fmt.Println("Error reading CA certificate:", err)
return nil, err
}
decodedCaCert, _ := pem.Decode(rawPemCert)
caCert, err := x509.ParseCertificate(decodedCaCert.Bytes)
if err != nil {
fmt.Println("Error parsing CA certificate:", err)
return nil, err
}
return caCert, nil
}
// genCaParentCertCmd represents the genCaParentCert command
var genCaParentCertCmd = &cobra.Command{
Use: "genCaParentCert",
Short: "create sub certificate from a CA cert",
Long: `creates a keypair for a client using a CA root certificate`,
Run: func(cmd *cobra.Command, args []string) {
caCert, err := parseCaCertificate()
if err != nil {
return
}
rawCaKey, err := os.ReadFile(CaKeyFilePath)
if err != nil {
fmt.Println("Error reading CA key from specified path: \n err:", CaKeyFilePath, err)
return
}
decodedCaKey, _ := pem.Decode(rawCaKey)
parsedCaKey, err := x509.ParsePKCS8PrivateKey(decodedCaKey.Bytes)
if err != nil {
fmt.Println("Error parsing CA key:", err)
return
}
serverPrivKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
fmt.Println("Error generate private key:", err)
return
}
randomSn, err := utils.GenerateRandomThreeBytesSN()
if err != nil {
fmt.Println("Error while generating random CA serial number:", err)
return
}
if OrganizationName == "" {
OrganizationName = utils.InputPrompt("Input your organization name:")
}
serverCertTmpl := x509.Certificate{
SerialNumber: randomSn,
Subject: pkix.Name{
Organization: []string{OrganizationName},
},
NotBefore: time.Now(),
NotAfter: time.Now().Add(365 * 24 * time.Hour),
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth},
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
IsCA: true,
BasicConstraintsValid: true,
Issuer: caCert.Issuer,
}
errGroup := new(errgroup.Group)
errGroup.Go(func() error {
serverCert, err := x509.CreateCertificate(
rand.Reader,
&serverCertTmpl,
caCert,
serverPrivKey.Public(),
parsedCaKey,
)
if err != nil {
return err
}
certPem := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: serverCert})
if err = os.WriteFile(utils.GenFilePath(ParentCertPath, ParentCertName, crtFileExtension), certPem, 0644); err != nil {
return err
}
return nil
})
errGroup.Go(func() error {
// Encode server private key in PEM format
binServerPrivKey, err := x509.MarshalECPrivateKey(serverPrivKey)
if err != nil {
return err
}
privKeyPem := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: binServerPrivKey})
// Write server certificate and key to files
if err = os.WriteFile(utils.GenFilePath(ParentKeyPath, ParentCertName, keyFileExtension), privKeyPem, 0644); err != nil {
return err
}
return nil
})
if err := errGroup.Wait(); err != nil {
// Cleanup eventual leftovers
fmt.Println("Error occured while generating keypair", err)
fmt.Println("Cleaning up leftovers...")
os.Remove(utils.GenFilePath(ParentCertPath, ParentCertName, keyFileExtension))
os.Remove(utils.GenFilePath(ParentKeyPath, ParentCertName, keyFileExtension))
return
}
fmt.Println("Successfully generated parent keypair from CA keypair")
},
}
func init() {
rootCmd.AddCommand(genCaParentCertCmd)
genCaParentCertCmd.Flags().StringVar(&ParentCertPath, "cert-out", "./", "output path for new parent certificate.")
genCaParentCertCmd.Flags().StringVar(&ParentKeyPath, "key-out", "./", "output path for new parent private key.")
genCaParentCertCmd.Flags().StringVarP(&ParentCertName, "name", "n", "client", `ca cert and key name.`)
genCaParentCertCmd.Flags().StringVarP(&CaCertFilePath, "ca-cert-path", "c", "./ca.crt", `path to read the ca cert from.`)
genCaParentCertCmd.Flags().
StringVarP(&CaKeyFilePath, "ca-key-path", "k", "./ca.key", `path to read the ca private key from.`)
genCaParentCertCmd.Flags().
StringVar(&OrganizationName, "organization-name", "", `organization name to have in the newly generated certificate.`)
}