forked from k0sproject/rig
-
Notifications
You must be signed in to change notification settings - Fork 0
/
winrm.go
354 lines (297 loc) · 8.43 KB
/
winrm.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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
package rig
import (
"bufio"
"context"
"fmt"
"io"
"os"
"sync"
"time"
"github.com/k0sproject/rig/exec"
"github.com/k0sproject/rig/log"
"github.com/masterzen/winrm"
"github.com/mitchellh/go-homedir"
)
// WinRM describes a WinRM connection with its configuration options
type WinRM struct {
Address string `yaml:"address" validate:"required,hostname_rfc1123|ip"`
User string `yaml:"user" validate:"omitempty,gt=2" default:"Administrator"`
Port int `yaml:"port" default:"5985" validate:"gt=0,lte=65535"`
Password string `yaml:"password,omitempty"`
UseHTTPS bool `yaml:"useHTTPS" default:"false"`
Insecure bool `yaml:"insecure" default:"false"`
UseNTLM bool `yaml:"useNTLM" default:"false"`
CACertPath string `yaml:"caCertPath,omitempty" validate:"omitempty,file"`
CertPath string `yaml:"certPath,omitempty" validate:"omitempty,file"`
KeyPath string `yaml:"keyPath,omitempty" validate:"omitempty,file"`
TLSServerName string `yaml:"tlsServerName,omitempty" validate:"omitempty,hostname_rfc1123|ip"`
Bastion *SSH `yaml:"bastion,omitempty"`
name string
caCert []byte
key []byte
cert []byte
client *winrm.Client
}
// SetDefaults sets various default values
func (c *WinRM) SetDefaults() {
if p, err := homedir.Expand(c.CACertPath); err == nil {
c.CACertPath = p
}
if p, err := homedir.Expand(c.CertPath); err == nil {
c.CertPath = p
}
if p, err := homedir.Expand(c.KeyPath); err == nil {
c.KeyPath = p
}
if c.Port == 5985 && c.UseHTTPS {
c.Port = 5986
}
}
// Protocol returns the protocol name, "WinRM"
func (c *WinRM) Protocol() string {
return "WinRM"
}
// IPAddress returns the connection address
func (c *WinRM) IPAddress() string {
return c.Address
}
// String returns the connection's printable name
func (c *WinRM) String() string {
if c.name == "" {
c.name = fmt.Sprintf("[winrm] %s:%d", c.Address, c.Port)
}
return c.name
}
// IsConnected returns true if the client is connected
func (c *WinRM) IsConnected() bool {
return c.client != nil
}
// IsWindows always returns true on winrm
func (c *WinRM) IsWindows() bool {
return true
}
func (c *WinRM) loadCertificates() error {
c.caCert = nil
if c.CACertPath != "" {
ca, err := os.ReadFile(c.CACertPath)
if err != nil {
return fmt.Errorf("%w: load ca-cerrt %s: %w", ErrInvalidPath, c.CACertPath, err)
}
c.caCert = ca
}
c.cert = nil
if c.CertPath != "" {
cert, err := os.ReadFile(c.CertPath)
if err != nil {
return fmt.Errorf("%w: load cert %s: %w", ErrInvalidPath, c.CertPath, err)
}
c.cert = cert
}
c.key = nil
if c.KeyPath != "" {
key, err := os.ReadFile(c.KeyPath)
if err != nil {
return fmt.Errorf("%w: load key %s: %w", ErrInvalidPath, key, err)
}
c.key = key
}
return nil
}
// Connect opens the WinRM connection
func (c *WinRM) Connect() error {
if err := c.loadCertificates(); err != nil {
return fmt.Errorf("%w: failed to load certificates: %w", ErrCantConnect, err)
}
endpoint := &winrm.Endpoint{
Host: c.Address,
Port: c.Port,
HTTPS: c.UseHTTPS,
Insecure: c.Insecure,
TLSServerName: c.TLSServerName,
Timeout: time.Minute,
}
if len(c.caCert) > 0 {
endpoint.CACert = c.caCert
}
if len(c.cert) > 0 {
endpoint.Cert = c.cert
}
if len(c.key) > 0 {
endpoint.Key = c.key
}
params := winrm.DefaultParameters
if c.Bastion != nil {
err := c.Bastion.Connect()
if err != nil {
return fmt.Errorf("bastion connect: %w", err)
}
params.Dial = c.Bastion.client.Dial
}
if c.UseNTLM {
params.TransportDecorator = func() winrm.Transporter { return &winrm.ClientNTLM{} }
}
if c.UseHTTPS && len(c.cert) > 0 {
params.TransportDecorator = func() winrm.Transporter { return &winrm.ClientAuthRequest{} }
}
client, err := winrm.NewClientWithParameters(endpoint, c.User, c.Password, params)
if err != nil {
return fmt.Errorf("create winrm client: %w", err)
}
log.Debugf("%s: testing connection", c)
_, err = client.RunWithContext(context.Background(), "echo ok", io.Discard, io.Discard)
if err != nil {
return fmt.Errorf("test connection: %w", err)
}
log.Debugf("%s: test passed", c)
c.client = client
return nil
}
// Disconnect closes the WinRM connection
func (c *WinRM) Disconnect() {
c.client = nil
}
// Command implements the Waiter interface
type Command struct {
sh *winrm.Shell
cmd *winrm.Command
stdin io.ReadCloser
stdout io.Writer
stderr io.Writer
}
// Wait blocks until the command finishes
func (c *Command) Wait() error {
var wg sync.WaitGroup
defer c.sh.Close()
defer c.cmd.Close()
if c.stdin == nil {
c.cmd.Stdin.Close()
} else {
wg.Add(1)
go func() {
defer c.cmd.Stdin.Close()
defer wg.Done()
log.Debugf("copying data to stdin")
_, err := io.Copy(c.cmd.Stdin, c.stdin)
if err != nil {
log.Errorf("copying data to command stdin failed: %v", err)
}
}()
}
wg.Add(2)
go func() {
defer wg.Done()
_, _ = io.Copy(c.stdout, c.cmd.Stdout)
}()
go func() {
defer wg.Done()
_, _ = io.Copy(c.stderr, c.cmd.Stderr)
}()
c.cmd.Wait()
log.Debugf("command finished")
var err error
if c.cmd.ExitCode() != 0 {
err = fmt.Errorf("%w: exit code %d", ErrCommandFailed, c.cmd.ExitCode())
}
wg.Wait()
return err
}
// ExecStreams executes a command on the remote host and uses the passed in streams for stdin, stdout and stderr. It returns a Waiter with a .Wait() function that
// blocks until the command finishes and returns an error if the exit code is not zero.
func (c *WinRM) ExecStreams(cmd string, stdin io.ReadCloser, stdout, stderr io.Writer, opts ...exec.Option) (waiter, error) {
if c.client == nil {
return nil, ErrNotConnected
}
execOpts := exec.Build(opts...)
command, err := execOpts.Command(cmd)
if err != nil {
return nil, fmt.Errorf("%w: build command: %w", ErrCommandFailed, err)
}
execOpts.LogCmd(c.String(), cmd)
shell, err := c.client.CreateShell()
if err != nil {
return nil, fmt.Errorf("%w: create shell: %w", ErrCantConnect, err)
}
proc, err := shell.ExecuteWithContext(context.Background(), command)
if err != nil {
return nil, fmt.Errorf("%w: execute command: %w", ErrCommandFailed, err)
}
return &Command{sh: shell, cmd: proc, stdin: stdin, stdout: stdout, stderr: stderr}, nil
}
// Exec executes a command on the host
func (c *WinRM) Exec(cmd string, opts ...exec.Option) error { //nolint:funlen,cyclop
execOpts := exec.Build(opts...)
shell, err := c.client.CreateShell()
if err != nil {
return fmt.Errorf("%w: create shell: %w", ErrCommandFailed, err)
}
defer shell.Close()
execOpts.LogCmd(c.String(), cmd)
command, err := shell.ExecuteWithContext(context.Background(), cmd)
if err != nil {
return fmt.Errorf("%w: execute command: %w", ErrCommandFailed, err)
}
var wg sync.WaitGroup
if execOpts.Stdin != "" {
execOpts.LogStdin(c.String())
wg.Add(1)
go func() {
defer wg.Done()
defer command.Stdin.Close()
_, _ = command.Stdin.Write([]byte(execOpts.Stdin))
}()
}
wg.Add(1)
go func() {
defer wg.Done()
if execOpts.Writer == nil {
outputScanner := bufio.NewScanner(command.Stdout)
for outputScanner.Scan() {
execOpts.AddOutput(c.String(), outputScanner.Text()+"\n", "")
}
if err := outputScanner.Err(); err != nil {
execOpts.LogErrorf("%s: %s", c, err.Error())
}
command.Stdout.Close()
} else {
if _, err := io.Copy(execOpts.Writer, command.Stdout); err != nil {
execOpts.LogErrorf("%s: failed to stream stdout: %v", c, err)
}
}
}()
gotErrors := false
wg.Add(1)
go func() {
defer wg.Done()
outputScanner := bufio.NewScanner(command.Stderr)
for outputScanner.Scan() {
gotErrors = true
execOpts.AddOutput(c.String(), "", outputScanner.Text()+"\n")
}
if err := outputScanner.Err(); err != nil {
gotErrors = true
execOpts.LogErrorf("%s: %s", c, err.Error())
}
command.Stderr.Close()
}()
command.Wait()
wg.Wait()
command.Close()
if ec := command.ExitCode(); ec > 0 {
return fmt.Errorf("%w: non-zero exit code: %d", ErrCommandFailed, ec)
}
if !execOpts.AllowWinStderr && gotErrors {
return fmt.Errorf("%w: received data in stderr", ErrCommandFailed)
}
return nil
}
// ExecInteractive executes a command on the host and copies stdin/stdout/stderr from local host
func (c *WinRM) ExecInteractive(cmd string) error {
if cmd == "" {
cmd = "cmd"
}
_, err := c.client.RunWithContextWithInput(context.Background(), cmd, os.Stdout, os.Stderr, os.Stdin)
if err != nil {
return fmt.Errorf("execute command interactive: %w", err)
}
return nil
}