-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathfetch_secret.go
More file actions
215 lines (182 loc) · 6.22 KB
/
fetch_secret.go
File metadata and controls
215 lines (182 loc) · 6.22 KB
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
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2016-present Datadog, Inc.
package secretsimpl
import (
"bytes"
"context"
"errors"
"fmt"
"os/exec"
"strconv"
"strings"
"time"
json "github.com/json-iterator/go"
secrets "github.com/DataDog/datadog-agent/comp/core/secrets/def"
"github.com/DataDog/datadog-agent/pkg/util/log"
)
type limitBuffer struct {
max int
buf *bytes.Buffer
}
func (b *limitBuffer) Write(p []byte) (n int, err error) {
if len(p)+b.buf.Len() > b.max {
return 0, fmt.Errorf("command output was too long: exceeded %d bytes", b.max)
}
return b.buf.Write(p)
}
func (r *secretResolver) execCommand(inputPayload string) ([]byte, error) {
// hook used only for tests
if r.commandHookFunc != nil {
return r.commandHookFunc(inputPayload)
}
ctx, cancel := context.WithTimeout(context.Background(),
time.Duration(r.backendTimeout)*time.Second)
defer cancel()
cmd, done, err := commandContext(ctx, r.backendCommand, r.backendArguments...)
if err != nil {
return nil, err
}
defer done()
if !r.embeddedBackendPermissiveRights {
if err := checkRightsFunc(cmd.Path, r.commandAllowGroupExec); err != nil {
return nil, err
}
}
cmd.Stdin = strings.NewReader(inputPayload)
stdout := limitBuffer{
buf: &bytes.Buffer{},
max: r.responseMaxSize,
}
stderr := limitBuffer{
buf: &bytes.Buffer{},
max: r.responseMaxSize,
}
cmd.Stdout = &stdout
cmd.Stderr = &stderr
// We add the actual time to the log message. This is needed in the case we have a secret in the datadog.yaml.
// When it's the case the log package is not yet initialized (since it needs the configuration) and it will
// buffer logs until it's initialized. This means the time of the log line will be the one after the package is
// initialized and not the creation time. This is an issue when troubleshooting a secret_backend_command in
// datadog.yaml.
log.Debugf("%s | calling secret_backend_command with payload: '%s'", time.Now().String(), inputPayload)
start := time.Now()
err = cmd.Run()
elapsed := time.Since(start)
log.Debugf("%s | secret_backend_command '%s' completed in %s", time.Now().String(), r.backendCommand, elapsed)
// We always log stderr to allow a secret_backend_command to logs info in the agent log file. This is useful to
// troubleshoot secret_backend_command in a containerized environment.
if err != nil {
log.Errorf("secret_backend_command stderr: %s", stderr.buf.String())
exitCode := "unknown"
var e *exec.ExitError
if errors.As(err, &e) {
exitCode = strconv.Itoa(e.ExitCode())
} else if ctx.Err() == context.DeadlineExceeded {
exitCode = "timeout"
}
r.tlmSecretBackendElapsed.Add(float64(elapsed.Milliseconds()), r.backendCommand, exitCode)
if ctx.Err() == context.DeadlineExceeded {
return nil, fmt.Errorf("error while running '%s': command timeout", r.backendCommand)
}
return nil, fmt.Errorf("error while running '%s': %s", r.backendCommand, err)
}
log.Debugf("secret_backend_command stderr: %s", stderr.buf.String())
r.tlmSecretBackendElapsed.Add(float64(elapsed.Milliseconds()), r.backendCommand, "0")
return stdout.buf.Bytes(), nil
}
func (r *secretResolver) fetchSecretBackendVersion() (string, error) {
// hook used only for tests
if r.versionHookFunc != nil {
return r.versionHookFunc()
}
// Only get version when secret_backend_type is used
if r.backendType == "" {
return "", errors.New("version only supported when secret_backend_type is configured")
}
ctx, cancel := context.WithTimeout(context.Background(),
min(time.Duration(r.backendTimeout)*time.Second, 1*time.Second))
defer cancel()
// Execute with --version argument
cmd, done, err := commandContext(ctx, r.backendCommand, "--version")
if err != nil {
return "", err
}
defer done()
if !r.embeddedBackendPermissiveRights {
if err := checkRights(cmd.Path, r.commandAllowGroupExec); err != nil {
return "", err
}
}
stdout := limitBuffer{
buf: &bytes.Buffer{},
max: r.responseMaxSize,
}
stderr := limitBuffer{
buf: &bytes.Buffer{},
max: r.responseMaxSize,
}
cmd.Stdout = &stdout
cmd.Stderr = &stderr
log.Debugf("calling secret_backend_command --version")
err = cmd.Run()
if err != nil {
log.Debugf("secret_backend_command --version stderr: %s", stderr.buf.String())
if ctx.Err() == context.DeadlineExceeded {
return "", errors.New("version command timeout")
}
return "", fmt.Errorf("version command failed: %w", err)
}
return strings.TrimSpace(stdout.buf.String()), nil
}
// fetchSecret receives a list of secrets name to fetch, exec a custom
// executable to fetch the actual secrets and returns them.
func (r *secretResolver) fetchSecret(secretsHandle []string) (map[string]string, error) {
payload := map[string]interface{}{
"version": secrets.PayloadVersion,
"secrets": secretsHandle,
"secret_backend_timeout": r.backendTimeout,
}
if r.backendType != "" {
payload["type"] = r.backendType
}
if len(r.backendConfig) > 0 {
payload["config"] = r.backendConfig
}
jsonPayload, err := json.Marshal(payload)
if err != nil {
return nil, fmt.Errorf("could not serialize secrets IDs to fetch password: %s", err)
}
output, err := r.execCommand(string(jsonPayload))
if err != nil {
return nil, err
}
secrets := map[string]secrets.SecretVal{}
err = json.Unmarshal(output, &secrets)
if err != nil {
r.tlmSecretUnmarshalError.Inc()
return nil, fmt.Errorf("could not unmarshal 'secret_backend_command' output: %s", err)
}
res := map[string]string{}
for _, sec := range secretsHandle {
v, ok := secrets[sec]
if !ok {
r.tlmSecretResolveError.Inc("missing", sec)
return nil, fmt.Errorf("secret handle '%s' was not resolved by the secret_backend_command", sec)
}
if v.ErrorMsg != "" {
r.tlmSecretResolveError.Inc("error", sec)
return nil, fmt.Errorf("an error occurred while resolving '%s': %s", sec, v.ErrorMsg)
}
if r.removeTrailingLinebreak {
v.Value = strings.TrimRight(v.Value, "\r\n")
}
if v.Value == "" {
r.tlmSecretResolveError.Inc("empty", sec)
return nil, fmt.Errorf("resolved secret for '%s' is empty", sec)
}
res[sec] = v.Value
}
return res, nil
}