-
Notifications
You must be signed in to change notification settings - Fork 61
/
result_writer.go
424 lines (373 loc) · 11 KB
/
result_writer.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
/*
* Copyright 2018-2021 Venafi, 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 main
import (
"bytes"
"crypto/rand"
"crypto/x509"
"encoding/json"
"encoding/pem"
"fmt"
"io/ioutil"
"os"
"strings"
"time"
"github.com/Venafi/vcert/v4/pkg/certificate"
"github.com/pavel-v-chernykh/keystore-go/v4"
"software.sslmate.com/src/go-pkcs12"
)
type Config struct {
Command string
Format string
JKSAlias string
JKSPassword string
ChainOption certificate.ChainOption
AllFile string
KeyFile string
CertFile string
CSRFile string
ChainFile string
PickupIdFile string
KeyPassword string
}
type Result struct {
Pcc *certificate.PEMCollection
PickupId string
Config *Config
}
type Output struct {
Certificate string `json:",omitempty"`
CSR string `json:",omitempty"`
PrivateKey string `json:",omitempty"`
Chain []string `json:",omitempty"`
PickupId string `json:",omitempty"`
}
//nolint
func (o *Output) AsPKCS12(c *Config) ([]byte, error) {
if len(o.Certificate) == 0 || len(o.PrivateKey) == 0 {
return nil, fmt.Errorf("at least certificate and private key are required")
}
p, _ := pem.Decode([]byte(o.Certificate))
if p == nil || p.Type != "CERTIFICATE" {
return nil, fmt.Errorf("certificate parse error(1)")
}
cert, err := x509.ParseCertificate(p.Bytes)
if err != nil {
return nil, fmt.Errorf("certificate parse error(2)")
}
// chain?
var chain_list = []*x509.Certificate{}
for _, chain_cert := range o.Chain {
crt, _ := pem.Decode([]byte(chain_cert))
cert, err := x509.ParseCertificate(crt.Bytes)
if err != nil {
return nil, fmt.Errorf("chain certificate parse error")
}
chain_list = append(chain_list, cert)
}
// key?
p, _ = pem.Decode([]byte(o.PrivateKey))
if p == nil {
return nil, fmt.Errorf("missing private key PEM")
}
var privDER []byte
if x509.IsEncryptedPEMBlock(p) {
privDER, err = x509.DecryptPEMBlock(p, []byte(c.KeyPassword))
if err != nil {
return nil, fmt.Errorf("private key PEM decryption error: %s", err)
}
} else {
privDER = p.Bytes
}
var privKey interface{}
switch p.Type {
case "EC PRIVATE KEY":
privKey, err = x509.ParseECPrivateKey(privDER)
case "RSA PRIVATE KEY":
privKey, err = x509.ParsePKCS1PrivateKey(privDER)
if err != nil {
privKey, err = x509.ParsePKCS8PrivateKey(privDER)
}
default:
return nil, fmt.Errorf("unexpected private key PEM type: %s", p.Type)
}
if err != nil {
return nil, fmt.Errorf("private key error(3): %s", err)
}
bytes, err := pkcs12.Encode(rand.Reader, privKey, cert, chain_list, c.KeyPassword)
if err != nil {
return nil, fmt.Errorf("encode error: %s", err)
}
return bytes, nil
}
//nolint
func (o *Output) AsJKS(c *Config) ([]byte, error) {
var err interface{}
if len(o.Certificate) == 0 || len(o.PrivateKey) == 0 {
return nil, fmt.Errorf("at least certificate and private key are required")
}
var certificateChain []keystore.Certificate
//getting the certificate in bytes
p, _ := pem.Decode([]byte(o.Certificate))
if p == nil || p.Type != "CERTIFICATE" {
return nil, fmt.Errorf("certificate parse error(1)")
}
var certInBytes = p.Bytes
//adding the certificates to the slice of Certificates
certificateChain = append(certificateChain, keystore.Certificate{
Type: "X509",
Content: certInBytes,
})
// getting each one of the certificates in the chain of certificates and adding their bytes to the chain of certificates
for _, chainCert := range o.Chain {
crt, _ := pem.Decode([]byte(chainCert))
certificateChain = append(certificateChain, keystore.Certificate{
Type: "X509",
Content: crt.Bytes,
})
}
// getting the bytes of the PK
p, _ = pem.Decode([]byte(o.PrivateKey))
if p == nil {
return nil, fmt.Errorf("missing private key PEM")
}
var privDER []byte
//decrypting the PK because due the restriction that always will be requested the key password
//to the user(--key-password or pass phrase value from prompt) for jks format then the PK always
//will be encrypted with the key password provided
if x509.IsEncryptedPEMBlock(p) {
privDER, err = x509.DecryptPEMBlock(p, []byte(c.KeyPassword))
if err != nil {
return nil, fmt.Errorf("private key PEM decryption error: %s", err)
}
} else {
privDER = p.Bytes
}
//Unmarshalling the PK
var privKey interface{}
switch p.Type {
case "EC PRIVATE KEY":
privKey, err = x509.ParseECPrivateKey(privDER)
case "RSA PRIVATE KEY":
privKey, err = x509.ParsePKCS1PrivateKey(privDER)
if err != nil {
privKey, err = x509.ParsePKCS8PrivateKey(privDER)
}
default:
return nil, fmt.Errorf("unexpected private key PEM type: %s", p.Type)
}
if err != nil {
return nil, fmt.Errorf("private key error(3): %s", err)
}
//Marshalling the PK to PKCS8, which is mandatory for JKS format
pkcs8DER, _ := x509.MarshalPKCS8PrivateKey(privKey)
//creating a JKS
keyStore := keystore.New()
//creating a PK entry
pkeIn := keystore.PrivateKeyEntry{
CreationTime: time.Now(),
PrivateKey: pkcs8DER,
CertificateChain: certificateChain,
}
//adding the PK entry to the JKS. Setting as keyPass the value from keyPassword(--key-password or pass phrase value)
if err := keyStore.SetPrivateKeyEntry(c.JKSAlias, pkeIn, []byte(c.KeyPassword)); err != nil {
return nil, fmt.Errorf("JKS private key error: %s", err)
}
buffer := new(bytes.Buffer)
var storePass []byte
//setting as storePass the value in --jks-password or the value from keyPassword( --key-password or pass phrase value)
if c.JKSPassword != "" {
storePass = []byte(c.JKSPassword)
} else {
storePass = []byte(c.KeyPassword)
}
//storing the JKS to the buffer
err = keyStore.Store(buffer, storePass)
if err != nil {
return nil, fmt.Errorf("JKS keystore error: %s", err) //log.Fatal(err) // nolint: gocritic
}
return buffer.Bytes(), nil
}
func (o *Output) Format(c *Config) ([]byte, error) {
switch strings.ToLower(c.Format) {
case "json":
b, err := json.Marshal(o)
if err != nil {
return nil, fmt.Errorf("failed to construct JSON: %s", err)
}
return b, nil
default: // pem
res := ""
switch c.ChainOption {
case certificate.ChainOptionRootFirst:
res += strings.Join(o.Chain, "")
res += o.Certificate
res += o.PrivateKey
case certificate.ChainOptionIgnore:
res += o.Certificate
res += o.PrivateKey
default:
res += o.Certificate
res += o.CSR
res += o.PrivateKey
res += strings.Join(o.Chain, "")
}
if o.PickupId != "" {
res += fmt.Sprintf("PickupID=\"%s\"\n", o.PickupId)
}
return []byte(res), nil
}
}
// this formatter mirrors previous logic of writing JSON/PEM to -*-file files
func (r *Result) format(x string) string {
if strings.ToLower(r.Config.Format) == "json" {
b, _ := json.Marshal(x)
return string(b)
} else {
return x
}
}
func (r *Result) formatChain(xs []string) string {
if strings.ToLower(r.Config.Format) == "json" {
b, _ := json.Marshal(xs)
return string(b)
} else {
var s string
for _, v := range xs {
s += v
}
return s
}
}
func (r *Result) Flush() error {
var err error
var errors []error
if r.Pcc == nil {
return fmt.Errorf("couldn't construct output: certificate collection is null")
}
stdOut := &Output{}
if r.Config.AllFile != "" {
allFileOutput := &Output{}
allFileOutput.PrivateKey = r.Pcc.PrivateKey
allFileOutput.Certificate = r.Pcc.Certificate
allFileOutput.Chain = r.Pcc.Chain
allFileOutput.CSR = r.Pcc.CSR
var bytes []byte
if r.Config.Format == "pkcs12" {
bytes, err = allFileOutput.AsPKCS12(r.Config)
if err != nil {
return fmt.Errorf("failed to encode pkcs12: %s", err)
}
} else if r.Config.Format == JKSFormat {
bytes, err = allFileOutput.AsJKS(r.Config)
if err != nil {
return err
}
} else {
bytes, err = allFileOutput.Format(r.Config)
if err != nil {
return err
}
}
err = ioutil.WriteFile(r.Config.AllFile, bytes, 0600)
errors = append(errors, err)
} else {
if r.Config.CertFile != "" && r.Pcc.Certificate != "" {
certFileOutput := &Output{}
certFileOutput.Certificate = r.Pcc.Certificate
if r.Config.ChainFile == "" {
certFileOutput.Chain = r.Pcc.Chain
}
err = writeFile(certFileOutput, r, r.Config.CertFile)
errors = append(errors, err)
} else {
stdOut.Certificate = r.Pcc.Certificate
}
if r.Config.CSRFile != "" && r.Pcc.CSR != "" {
csrFileOutput := &Output{}
csrFileOutput.CSR = r.Pcc.CSR
err = writeFile(csrFileOutput, r, r.Config.CSRFile)
errors = append(errors, err)
} else {
stdOut.CSR = r.Pcc.CSR
}
if r.Config.KeyFile != "" && r.Pcc.PrivateKey != "" {
keyFileOutput := &Output{}
keyFileOutput.PrivateKey = r.Pcc.PrivateKey
err = writeFile(keyFileOutput, r, r.Config.KeyFile)
errors = append(errors, err)
} else {
stdOut.PrivateKey = r.Pcc.PrivateKey
}
if r.Config.ChainFile != "" && len(r.Pcc.Chain) > 0 {
chainFileOutput := &Output{}
chainFileOutput.Chain = r.Pcc.Chain
err = writeFile(chainFileOutput, r, r.Config.ChainFile)
errors = append(errors, err)
} else if r.Config.CertFile == "" {
stdOut.Chain = r.Pcc.Chain
}
}
// PickupId is special -- it wasn't supposed to be written to -file
if r.Config.Command == commandEnrollName || r.Config.Command == commandRenewName {
if r.Config.PickupIdFile != "" && r.PickupId != "" {
pickupFileOutput := &Output{}
pickupFileOutput.PickupId = r.PickupId
err = writeFile(pickupFileOutput, r, r.Config.PickupIdFile)
errors = append(errors, err)
} else {
stdOut.PickupId = r.PickupId
}
}
// and flush the rest to STDOUT
bytes, err := stdOut.Format(r.Config)
if err != nil {
return err // something worse than file permission problem
}
fmt.Fprint(os.Stdout, string(bytes))
var finalError error
for _, e := range errors {
if e != nil {
if finalError == nil {
finalError = fmt.Errorf("error(s) happened on results output stage: ")
}
finalError = fmt.Errorf("%s%s; ", finalError, e)
}
}
return finalError
}
func writeFile(output *Output, result *Result, filePath string) (err error) {
if output.Certificate != "" || output.PrivateKey != "" || output.CSR != "" || len(output.Chain) > 0 {
var bytes []byte
bytes, err = output.Format(result.Config)
if err != nil {
return // something worse than file permission problem
}
err = ioutil.WriteFile(filePath, bytes, 0600)
} else {
if output.PickupId != "" {
err = ioutil.WriteFile(result.Config.PickupIdFile, []byte(result.PickupId+"\n"), 0600)
}
}
return
}
func outputJSON(resp interface{}) error {
jsonData, err := json.MarshalIndent(resp, "", " ")
if err == nil {
fmt.Println(string(jsonData))
}
return err
}