-
Notifications
You must be signed in to change notification settings - Fork 20
/
provider.go
386 lines (340 loc) · 12.1 KB
/
provider.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
package venafi
import (
"context"
"crypto/tls"
"crypto/x509"
"encoding/pem"
"fmt"
"net/http"
"os"
"strings"
"github.com/Venafi/vcert/v5"
"github.com/Venafi/vcert/v5/pkg/endpoint"
"github.com/Venafi/vcert/v5/pkg/venafi/tpp"
"github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"golang.org/x/crypto/pkcs12"
)
const (
messageVenafiPingFailed = "Failed to ping Venafi endpoint"
messageVenafiPingSuccessful = "Venafi ping successful"
messageVenafiClientInitFailed = "Failed to initialize Venafi client"
messageVenafiConfigFailed = "Failed to build config for Venafi issuer"
messageUseDevMode = "Using dev mode to issue certificate"
messageUseVaas = "Using VaaS to issue certificate"
messageUseTLSPDC = "Using Platform TLSPDC with url %s to issue certificate"
messageVenafiAuthFailed = "Failed to authenticate to Venafi platform"
utilityName = "HashiCorp Terraform"
defaultClientID = "hashicorp-terraform-by-venafi"
// Environment variables for Provider attributes
envVenafiURL = "VENAFI_URL"
envVenafiZone = "VENAFI_ZONE"
envVenafiUsername = "VENAFI_USER"
envVenafiPassword = "VENAFI_PASS"
envVenafiAccessToken = "VENAFI_TOKEN"
envVenafiApiKey = "VENAFI_API"
envVenafiDevMode = "VENAFI_DEVMODE"
envVenafiP12Certificate = "VENAFI_P12_CERTIFICATE"
envVenafiP12Password = "VENAFI_P12_PASSWORD"
envVenafiClientID = "VENAFI_CLIENT_ID"
// Attributes of the provider
providerURL = "url"
providerZone = "zone"
providerDevMode = "dev_mode"
providerUsername = "tpp_username"
providerPassword = "tpp_password"
providerP12Cert = "p12_cert_filename"
providerP12Password = "p12_cert_password"
providerAccessToken = "access_token"
providerApiKey = "api_key"
providerTrustBundle = "trust_bundle"
providerClientID = "client_id"
)
var (
messageVenafiNoAuthProvided = fmt.Sprintf("no authorization attributes defined in provider. "+
"One of the following must be set: %s, %s/%s, %s/%s, or %s",
providerAccessToken, providerP12Cert, providerP12Password, providerUsername, providerPassword, providerApiKey)
)
// Provider returns a terraform.ResourceProvider.
func Provider() *schema.Provider {
return &schema.Provider{
Schema: map[string]*schema.Schema{
providerURL: {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc(envVenafiURL, nil),
Description: "The Venafi Platform URL. Example: https://tpp.venafi.example/vedsdk",
},
providerZone: {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc(envVenafiZone, "Default"),
Description: `DN of the Venafi TLSPDC policy folder or name of the Venafi as a Service application plus issuing template alias.
Example for Platform: testPolicy\\vault
Example for Venafi as a Service: myApp\\Default`,
},
providerUsername: {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc(envVenafiUsername, nil),
Description: "WebSDK user for Venafi TLSPDC. Example: admin",
Deprecated: ", please use access_token instead",
},
providerPassword: {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc(envVenafiPassword, nil),
Description: "Password for WebSDK user. Example: password",
Deprecated: ", please use access_token instead",
Sensitive: true,
},
providerAccessToken: {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc(envVenafiAccessToken, nil),
Description: "Access token for Venafi TLSPDC, user should use this for authentication",
Sensitive: true,
},
providerP12Cert: {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc(envVenafiP12Certificate, nil),
Description: "Filename of PKCS#12 keystore containing a client certificate, private key, and chain certificates to authenticate to TLSPDC",
},
providerP12Password: {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc(envVenafiP12Password, nil),
Description: "Password for the PKCS#12 keystore declared in p12_cert",
Sensitive: true,
},
providerTrustBundle: {
Type: schema.TypeString,
Optional: true,
Description: `Use to specify a PEM-formatted file that contains certificates to be trust anchors for all communications with the Venafi Web Service.
Example:
trust_bundle = "${file("chain.pem")}"`,
},
providerApiKey: {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc(envVenafiApiKey, nil),
Description: `API key for Venafi as a Service. Example: 142231b7-cvb0-412e-886b-6aeght0bc93d`,
Sensitive: true,
},
providerDevMode: {
Type: schema.TypeBool,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc(envVenafiDevMode, nil),
Description: `When set to true, the resulting certificate will be issued by an ephemeral, no trust CA rather than enrolling using Venafi as a Service or Trust Protection Platform. Useful for development and testing.`,
},
providerClientID: {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc(envVenafiClientID, defaultClientID),
Description: "application that will be using the token",
},
},
ResourcesMap: map[string]*schema.Resource{
"venafi_certificate": resourceVenafiCertificate(),
"venafi_policy": resourceVenafiPolicy(),
"venafi_ssh_certificate": resourceVenafiSshCertificate(),
"venafi_ssh_config": resourceVenafiSshConfig(),
},
ConfigureContextFunc: providerConfigure,
}
}
func providerConfigure(ctx context.Context, d *schema.ResourceData) (interface{}, diag.Diagnostics) {
tflog.Info(ctx, "Configuring venafi provider")
apiKey := d.Get(providerApiKey).(string)
url := d.Get(providerURL).(string)
tppUser := d.Get(providerUsername).(string)
tppPassword := d.Get(providerPassword).(string)
accessToken := d.Get(providerAccessToken).(string)
zone := d.Get(providerZone).(string)
trustBundle := d.Get(providerTrustBundle).(string)
p12Certificate := d.Get(providerP12Cert).(string)
p12Password := d.Get(providerP12Password).(string)
clientID := d.Get(providerClientID).(string)
// Normalize zone for VCert usage
zone = normalizeZone(zone)
//Dev Mode
devMode := d.Get(providerDevMode).(bool)
// TLSPDC auth methods
userPassMethod := tppUser != "" && tppPassword != ""
clientCertMethod := p12Certificate != "" && p12Password != ""
accessTokenMethod := accessToken != ""
// TLSPC auth methods
apiKeyMethod := apiKey != ""
// Warning or errors can be collected in a slice type
var diags diag.Diagnostics
if !accessTokenMethod && !clientCertMethod && !userPassMethod && !apiKeyMethod && !devMode {
tflog.Error(ctx, messageVenafiNoAuthProvided)
diags = append(diags, diag.Diagnostic{
Severity: diag.Error,
Summary: messageVenafiClientInitFailed,
Detail: fmt.Sprintf("%s: %s", messageVenafiConfigFailed, messageVenafiNoAuthProvided),
})
return nil, diags
}
cfg := vcert.Config{
BaseUrl: url,
Zone: zone,
LogVerbose: true,
Credentials: &endpoint.Authentication{
ClientId: clientID,
},
}
if devMode {
tflog.Info(ctx, messageUseDevMode)
cfg.ConnectorType = endpoint.ConnectorTypeFake
} else if accessTokenMethod {
tflog.Info(ctx, fmt.Sprintf(messageUseTLSPDC, url))
cfg.ConnectorType = endpoint.ConnectorTypeTPP
cfg.Credentials.AccessToken = accessToken
} else if clientCertMethod {
tflog.Info(ctx, fmt.Sprintf(messageUseTLSPDC, url))
cfg.ConnectorType = endpoint.ConnectorTypeTPP
cfg.Credentials.ClientPKCS12 = true
err := setTLSConfig(ctx, p12Certificate, p12Password)
if err != nil {
tflog.Error(ctx, err.Error())
diags = append(diags, diag.Diagnostic{
Severity: diag.Error,
Summary: messageVenafiClientInitFailed,
Detail: fmt.Sprintf("%s: %s", messageVenafiConfigFailed, err.Error()),
})
return nil, diags
}
} else if userPassMethod {
tflog.Info(ctx, fmt.Sprintf(messageUseTLSPDC, url))
cfg.ConnectorType = endpoint.ConnectorTypeTPP
cfg.Credentials.User = tppUser
cfg.Credentials.Password = tppPassword
} else if apiKeyMethod {
tflog.Info(ctx, messageUseVaas)
cfg.ConnectorType = endpoint.ConnectorTypeCloud
cfg.Credentials.APIKey = apiKey
} else {
tflog.Error(ctx, messageVenafiNoAuthProvided)
diags = append(diags, diag.Diagnostic{
Severity: diag.Error,
Summary: messageVenafiClientInitFailed,
Detail: fmt.Sprintf("%s: %s", messageVenafiConfigFailed, messageVenafiNoAuthProvided),
})
return nil, diags
}
if trustBundle != "" {
tflog.Info(ctx, "Using trusted certificate")
tflog.Debug(ctx, fmt.Sprintf("Using trusted certificate: \n %s", trustBundle))
cfg.ConnectionTrust = trustBundle
}
err := pingVenafi(ctx, &cfg)
if err != nil {
diags = append(diags, diag.Diagnostic{
Severity: diag.Error,
Summary: messageVenafiClientInitFailed,
Detail: messageVenafiPingFailed + ": " + err.Error(),
})
return nil, diags
}
if clientCertMethod {
err = getAccessTokenFromClientCertificate(ctx, &cfg)
if err != nil {
diags = append(diags, diag.Diagnostic{
Severity: diag.Error,
Summary: messageVenafiClientInitFailed,
Detail: messageVenafiAuthFailed + ": " + err.Error(),
})
}
}
return &cfg, diags
}
func normalizeZone(zone string) string {
if zone == "" {
return zone
}
values := strings.Split(zone, "\\")
newZone := ""
for i, z := range values {
if len(z) > 0 {
newZone += z
if i < len(values)-1 {
newZone += "\\"
}
}
}
//Add leading forward slash when the zone includes the "VED" prefix
if strings.HasPrefix(newZone, "VED") {
newZone = "\\" + newZone
}
return newZone
}
func setTLSConfig(ctx context.Context, p12FileLocation string, p12Password string) error {
tflog.Info(ctx, "Setting up TLS Configuration")
tlsConfig := tls.Config{
Renegotiation: tls.RenegotiateFreelyAsClient,
}
data, err := os.ReadFile(p12FileLocation)
if err != nil {
return fmt.Errorf("unable to read PKCS#12 file at [%s]: %w", p12FileLocation, err)
}
// We have a PKCS12 file to use, set it up for cert authentication
blocks, err := pkcs12.ToPEM(data, p12Password)
if err != nil {
return fmt.Errorf("failed converting PKCS#12 archive file to PEM blocks: %w", err)
}
var pemData []byte
for _, b := range blocks {
pemData = append(pemData, pem.EncodeToMemory(b)...)
}
// Construct TLS certificate from PEM data
cert, err := tls.X509KeyPair(pemData, pemData)
if err != nil {
return fmt.Errorf("failed reading PEM data to build X.509 certificate: %w", err)
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(pemData)
// Setup HTTPS client
tlsConfig.Certificates = []tls.Certificate{cert}
tlsConfig.RootCAs = caCertPool
// Create own Transport to allow HTTP1.1 connections
transport := &http.Transport{
// Only one request is made with a client
DisableKeepAlives: true,
// This is to allow for http1.1 connections
ForceAttemptHTTP2: false,
TLSClientConfig: &tlsConfig,
}
//Setting Default HTTP Transport
http.DefaultTransport = transport
return nil
}
func pingVenafi(ctx context.Context, config *vcert.Config) error {
tflog.Info(ctx, fmt.Sprintf("Pinging Venafi Platform: %s", config.ConnectorType.String()))
client, err := vcert.NewClient(config, false)
if err != nil {
return err
}
err = client.Ping()
if err != nil {
return err
}
tflog.Info(ctx, "Ping Successful")
return nil
}
func getAccessTokenFromClientCertificate(ctx context.Context, config *vcert.Config) error {
tflog.Info(ctx, "PFX Certificate provided for authentication: Trying to authenticate")
client, err := vcert.NewClient(config, false)
if err != nil {
return err
}
resp, err := client.(*tpp.Connector).GetRefreshToken(config.Credentials)
if err != nil {
return err
}
config.Credentials.AccessToken = resp.Access_token
tflog.Info(ctx, "Successfully authenticated")
return nil
}