forked from runtheops/azure-keyvault-env
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
262 lines (216 loc) · 7.22 KB
/
main.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
package main
import (
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"fmt"
"io/ioutil"
"log"
"os"
"strings"
"crypto/tls"
"bytes"
"encoding/json"
"github.com/Azure/azure-sdk-for-go/dataplane/keyvault"
"github.com/Azure/go-autorest/autorest"
"github.com/cosmincojocar/adal"
"github.com/namsral/flag"
"golang.org/x/crypto/pkcs12"
)
const (
activeDirectoryEndpoint = "https://login.microsoftonline.com/"
resource = "https://vault.azure.net"
akePrefix = "AKE"
)
type option struct {
name string
value string
}
var (
vaultName string
tenantID string
applicationID string
certificatePath string
servicePrefix string
jsonOutput bool
)
func init() {
fs := flag.NewFlagSetWithEnvPrefix(os.Args[0], akePrefix, 0)
fs.StringVar(&vaultName, "vaultName", "", "key vault from which secrets are retrieved")
fs.StringVar(&tenantID, "tenantId", "", "tenant id")
fs.StringVar(&applicationID, "applicationId", "", "application id for service principal")
fs.StringVar(&certificatePath, "certificatePath", "", "path to pk12/PFC application certificate")
fs.StringVar(&servicePrefix, "servicePrefix", "", "prefix to filter keys for service")
fs.BoolVar(&jsonOutput, "json", false, "json output")
fs.Parse(os.Args[1:])
checkMandatoryOptions(
option{name: "vaultName", value: vaultName},
option{name: "tenantId", value: tenantID},
option{name: "applicationId", value: applicationID},
option{name: "certificatePath", value: certificatePath},
option{name: "servicePrefix", value: servicePrefix},
)
}
func main() {
oauthConfig, err := adal.NewOAuthConfig(activeDirectoryEndpoint, tenantID)
if err != nil {
log.Fatalf("Failed to create OAuth config: %q", err)
}
spt, err := acquireTokenClientCertFlow(
*oauthConfig,
applicationID,
certificatePath,
resource)
if err != nil {
log.Fatalf("Failed to acquire a token for resource %s. Error: %v", resource, err)
}
envVars, err := expandVars(vaultName, spt)
if err != nil {
log.Fatalf("Failed to expand environment: %v", err)
}
if jsonOutput {
output, _ := json.Marshal(envVars)
fmt.Println(string(output))
} else {
for key, value := range envVars {
exportString := fmt.Sprintf("export %s=\"%s\"", key, value)
fmt.Println(exportString)
}
}
}
func checkMandatoryOptions(options ...option) {
for _, option := range options {
if strings.TrimSpace(option.value) == "" {
log.Fatalf("Authentication requires mandatory option '%s'.", option.name)
}
}
}
func decodePkcs12(pkcs []byte, password string) (*x509.Certificate, *rsa.PrivateKey, error) {
privateKey, certificate, err := pkcs12.Decode(pkcs, password)
if err != nil {
return nil, nil, err
}
rsaPrivateKey, isRsaKey := privateKey.(*rsa.PrivateKey)
if !isRsaKey {
return nil, nil, fmt.Errorf("PKCS#12 certificate must contain an RSA private key")
}
return certificate, rsaPrivateKey, nil
}
func decodePem(filePath string) (*x509.Certificate, *rsa.PrivateKey, error) {
pemFile, err := ioutil.ReadFile(filePath)
cliCertIndex := bytes.Index(pemFile, []byte("issuer=/CN=CLI-Login"))
if cliCertIndex == 0 {
return nil, nil, fmt.Errorf("couldn't find CLI-Login certificate")
}
cliKeyId := pemFile[cliCertIndex-41 : cliCertIndex-23]
cliCertificate := pemFile[cliCertIndex+20:]
cliCertEnd := bytes.Index(cliCertificate, []byte("-----END CERTIFICATE-----"))
if cliCertEnd == 0 {
return nil, nil, fmt.Errorf("couldn't parse CLI-Login certificate")
}
cliCertificate = cliCertificate[:cliCertEnd+25]
cliPrivateIndex := bytes.Index(pemFile, cliKeyId)
if cliCertIndex == 0 {
return nil, nil, fmt.Errorf("couldn't find CLI-Login private key")
}
cliPrivateKey := pemFile[cliPrivateIndex:]
cliPrivateEnd := bytes.Index(cliPrivateKey, []byte("-----END PRIVATE KEY-----"))
if cliPrivateEnd == 0 {
return nil, nil, fmt.Errorf("couldn't parse CLI-Login private key")
}
cliPrivateKey = cliPrivateKey[:cliPrivateEnd+25]
cert, err := tls.X509KeyPair(cliCertificate, cliPrivateKey)
if err != nil {
return nil, nil, fmt.Errorf("failed to load x509 keypair: %q", err)
}
x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
key, ok := cert.PrivateKey.(*rsa.PrivateKey)
if !ok {
return nil, nil, fmt.Errorf("incorrect private key %v", cert.PrivateKey)
}
return x509Cert, key, err
}
func acquireTokenClientCertFlow(oauthConfig adal.OAuthConfig,
applicationID string,
applicationCertPath string,
resource string) (*adal.ServicePrincipalToken, error) {
var rsaPrivateKey *rsa.PrivateKey
var certificate *x509.Certificate
var err error
if strings.HasSuffix(certificatePath, ".pfx") {
certData, err := ioutil.ReadFile(certificatePath)
if err != nil {
return nil, fmt.Errorf("failed to read the certificate file (%s): %v", certificatePath, err)
}
certificate, rsaPrivateKey, err = decodePkcs12(certData, "")
} else {
certificate, rsaPrivateKey, err = decodePem(certificatePath)
}
if err != nil {
return nil, fmt.Errorf("failed to decode certificate and private key while creating spt: %v", err)
}
spt, err := adal.NewServicePrincipalTokenFromCertificate(
oauthConfig,
applicationID,
certificate,
rsaPrivateKey,
resource)
if err != nil {
return nil, err
}
return spt, spt.Refresh()
}
func splitVar(v string) (key, val string) {
parts := strings.Split(v, "=")
return parts[0], parts[1]
}
func expandVars(vaultName string,
spt *adal.ServicePrincipalToken) (map[string]string, error) {
var exportStrings []string
var secretName string
var secretDest string
var secretFile bool
exportVars := make(map[string]string)
vaultClient := keyvault.New()
vaultClient.Authorizer = autorest.NewBearerAuthorizer(spt)
vaultURL := fmt.Sprintf("https://%s.vault.azure.net", vaultName)
secretList, err := vaultClient.GetSecrets(vaultURL, nil)
if err != nil || *secretList.Value == nil {
return nil, fmt.Errorf("error on getting secrets list: %v", err)
}
for _, secret := range *secretList.Value {
secretKeyUrl := strings.Split(*secret.ID, "/")
secretKey := secretKeyUrl[len(secretKeyUrl)-1]
if strings.HasPrefix(secretKey, servicePrefix) {
secretName = secretKey[len(servicePrefix)+1:]
if strings.HasSuffix(secretName, "-file") {
secretName = secretName[:len(secretName)-5]
secretFile = true
}
secret, err := vaultClient.GetSecret(vaultURL, secretKey, "")
if err != nil {
return nil, fmt.Errorf("failed to obtain secret with key \"%s\" from vault: %v", secretKey, err)
}
secretValue := *secret.Value
if secretFile {
secretContent, err := base64.StdEncoding.DecodeString(secretValue)
if err != nil {
return nil, fmt.Errorf("failed to base64 decode secret with key \"%s\": %v", secretKey, err)
}
secretDest = strings.Split(string(secretContent), "\r\n")[0]
secretContent = secretContent[len(secretDest)+2:]
err = ioutil.WriteFile(secretDest, secretContent, 0644)
if err != nil {
return nil, fmt.Errorf("failed to write contents of \"%s\" secret to \"%s\": %v", secretName, secretDest, exportStrings)
}
secretValue = secretDest
}
varName := strings.Replace(strings.ToUpper(secretName), "-", "_", -1)
exportVars[varName] = secretValue
if err != nil {
return nil, fmt.Errorf("failed to update environment variable \"%s\": %v", secretName, err)
}
}
}
return exportVars, nil
}