-
Notifications
You must be signed in to change notification settings - Fork 6
/
op_sign.go
199 lines (162 loc) · 5.54 KB
/
op_sign.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
/*
* Copyright (c) 2019 Entrust Datacard Corporation.
* All rights reserved.
*/
package main
import (
"bytes"
"context"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"fmt"
"io/ioutil"
"math/big"
"net/http"
"github.com/hashicorp/vault/logical"
"github.com/hashicorp/vault/logical/framework"
)
func (b *backend) opWriteSign(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
roleName := data.Get("roleName").(string)
if len(roleName) <= 0 {
return logical.ErrorResponse("a role name must be specified"), nil
}
var err error
format, err := getFormat(data)
if err != nil {
return logical.ErrorResponse("%v", err), err
}
// Comma separated list of subject variables: cn=Test,o=Entrust,c=CA
subjectVariables := data.Get("subject_variables").(string)
var subjectVars []SubjectVariable
if len(subjectVariables) > 0 {
subjectVars, err = processSubjectVariables(subjectVariables)
if err != nil {
return logical.ErrorResponse("Failed parsing the subject_variables"), err
}
}
altNames := data.Get("alt_names").([]string)
var subjAltNames []SubjectAltName
if len(altNames) > 0 {
subjAltNames, err = processSubjectAltNames(altNames)
if err != nil {
return logical.ErrorResponse("Failed parsing the subject alt names: %s", altNames), err
}
}
csrPem := data.Get("csr").(string)
// Just decode a single block, omit any subsequent blocks
csrBlock, _ := pem.Decode([]byte(csrPem))
if csrBlock == nil {
return logical.ErrorResponse("CSR could not be decoded"), nil
}
csrBase64 := base64.StdEncoding.EncodeToString(csrBlock.Bytes)
configRole, err := getConfigRole(ctx, req, roleName)
if err != nil {
return logical.ErrorResponse("Error fetching config"), err
}
caId := configRole.CAId
if len(caId) <= 0 {
caId = roleName
}
profileId := configRole.ProfileId
if len(profileId) <= 0 {
profileId = data.Get("profile").(string)
if len(profileId) <= 0 {
return logical.ErrorResponse("a profile must be specified for this CA role configuration"), nil
}
}
configProfile, err := getConfigProfile(ctx, req, roleName, profileId)
if err != nil {
return logical.ErrorResponse("Could not get profile configuration for profile " + profileId + ": " + err.Error()), err
}
ttl := getTTL(data, configProfile)
// Construct enrollment request
enrollmentRequest := EnrollmentRequest{
ProfileId: profileId,
RequiredFormat: RequiredFormat{
Format: "X509",
Protection: nil,
},
CSR: csrBase64,
SubjectVariables: subjectVars,
SubjectAltNames: subjAltNames,
OptionalCertificateRequestDetails: CertificateRequestDetails{
ValidityPeriod: fmt.Sprintf("PT%dM", int64(ttl.Minutes())),
},
}
body, err := json.Marshal(enrollmentRequest)
if err != nil {
return logical.ErrorResponse("Error constructing enrollment request: %v", err), err
}
if b.Logger().IsDebug() {
b.Logger().Debug(fmt.Sprintf("Enrollment request body: %v", string(body)))
}
tlsClientConfig, err := getTLSConfig(ctx, req, configRole)
if err != nil {
return logical.ErrorResponse("Error retrieving TLS configuration: %v", err), err
}
tr := &http.Transport{
Proxy: http.ProxyFromEnvironment,
TLSClientConfig: tlsClientConfig,
}
client := &http.Client{Transport: tr}
resp, err := client.Post(configRole.URL+"/v1/certificate-authorities/"+caId+"/enrollments", "application/json", bytes.NewReader(body))
if err != nil {
return logical.ErrorResponse("Error response: %v", err), err
}
responseBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return logical.ErrorResponse("CAGW response could not be read: %v", err), err
}
if b.Logger().IsTrace() {
b.Logger().Trace("response body: " + string(responseBody))
}
err = CheckForError(b, responseBody, resp.StatusCode)
if err != nil {
return logical.ErrorResponse("Error response received from gateway: %v", err), err
}
var enrollmentResponse EnrollmentResponse
err = json.Unmarshal(responseBody, &enrollmentResponse)
if err != nil {
return logical.ErrorResponse("CAGW enrollment response could not be parsed: %v", err), err
}
var respData map[string]interface{}
switch *format {
case "der":
respData = map[string]interface{}{
"certificate": enrollmentResponse.Enrollment.Body,
}
case "pem", "pem_bundle":
data, err := base64.StdEncoding.DecodeString(enrollmentResponse.Enrollment.Body)
if err != nil {
return logical.ErrorResponse("Error decoding base64 response from CAGW: %v", err), err
}
block := pem.Block{Type: "CERTIFICATE", Bytes: data}
certificate, err := x509.ParseCertificate(data)
if err != nil {
return logical.ErrorResponse("Failed to parse the certificate: %v", err), err
}
respData = map[string]interface{}{
"certificate": string(pem.EncodeToMemory(&block)),
"serial_number": certificate.SerialNumber,
}
}
storageEntry, err := logical.StorageEntryJSON("sign/"+roleName+"/"+respData["serial_number"].(*big.Int).String(), respData)
if err != nil {
return logical.ErrorResponse("error creating certificate storage entry"), err
}
err = req.Storage.Put(ctx, storageEntry)
if err != nil {
return logical.ErrorResponse("could not store certificate"), err
}
return &logical.Response{
Data: respData,
}, nil
}
func (b *backend) opReadSign(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
return opReadCert(ctx, req, data, "sign")
}
func (b *backend) opListSign(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
return opListCerts(ctx, req, data, "sign")
}