From 86701ad873a0727b9c2512fed38f4ad150e33a4f Mon Sep 17 00:00:00 2001 From: Daniel Nelson Date: Thu, 4 Jan 2018 15:28:00 -0800 Subject: [PATCH] Escape environment variables during config toml parsing (#3637) --- internal/config/config.go | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/internal/config/config.go b/internal/config/config.go index 98d68f9ef..2aaa2da19 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -40,6 +40,11 @@ var ( // envVarRe is a regex to find environment variables in the config file envVarRe = regexp.MustCompile(`\$\w+`) + + envVarEscaper = strings.NewReplacer( + `"`, `\"`, + `\`, `\\`, + ) ) // Config specifies the URL/user/password for the database that telegraf @@ -689,6 +694,11 @@ func trimBOM(f []byte) []byte { return bytes.TrimPrefix(f, []byte("\xef\xbb\xbf")) } +// escapeEnv escapes a value for inserting into a TOML string. +func escapeEnv(value string) string { + return envVarEscaper.Replace(value) +} + // parseFile loads a TOML configuration from a provided path and // returns the AST produced from the TOML parser. When loading the file, it // will find environment variables and replace them. @@ -702,8 +712,9 @@ func parseFile(fpath string) (*ast.Table, error) { env_vars := envVarRe.FindAll(contents, -1) for _, env_var := range env_vars { - env_val := os.Getenv(strings.TrimPrefix(string(env_var), "$")) - if env_val != "" { + env_val, ok := os.LookupEnv(strings.TrimPrefix(string(env_var), "$")) + if ok { + env_val = escapeEnv(env_val) contents = bytes.Replace(contents, env_var, []byte(env_val), 1) } }