-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathmain.go
More file actions
231 lines (203 loc) · 10.8 KB
/
Copy pathmain.go
File metadata and controls
231 lines (203 loc) · 10.8 KB
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
/* Copyright (c) 2019 Snowflake Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
// Package main implements the SansShell CLI client.
package main
import (
"bufio"
"context"
"flag"
"fmt"
"log"
"os"
"strings"
"time"
"github.com/go-logr/logr"
"github.com/go-logr/stdr"
"github.com/google/subcommands"
"google.golang.org/grpc/metadata"
"github.com/Snowflake-Labs/sansshell/auth/mtls"
mtlsFlags "github.com/Snowflake-Labs/sansshell/auth/mtls/flags"
"github.com/Snowflake-Labs/sansshell/auth/opa"
"github.com/Snowflake-Labs/sansshell/auth/rpcauth"
"github.com/Snowflake-Labs/sansshell/cmd/sanssh/client"
cmdUtil "github.com/Snowflake-Labs/sansshell/cmd/util"
"github.com/Snowflake-Labs/sansshell/services/util"
// Import services here to make them accessible for CLI
_ "github.com/Snowflake-Labs/sansshell/services/ansible/client"
_ "github.com/Snowflake-Labs/sansshell/services/dns/client"
_ "github.com/Snowflake-Labs/sansshell/services/exec/client"
_ "github.com/Snowflake-Labs/sansshell/services/fdb/client"
_ "github.com/Snowflake-Labs/sansshell/services/healthcheck/client"
_ "github.com/Snowflake-Labs/sansshell/services/httpoverrpc/client"
_ "github.com/Snowflake-Labs/sansshell/services/localfile/client"
_ "github.com/Snowflake-Labs/sansshell/services/mpa/client"
_ "github.com/Snowflake-Labs/sansshell/services/network/client"
_ "github.com/Snowflake-Labs/sansshell/services/packages/client"
_ "github.com/Snowflake-Labs/sansshell/services/power/client"
_ "github.com/Snowflake-Labs/sansshell/services/process/client"
_ "github.com/Snowflake-Labs/sansshell/services/raw/client"
_ "github.com/Snowflake-Labs/sansshell/services/sansshell/client"
_ "github.com/Snowflake-Labs/sansshell/services/service/client"
_ "github.com/Snowflake-Labs/sansshell/services/sysinfo/client"
_ "github.com/Snowflake-Labs/sansshell/services/tlsinfo/client"
)
const (
defaultProxyPort = 50043
defaultTargetPort = 50042
proxyEnv = "SANSSHELL_PROXY"
)
var (
defaultDialTimeout = 10 * time.Second
defaultIdleTimeout = 15 * time.Minute
proxyAddr = flag.String("proxy", "", fmt.Sprintf(
`Address (host[:port]) to contact for proxy to sansshell-server.
%s in the environment can also be set instead of setting this flag. The flag will take precedence.
If blank a direct connection to the first entry in --targets will be made.
If port is blank the default of %d will be used`, proxyEnv, defaultProxyPort))
proxyAuthorityOverride = flag.String("proxy-authority-override", "", "Authority override to use when dialing the proxy (passed to grpc.WithAuthority when set)")
// Deprecated: --timeout flag is deprecated. Use --idle-timeout or --dial-timeout instead
_ = flag.Duration("timeout", defaultDialTimeout, "DEPRECATED. Please use --idle-timeout or --dial-timeout instead")
dialTimeout = flag.Duration("dial-timeout", defaultDialTimeout, "How long to wait for the connection to be accepted. Timeout specified in --targets or --proxy will take precedence")
idleTimeout = flag.Duration("idle-timeout", defaultIdleTimeout, "Maximum time that a connection is idle. If no messages are received within this timeframe, connection will be terminated")
credSource = flag.String("credential-source", mtlsFlags.Name(), fmt.Sprintf("Method used to obtain mTLS credentials (one of [%s])", strings.Join(mtls.Loaders(), ",")))
outputsDir = flag.String("output-dir", "", "If set defines a directory to emit output/errors from commands. Files will be generated based on target as destination/0 destination/0.error, etc.")
justification = flag.String("justification", "", "If non-empty will add the key '"+rpcauth.ReqJustKey+"' to the outgoing context Metadata to be passed along to the server for possible validation and logging.")
targetsFile = flag.String("targets-file", "", "If set read the targets list line by line (as host[:port]) from the indicated file instead of using --targets (error if both flags are used). A blank port acts the same as --targets")
clientPolicyFlag = flag.String("client-policy", "", "OPA policy for outbound client actions. If empty no policy is applied.")
clientPolicyFile = flag.String("client-policy-file", "", "Path to a file with a client OPA. If empty uses --client-policy")
verbosity = flag.Int("v", -1, "Verbosity level. > 0 indicates more extensive logging")
prefixHeader = flag.Bool("h", false, "If true prefix each line of output with '<index>-<target>: '")
batchSize = flag.Int("batch-size", 0, "If non-zero will perform the proxy->target work in batches of this size (with any remainder done at the end).")
mpa = flag.Bool("mpa", false, "Request multi-party approval for commands. This will create an MPA request, wait for approval, and then execute the command.")
authzDryRun = flag.Bool("authz-dry-run", false, "If true, the client will send a request to the server to check if the user has the permission to run the command. The server will respond with a success or failure message.")
// targets will be bound to --targets for sending a single request to N nodes.
targetsFlag util.StringSliceCommaOrWhitespaceFlag
// outputs will be found to --outputs for directing output from a single request to N nodes.
outputsFlag util.StringSliceCommaOrWhitespaceFlag
)
func init() {
flag.StringVar(&mtlsFlags.ClientCertFile, "client-cert", mtlsFlags.ClientCertFile, "Path to this client's x509 cert, PEM format")
flag.StringVar(&mtlsFlags.ClientKeyFile, "client-key", mtlsFlags.ClientKeyFile, "Path to this client's key")
flag.StringVar(&mtlsFlags.ServerCertFile, "server-cert", mtlsFlags.ServerCertFile, "Path to an x509 server cert, PEM format")
flag.StringVar(&mtlsFlags.ServerKeyFile, "server-key", mtlsFlags.ServerKeyFile, "Path to the server's TLS key")
flag.StringVar(&mtlsFlags.RootCAFile, "root-ca", mtlsFlags.RootCAFile, "The root of trust for remote identities, PEM format")
// Setup an empty slice so it can be deref'd below regardless of user input.
outputsFlag.Target = &[]string{}
targetsFlag.Target = &[]string{}
flag.Var(&targetsFlag, "targets", fmt.Sprintf("List of targets (host[:port] separated by commas and/or whitespace) to apply RPC against. If --proxy is not set must be one entry only. If port is blank the default of %d will be used", defaultTargetPort))
flag.Var(&outputsFlag, "outputs", `List of output destinations (separated by commas and/or whitespace) to direct output into.
Use - to indicated stdout/stderr (default if nothing else is set). Using - does not have to be repeated per target.
Errors will be emitted to <destination>.error separately from command/execution output which will be in the destination file.
NOTE: This must map 1:1 with --targets except in the '-' case.`)
subcommands.ImportantFlag("credential-source")
subcommands.ImportantFlag("proxy")
subcommands.ImportantFlag("targets")
subcommands.ImportantFlag("outputs")
subcommands.ImportantFlag("output-dir")
subcommands.ImportantFlag("targets-file")
subcommands.ImportantFlag("justification")
subcommands.ImportantFlag("client-policy")
subcommands.ImportantFlag("client-policy-file")
subcommands.ImportantFlag("mpa")
subcommands.ImportantFlag("v")
}
func isFlagPassed(name string) bool {
result := false
flag.Visit(func(f *flag.Flag) {
if f.Name == name {
result = true
}
})
return result
}
func main() {
// If this is blank it'll remain blank which is fine
// as that means just talk to --targets[0] instead.
// If the flag itself was set that will override.
*proxyAddr = os.Getenv(proxyEnv)
client.AddCommandLineCompletion(map[string]client.Predictor{
"targets": func(string) []string { return []string{"localhost"} },
})
flag.Parse()
if isFlagPassed("timeout") {
log.Fatalf("DEPRECATED: --timeout flag is deprecated. Please use --dial-timeout or --idle-timeout instead. Run `sanssh help` for details")
}
// If we're given a --targets-file read it in and stuff into targetsFlag
// so it can be processed below as if it was set that way.
if *targetsFile != "" {
// Can't set both flags.
if len(*targetsFlag.Target) > 0 {
log.Fatal("can't set --targets-file and --targets at the same time")
}
f, err := os.Open(*targetsFile)
if err != nil {
log.Fatalf("can't open %s: %v", *targetsFile, err)
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := scanner.Text()
target := strings.TrimSpace(line)
// Warn if whitespace was trimmed to help users clean up their files
if len(target) != len(line) && target != "" {
log.Printf("Warning: trimmed whitespace from target %q in %s", line, *targetsFile)
}
// Skip empty lines (including lines with only whitespace)
if target != "" {
*targetsFlag.Target = append(*targetsFlag.Target, target)
}
}
if err := scanner.Err(); err != nil {
log.Fatalf("scanning error reading %s: %v", *targetsFile, err)
}
}
// Validate and add the default proxy port (if needed).
if *proxyAddr != "" {
*proxyAddr = cmdUtil.ValidateAndAddPortAndTimeout(*proxyAddr, defaultProxyPort, *dialTimeout)
}
// Validate and add the default target port (if needed) for each target.
for i, t := range *targetsFlag.Target {
(*targetsFlag.Target)[i] = cmdUtil.ValidateAndAddPortAndTimeout(t, defaultTargetPort, *dialTimeout)
}
opaClientPolicy := cmdUtil.ChoosePolicy(logr.Discard(), "", *clientPolicyFlag, *clientPolicyFile)
logOpts := log.Ldate | log.Ltime | log.Lshortfile
logger := stdr.New(log.New(os.Stderr, "", logOpts)).WithName("sanssh")
stdr.SetVerbosity(*verbosity)
ctx := logr.NewContext(context.Background(), logger)
var clientPolicy rpcauth.AuthzPolicy
if opaClientPolicy != "" {
var err error
clientPolicy, err = opa.NewOpaAuthzPolicy(ctx, opaClientPolicy)
if err != nil {
logger.Error(err, "Could not load policy")
}
}
rs := client.RunState{
Proxy: *proxyAddr,
ProxyAuthorityOverride: *proxyAuthorityOverride,
Targets: *targetsFlag.Target,
Outputs: *outputsFlag.Target,
AuthzDryRun: *authzDryRun,
OutputsDir: *outputsDir,
CredSource: *credSource,
IdleTimeout: *idleTimeout,
ClientAuthzPolicy: clientPolicy,
PrefixOutput: *prefixHeader,
BatchSize: *batchSize,
EnableMPA: *mpa,
}
if *justification != "" {
ctx = metadata.AppendToOutgoingContext(ctx, rpcauth.ReqJustKey, *justification)
}
client.Run(ctx, rs)
}