forked from bhendo/go-powershell
/
session_config.go
95 lines (74 loc) · 2.26 KB
/
session_config.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
// Copyright (c) 2017 Gorillalabs. All rights reserved.
package middleware
import (
"fmt"
"strconv"
"github.com/EnclaveData/go-powershell/utils"
"github.com/juju/errors"
)
const (
HTTPPort = 5985
HTTPSPort = 5986
)
type SessionConfig struct {
ComputerName string
AllowRedirection bool
Authentication string
CertificateThumbprint string
Credential interface{}
Port int
UseSSL bool
}
func NewSessionConfig() *SessionConfig {
return &SessionConfig{}
}
func (c *SessionConfig) ToArgs() []string {
args := make([]string, 0)
if c.ComputerName != "" {
args = append(args, "-ComputerName")
args = append(args, utils.QuoteArg(c.ComputerName))
}
if c.AllowRedirection {
args = append(args, "-AllowRedirection")
}
if c.Authentication != "" {
args = append(args, "-Authentication")
args = append(args, utils.QuoteArg(c.Authentication))
}
if c.CertificateThumbprint != "" {
args = append(args, "-CertificateThumbprint")
args = append(args, utils.QuoteArg(c.CertificateThumbprint))
}
if c.Port > 0 {
args = append(args, "-Port")
args = append(args, strconv.Itoa(c.Port))
}
if asserted, ok := c.Credential.(string); ok {
args = append(args, "-Credential")
args = append(args, asserted) // do not quote, as it contains a variable name when using password auth
}
if c.UseSSL {
args = append(args, "-UseSSL")
}
return args
}
type credential interface {
prepare(Middleware) (interface{}, error)
}
type UserPasswordCredential struct {
Username string
Password string
}
func (c *UserPasswordCredential) prepare(s Middleware) (interface{}, error) {
name := "goCred" + utils.CreateRandomString(8)
pwname := "goPass" + utils.CreateRandomString(8)
_, _, err := s.Execute(fmt.Sprintf("$%s = ConvertTo-SecureString -String %s -AsPlainText -Force", pwname, utils.QuoteArg(c.Password)))
if err != nil {
return nil, errors.Annotate(err, "Could not convert password to secure string")
}
_, _, err = s.Execute(fmt.Sprintf("$%s = New-Object -TypeName 'System.Management.Automation.PSCredential' -ArgumentList %s, $%s", name, utils.QuoteArg(c.Username), pwname))
if err != nil {
return nil, errors.Annotate(err, "Could not create PSCredential object")
}
return fmt.Sprintf("$%s", name), nil
}