-
Notifications
You must be signed in to change notification settings - Fork 3
/
backend.go
235 lines (198 loc) · 6.67 KB
/
backend.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
/*
* Copyright 2024 Keyfactor
* 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 keyfactor
import (
"context"
b64 "encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"strings"
"sync"
"time"
"github.com/hashicorp/errwrap"
"github.com/hashicorp/vault/sdk/framework"
"github.com/hashicorp/vault/sdk/logical"
)
//var config map[string]string
// Factory configures and returns backend
func Factory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) {
b := backend()
if err := b.Setup(ctx, conf); err != nil {
return nil, err
}
return b, nil
}
// // Store certificates by serial number
type keyfactorBackend struct {
*framework.Backend
lock sync.RWMutex
cachedConfig *keyfactorConfig
client *keyfactorClient
}
// keyfactorBackend defines the target API keyfactorBackend
// for Vault. It must include each path
// and the secrets it will store.
func backend() *keyfactorBackend {
var b = keyfactorBackend{}
b.Backend = &framework.Backend{
Help: strings.TrimSpace(keyfactorHelp),
PathsSpecial: &logical.Paths{
LocalStorage: []string{},
SealWrapStorage: []string{
"config",
"role/*",
},
},
Paths: framework.PathAppend(
pathConfig(&b),
pathRoles(&b),
pathCA(&b),
pathCerts(&b),
),
Secrets: []*framework.Secret{},
BackendType: logical.TypeLogical,
Invalidate: b.invalidate,
}
return &b
}
// reset clears any client configuration for a new
// backend to be configured
func (b *keyfactorBackend) reset() {
b.lock.Lock()
defer b.lock.Unlock()
b.client = nil
}
// invalidate clears an existing client configuration in
// the backend
func (b *keyfactorBackend) invalidate(ctx context.Context, key string) {
if key == "config" {
b.reset()
}
}
// getClient locks the backend as it configures and creates a
// a new client for the target API
func (b *keyfactorBackend) getClient(ctx context.Context, s logical.Storage) (*keyfactorClient, error) {
b.lock.RLock()
unlockFunc := b.lock.RUnlock
defer func() { unlockFunc() }()
if b.client != nil {
return b.client, nil
}
b.lock.RUnlock()
b.lock.Lock()
unlockFunc = b.lock.Unlock
return nil, fmt.Errorf("need to return client")
}
// Handle interface with Keyfactor API to enroll a certificate with given content
func (b *keyfactorBackend) submitCSR(ctx context.Context, req *logical.Request, csr string, caName string, templateName string) ([]string, string, error) {
config, err := b.config(ctx, req.Storage)
if err != nil {
return nil, "", err
}
if config == nil {
return nil, "", errors.New("configuration is empty")
}
ca := config.CertAuthority
template := config.CertTemplate
creds := config.Username + ":" + config.Password
encCreds := b64.StdEncoding.EncodeToString([]byte(creds))
location, _ := time.LoadLocation("UTC")
t := time.Now().In(location)
time := t.Format("2006-01-02T15:04:05")
// This is only needed when running as a vault extension
b.Logger().Debug("Closing idle connections")
http.DefaultClient.CloseIdleConnections()
// Build request
url := config.KeyfactorUrl + "/KeyfactorAPI/Enrollment/CSR"
b.Logger().Debug("url: " + url)
bodyContent := "{\"CSR\": \"" + csr + "\",\"CertificateAuthority\":\"" + ca + "\",\"IncludeChain\": true, \"Metadata\": {}, \"Timestamp\": \"" + time + "\",\"Template\": \"" + template + "\",\"SANs\": {}}"
payload := strings.NewReader(bodyContent)
b.Logger().Debug("body: " + bodyContent)
httpReq, err := http.NewRequest("POST", url, payload)
if err != nil {
b.Logger().Info("Error forming request: {{err}}", err)
}
httpReq.Header.Add("x-keyfactor-requested-with", "APIClient")
httpReq.Header.Add("content-type", "application/json")
httpReq.Header.Add("authorization", "Basic "+encCreds)
httpReq.Header.Add("x-certificateformat", "PEM")
// Send request and check status
b.Logger().Debug("About to connect to " + config.KeyfactorUrl + "for csr submission")
res, err := http.DefaultClient.Do(httpReq)
if err != nil {
b.Logger().Info("CSR Enrollment failed: {{err}}", err.Error())
return nil, "", err
}
if res.StatusCode != 200 {
b.Logger().Error("CSR Enrollment failed: server returned" + fmt.Sprint(res.StatusCode))
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
b.Logger().Error("Error response: " + string(body[:]))
return nil, "", fmt.Errorf("CSR Enrollment request failed with status code %d and error: "+string(body[:]), res.StatusCode)
}
// Read response and return certificate and key
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
b.Logger().Error("Error reading response: {{err}}", err)
return nil, "", err
}
// Parse response
var r map[string]interface{}
json.Unmarshal(body, &r)
b.Logger().Debug("response = ", r)
inner := r["CertificateInformation"].(map[string]interface{})
certI := inner["Certificates"].([]interface{})
certs := make([]string, len(certI))
for i, v := range certI {
certs[i] = v.(string)
start := strings.Index(certs[i], "-----BEGIN CERTIFICATE-----")
certs[i] = certs[i][start:]
}
serial := inner["SerialNumber"].(string)
kfId := inner["KeyfactorID"].(float64)
b.Logger().Debug("parsed response: ", certI...)
if err != nil {
b.Logger().Error("unable to parse ca_chain response", fmt.Sprint(err))
}
caEntry, err := logical.StorageEntryJSON("ca_chain/", certs[1:])
if err != nil {
b.Logger().Error("error creating ca_chain entry", err)
}
err = req.Storage.Put(ctx, caEntry)
if err != nil {
b.Logger().Error("error storing the ca_chain locally", err)
}
key := "certs/" + normalizeSerial(serial)
entry := &logical.StorageEntry{
Key: key,
Value: []byte(certs[0]),
}
b.Logger().Debug("cert entry.Value = ", string(entry.Value))
err = req.Storage.Put(ctx, entry)
if err != nil {
return nil, "", errwrap.Wrapf("unable to store certificate locally: {{err}}", err)
}
kfIdEntry, err := logical.StorageEntryJSON("kfId/"+normalizeSerial(serial), kfId)
if err != nil {
return nil, "", err
}
err = req.Storage.Put(ctx, kfIdEntry)
if err != nil {
return nil, "", errwrap.Wrapf("unable to store the keyfactor ID for the certificate locally: {{err}}", err)
}
return certs, serial, nil
}
const keyfactorHelp = `
The Keyfactor backend is a pki service that issues and manages certificates.
`