-
Notifications
You must be signed in to change notification settings - Fork 61
/
result_writer.go
293 lines (264 loc) · 7.42 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
/*
* Copyright 2018 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 (
"crypto/rand"
"crypto/x509"
"encoding/json"
"encoding/pem"
"fmt"
"github.com/Venafi/vcert/v4/pkg/certificate"
"io/ioutil"
"os"
"software.sslmate.com/src/go-pkcs12"
"strings"
)
type Config struct {
Command string
Format 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"`
}
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)
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
}
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 {
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
}