-
Notifications
You must be signed in to change notification settings - Fork 20
/
communicator.go
259 lines (220 loc) · 6.63 KB
/
communicator.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
package winrm
import (
"fmt"
"io"
"log"
"os"
"strings"
"time"
"github.com/masterzen/winrm/winrm"
"github.com/mitchellh/packer/packer"
)
type Communicator struct {
client *winrm.Client
endpoint *winrm.Endpoint
user string
password string
timeout time.Duration
}
type elevatedShellOptions struct {
Command string
User string
Password string
}
// Creates a new packer.Communicator implementation over WinRM.
// Called when Packer tries to connect to WinRM
func New(endpoint *winrm.Endpoint, user string, password string, timeout time.Duration) (*Communicator, error) {
// Create the WinRM client we use internally
params := winrm.DefaultParameters()
params.Timeout = ISO8601DurationString(timeout)
client := winrm.NewClientWithParameters(endpoint, user, password, params)
// Attempt to connect to the WinRM service
shell, err := client.CreateShell()
if err != nil {
return nil, err
}
err = shell.Close()
if err != nil {
return nil, err
}
return &Communicator{
endpoint: endpoint,
user: user,
password: password,
timeout: timeout,
client: client,
}, nil
}
func (c *Communicator) Start(cmd *packer.RemoteCmd) (err error) {
// TODO: Can we only run as Elevated if specified in config/setting.
// It's fairly slow. It also doesn't work see Issue #1
//return c.StartElevated(cmd)
return c.StartUnelevated(cmd)
}
func (c *Communicator) StartElevated(cmd *packer.RemoteCmd) (err error) {
// Wrap the command in scheduled task
tpl, err := packer.NewConfigTemplate()
if err != nil {
return err
}
// The command gets put into an interpolated string in the PS script,
// so we need to escape any embedded quotes.
escapedCmd := strings.Replace(cmd.Command, "\"", "`\"", -1)
elevatedScript, err := tpl.Process(ElevatedShellTemplate, &elevatedShellOptions{
Command: escapedCmd,
User: c.user,
Password: c.password,
})
if err != nil {
return err
}
// Upload the script which creates and manages the scheduled task
log.Printf("uploading elevated command: %s", cmd.Command)
err = c.Upload("$env:TEMP/packer-elevated-shell.ps1", strings.NewReader(elevatedScript), nil)
if err != nil {
return err
}
// Run the script that was uploaded
path := "%TEMP%/packer-elevated-shell.ps1"
log.Printf("executing elevated command: %s", path)
command := fmt.Sprintf("powershell -executionpolicy bypass -file \"%s\"", path)
return c.runCommand(command, cmd)
}
func (c *Communicator) StartUnelevated(cmd *packer.RemoteCmd) (err error) {
log.Printf("starting remote command: %s", cmd.Command)
return c.runCommand(cmd.Command, cmd)
}
func (c *Communicator) runCommand(commandText string, cmd *packer.RemoteCmd) (err error) {
// Create a new shell process on the guest
err = c.client.RunWithInput(commandText, os.Stdout, os.Stderr, os.Stdin)
if err != nil {
fmt.Println(err)
cmd.SetExited(1)
return err
}
cmd.SetExited(0)
return
}
func (c *Communicator) Upload(dst string, input io.Reader, ignored *os.FileInfo) error {
log.Println("Uploading with the HTTP Server")
fm, err := NewFileManager(c)
if err != nil {
log.Printf("Unable to create File Manager: %s", err)
return err
}
return fm.Upload(dst, input)
}
func (c *Communicator) UploadDir(dst string, src string, excl []string) error {
fm, err := NewFileManager(c)
if err != nil {
log.Printf("Unable to create File Manager: %s", err)
return err
}
return fm.UploadDir(dst, src)
}
func (c *Communicator) Download(string, io.Writer) error {
panic("Download not implemented yet")
}
const ElevatedShellTemplate = `
$command = "{{.Command}}" + '; exit $LASTEXITCODE'
$user = '{{.User}}'
$password = '{{.Password}}'
$task_name = "packer-elevated-shell"
$out_file = "$env:TEMP\packer-elevated-shell.log"
if (Test-Path $out_file) {
del $out_file
}
$task_xml = @'
<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
<Principals>
<Principal id="Author">
<UserId>{user}</UserId>
<LogonType>Password</LogonType>
<RunLevel>HighestAvailable</RunLevel>
</Principal>
</Principals>
<Settings>
<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
<AllowHardTerminate>true</AllowHardTerminate>
<StartWhenAvailable>false</StartWhenAvailable>
<RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
<IdleSettings>
<StopOnIdleEnd>true</StopOnIdleEnd>
<RestartOnIdle>false</RestartOnIdle>
</IdleSettings>
<AllowStartOnDemand>true</AllowStartOnDemand>
<Enabled>true</Enabled>
<Hidden>false</Hidden>
<RunOnlyIfIdle>false</RunOnlyIfIdle>
<WakeToRun>false</WakeToRun>
<ExecutionTimeLimit>PT2H</ExecutionTimeLimit>
<Priority>4</Priority>
</Settings>
<Actions Context="Author">
<Exec>
<Command>cmd</Command>
<Arguments>{arguments}</Arguments>
</Exec>
</Actions>
</Task>
'@
$bytes = [System.Text.Encoding]::Unicode.GetBytes($command)
$encoded_command = [Convert]::ToBase64String($bytes)
$arguments = "/c powershell.exe -EncodedCommand $encoded_command > $out_file 2>&1"
$task_xml = $task_xml.Replace("{arguments}", $arguments)
$task_xml = $task_xml.Replace("{user}", $user)
$schedule = New-Object -ComObject "Schedule.Service"
$schedule.Connect()
$task = $schedule.NewTask($null)
$task.XmlText = $task_xml
$folder = $schedule.GetFolder("\")
$folder.RegisterTaskDefinition($task_name, $task, 6, $user, $password, 1, $null) | Out-Null
$registered_task = $folder.GetTask("\$task_name")
$registered_task.Run($null) | Out-Null
$timeout = 10
$sec = 0
while ( (!($registered_task.state -eq 4)) -and ($sec -lt $timeout) ) {
Start-Sleep -s 1
$sec++
}
function SlurpOutput($out_file, $cur_line) {
if (Test-Path $out_file) {
get-content $out_file | select -skip $cur_line | ForEach {
$cur_line += 1
Write-Host "$_"
}
}
return $cur_line
}
$cur_line = 0
do {
Start-Sleep -m 100
$cur_line = SlurpOutput $out_file $cur_line
} while (!($registered_task.state -eq 3))
$exit_code = $registered_task.LastTaskResult
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($schedule) | Out-Null
exit $exit_code
`
func ISO8601DurationString(d time.Duration) string {
// We're not supporting negative durations
if d.Seconds() <= 0 {
return "PT0S"
}
hours := int(d.Hours())
minutes := int(d.Minutes()) - (hours * 60)
seconds := int(d.Seconds()) - (hours*3600 + minutes*60)
s := "PT"
if hours > 0 {
s = fmt.Sprintf("%s%dH", s, hours)
}
if minutes > 0 {
s = fmt.Sprintf("%s%dM", s, minutes)
}
if seconds > 0 {
s = fmt.Sprintf("%s%dS", s, seconds)
}
return s
}