Auto escape chars special to PowerShell in user supplied data

This commit is contained in:
DanHam 2017-10-15 13:28:59 +01:00
parent aaf7102b9a
commit 2d830d5d43
No known key found for this signature in database
GPG Key ID: 58E79AEDD6AA987E
1 changed files with 30 additions and 4 deletions

View File

@ -24,6 +24,13 @@ import (
var retryableSleep = 2 * time.Second var retryableSleep = 2 * time.Second
var psEscape = strings.NewReplacer(
"$", "`$",
"\"", "`\"",
"`", "``",
"'", "`'",
)
type Config struct { type Config struct {
common.PackerConfig `mapstructure:",squash"` common.PackerConfig `mapstructure:",squash"`
@ -359,7 +366,13 @@ func (p *Provisioner) createFlattenedEnvVars(elevated bool) (flattened string) {
// Split vars into key/value components // Split vars into key/value components
for _, envVar := range p.config.Vars { for _, envVar := range p.config.Vars {
keyValue := strings.SplitN(envVar, "=", 2) keyValue := strings.SplitN(envVar, "=", 2)
envVars[keyValue[0]] = keyValue[1] // Escape chars special to PS in each env var value
escapedEnvVarValue := psEscape.Replace(keyValue[1])
if escapedEnvVarValue != keyValue[1] {
log.Printf("Env var %s converted to %s after escaping chars special to PS", keyValue[1],
escapedEnvVarValue)
}
envVars[keyValue[0]] = escapedEnvVarValue
} }
// Create a list of env var keys in sorted order // Create a list of env var keys in sorted order
@ -480,13 +493,26 @@ func (p *Provisioner) generateElevatedRunner(command string) (uploadedPath strin
} }
escapedCommand := buffer.String() escapedCommand := buffer.String()
log.Printf("Command [%s] converted to [%s] for use in XML string", command, escapedCommand) log.Printf("Command [%s] converted to [%s] for use in XML string", command, escapedCommand)
buffer.Reset() buffer.Reset()
// Escape chars special to PowerShell in the ElevatedUser string
escapedElevatedUser := psEscape.Replace(p.config.ElevatedUser)
if escapedElevatedUser != p.config.ElevatedUser {
log.Printf("Elevated user %s converted to %s after escaping chars special to PowerShell",
p.config.ElevatedUser, escapedElevatedUser)
}
// Escape chars special to PowerShell in the ElevatedPassword string
escapedElevatedPassword := psEscape.Replace(p.config.ElevatedPassword)
if escapedElevatedPassword != p.config.ElevatedPassword {
log.Printf("Elevated password %s converted to %s after escaping chars special to PowerShell",
p.config.ElevatedPassword, escapedElevatedPassword)
}
// Generate command // Generate command
err = elevatedTemplate.Execute(&buffer, elevatedOptions{ err = elevatedTemplate.Execute(&buffer, elevatedOptions{
User: p.config.ElevatedUser, User: escapedElevatedUser,
Password: p.config.ElevatedPassword, Password: escapedElevatedPassword,
TaskName: taskName, TaskName: taskName,
TaskDescription: "Packer elevated task", TaskDescription: "Packer elevated task",
LogFile: logFile, LogFile: logFile,