-
Notifications
You must be signed in to change notification settings - Fork 181
/
kustomization_decryptor.go
167 lines (142 loc) · 4.64 KB
/
kustomization_decryptor.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
/*
Copyright 2020 The Flux authors
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 controllers
import (
"bytes"
"context"
"fmt"
"io/ioutil"
"os"
"os/exec"
securejoin "github.com/cyphar/filepath-securejoin"
"go.mozilla.org/sops/v3"
"go.mozilla.org/sops/v3/aes"
"go.mozilla.org/sops/v3/cmd/sops/common"
"go.mozilla.org/sops/v3/cmd/sops/formats"
"go.mozilla.org/sops/v3/keyservice"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/kustomize/api/resource"
"sigs.k8s.io/yaml"
kustomizev1 "github.com/fluxcd/kustomize-controller/api/v1beta1"
intkeyservice "github.com/fluxcd/kustomize-controller/internal/sops/keyservice"
)
const DecryptionProviderSOPS = "sops"
type KustomizeDecryptor struct {
client.Client
kustomization kustomizev1.Kustomization
homeDir string
}
func NewDecryptor(kubeClient client.Client,
kustomization kustomizev1.Kustomization, homeDir string) *KustomizeDecryptor {
return &KustomizeDecryptor{
Client: kubeClient,
kustomization: kustomization,
homeDir: homeDir,
}
}
func NewTempDecryptor(kubeClient client.Client,
kustomization kustomizev1.Kustomization) (*KustomizeDecryptor, func(), error) {
tmpDir, err := ioutil.TempDir("", fmt.Sprintf("decryptor-%s-", kustomization.Name))
if err != nil {
return nil, nil, fmt.Errorf("tmp dir error: %w", err)
}
cleanup := func() { os.RemoveAll(tmpDir) }
return NewDecryptor(kubeClient, kustomization, tmpDir), cleanup, nil
}
func (kd *KustomizeDecryptor) Decrypt(res *resource.Resource) (*resource.Resource, error) {
out, err := res.AsYAML()
if err != nil {
return nil, err
}
if kd.kustomization.Spec.Decryption != nil && kd.kustomization.Spec.Decryption.Provider == DecryptionProviderSOPS &&
bytes.Contains(out, []byte("sops:")) && bytes.Contains(out, []byte("mac: ENC[")) {
store := common.StoreForFormat(formats.Yaml)
tree, err := store.LoadEncryptedFile(out)
if err != nil {
return nil, fmt.Errorf("LoadEncryptedFile: %w", err)
}
key, err := tree.Metadata.GetDataKeyWithKeyServices(
[]keyservice.KeyServiceClient{
intkeyservice.NewLocalClient(intkeyservice.NewServer(false, kd.homeDir)),
},
)
if err != nil {
if userErr, ok := err.(sops.UserError); ok {
err = fmt.Errorf(userErr.UserError())
}
return nil, fmt.Errorf("GetDataKey: %w", err)
}
cipher := aes.NewCipher()
if _, err := tree.Decrypt(key, cipher); err != nil {
return nil, fmt.Errorf("AES decrypt: %w", err)
}
data, err := store.EmitPlainFile(tree.Branches)
if err != nil {
return nil, fmt.Errorf("EmitPlainFile: %w", err)
}
jsonData, err := yaml.YAMLToJSON(data)
if err != nil {
return nil, fmt.Errorf("YAMLToJSON: %w", err)
}
err = res.UnmarshalJSON(jsonData)
if err != nil {
return nil, fmt.Errorf("UnmarshalJSON: %w", err)
}
return res, nil
}
return nil, nil
}
func (kd *KustomizeDecryptor) ImportKeys(ctx context.Context) error {
if kd.kustomization.Spec.Decryption != nil && kd.kustomization.Spec.Decryption.SecretRef != nil {
secretName := types.NamespacedName{
Namespace: kd.kustomization.GetNamespace(),
Name: kd.kustomization.Spec.Decryption.SecretRef.Name,
}
var secret corev1.Secret
if err := kd.Get(ctx, secretName, &secret); err != nil {
return fmt.Errorf("decryption secret error: %w", err)
}
tmpDir, err := ioutil.TempDir("", kd.kustomization.Name)
if err != nil {
return fmt.Errorf("tmp dir error: %w", err)
}
defer os.RemoveAll(tmpDir)
for name, key := range secret.Data {
keyPath, err := securejoin.SecureJoin(tmpDir, name)
if err != nil {
return err
}
if err := ioutil.WriteFile(keyPath, key, os.ModePerm); err != nil {
return fmt.Errorf("unable to write key to storage: %w", err)
}
if err := kd.gpgImport(keyPath); err != nil {
return err
}
}
}
return nil
}
func (kd *KustomizeDecryptor) gpgImport(path string) error {
args := []string{"--batch", "--import", path}
if kd.homeDir != "" {
args = append([]string{"--homedir", kd.homeDir}, args...)
}
cmd := exec.Command("gpg", args...)
out, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("gpg import error: %s", string(out))
}
return nil
}