-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
214 lines (189 loc) · 5.51 KB
/
main.go
File metadata and controls
214 lines (189 loc) · 5.51 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
package main
import (
"bytes"
"context"
"fmt"
"io"
"os"
"os/exec"
"os/signal"
"strings"
"syscall"
"time"
"github.com/adfinis/bssh/config"
"github.com/adfinis/bssh/otp"
"github.com/charmbracelet/fang"
"github.com/charmbracelet/log"
"github.com/creack/pty"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"golang.org/x/term"
)
var (
// Version is the current version of bssh.
Version = "devel"
// Commit is the git commit hash of the current version.
Commit = "none"
)
var exitCode int
var rootCmdFlags struct {
configPath string
logLevel string
}
var rootCmd = &cobra.Command{
Use: "bssh [flags] [host] [-- extra-ssh-args...]",
Short: "SSH for The Bastion with fancy autocompletion and OTP callback support",
Args: cobra.ArbitraryArgs,
FParseErrWhitelist: cobra.FParseErrWhitelist{UnknownFlags: true},
ValidArgsFunction: completeHosts,
CompletionOptions: cobra.CompletionOptions{
HiddenDefaultCmd: true,
},
PersistentPreRun: func(_ *cobra.Command, _ []string) {
level, err := log.ParseLevel(rootCmdFlags.logLevel)
if err != nil {
log.Fatal("Invalid log level", "error", err)
}
log.SetLevel(level)
},
Run: root,
}
func init() {
rootCmd.Flags().StringVarP(&rootCmdFlags.configPath, "config", "c", "", "Path to config file")
rootCmd.Flags().StringVar(&rootCmdFlags.logLevel, "log-level", "info", "Log level (debug, info, warn, error, fatal)")
rootCmd.Flags().String("username", "", "SSH username")
rootCmd.Flags().String("hostname", "", "SSH hostname")
rootCmd.Flags().Int("port", 0, "SSH port")
rootCmd.Flags().String("ssh-command", "", "SSH command (default \"ssh -t\")")
rootCmd.Flags().String("otp-callback-command", "", "Command to obtain OTP code")
rootCmd.Flags().String("otp-shell-command", "", "Shell command to run OTP callback (default \"/usr/bin/env bash -c\")")
v := config.GetViper()
_ = v.BindPFlag("username", rootCmd.Flags().Lookup("username"))
_ = v.BindPFlag("hostname", rootCmd.Flags().Lookup("hostname"))
_ = v.BindPFlag("port", rootCmd.Flags().Lookup("port"))
_ = v.BindPFlag("ssh_command", rootCmd.Flags().Lookup("ssh-command"))
_ = v.BindPFlag("otp_callback_command", rootCmd.Flags().Lookup("otp-callback-command"))
_ = v.BindPFlag("otp_shell_command", rootCmd.Flags().Lookup("otp-shell-command"))
}
func main() {
if err := fang.Execute(
context.Background(),
rootCmd,
fang.WithCommit(Commit),
fang.WithVersion(Version),
); err != nil {
os.Exit(1)
}
}
func extractUnknownArgs(flags *pflag.FlagSet, args []string) []string {
var unknownArgs []string
for i := 0; i < len(args); i++ {
a := args[i]
var f *pflag.Flag
if a[0] == '-' {
if a[1] == '-' {
f = flags.Lookup(strings.SplitN(a[2:], "=", 2)[0])
} else {
for _, s := range a[1:] {
f = flags.ShorthandLookup(string(s))
if f == nil {
break
}
}
}
}
if f != nil {
if f.NoOptDefVal == "" && i+1 < len(args) && f.Value.String() == args[i+1] {
i++
}
continue
}
unknownArgs = append(unknownArgs, a)
}
return unknownArgs
}
func root(cmd *cobra.Command, _ []string) {
unknownArgs := extractUnknownArgs(cmd.Flags(), os.Args[1:])
log.Debug("Unknown args", "args", unknownArgs)
log.Debug("Loading config", "path", rootCmdFlags.configPath)
cfg, err := config.Load(rootCmdFlags.configPath)
if err != nil {
log.Fatal("Failed to load config", "error", err)
}
log.Debug("Config loaded",
"username", cfg.Username,
"hostname", cfg.Hostname,
"port", cfg.Port,
"ssh_command", cfg.SSHCommand,
"otp_shell_command", cfg.OTPShellCommand,
"otp_callback_command", cfg.OTPCallbackCommand,
)
sshParts := strings.Fields(cfg.SSHCommand)
sshParts = append(sshParts, fmt.Sprintf("%s@%s", cfg.Username, cfg.Hostname), "--")
sshParts = append(sshParts, unknownArgs...)
log.Debug("SSH command", "parts", sshParts)
sshCmd := exec.Command(sshParts[0], sshParts[1:]...)
ptmx, err := pty.Start(sshCmd)
if err != nil {
log.Fatal("Failed to start SSH", "error", err)
}
defer ptmx.Close() //nolint:errcheck
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, syscall.SIGWINCH)
go func() {
for range sigCh {
_ = pty.InheritSize(os.Stdin, ptmx)
}
}()
sigCh <- syscall.SIGWINCH
oldState, err := term.MakeRaw(int(os.Stdin.Fd()))
if err != nil {
log.Fatal("Failed to set terminal to raw mode", "error", err)
}
defer func() { _ = term.Restore(int(os.Stdin.Fd()), oldState) }()
go func() { _, _ = io.Copy(ptmx, os.Stdin) }()
handleOutput(ptmx, cfg)
if err := sshCmd.Wait(); err != nil {
if exitErr, ok := err.(*exec.ExitError); ok {
exitCode = exitErr.ExitCode()
} else {
exitCode = 1
}
}
log.Debug("SSH exited", "code", exitCode)
}
func handleOutput(ptmx *os.File, cfg *config.Config) {
buf := make([]byte, 4096)
var acc bytes.Buffer
otpDone := false
deadline := time.Now().Add(10 * time.Second)
callback := otp.NewCallback(cfg)
for {
n, err := ptmx.Read(buf)
if n > 0 {
_, _ = os.Stdout.Write(buf[:n])
if !otpDone {
if time.Now().After(deadline) {
log.Debug("OTP deadline reached without seeing prompt")
otpDone = true
} else {
acc.Write(buf[:n])
if bytes.Contains(acc.Bytes(), []byte("Verification code:")) {
log.Debug("OTP prompt detected, fetching code")
code, err := callback()
if err != nil {
log.Fatal("Failed to get OTP", "error", err)
}
log.Debug("OTP obtained, sending")
_, _ = fmt.Fprintf(ptmx, "%s\r", code)
otpDone = true
}
}
}
}
if err != nil {
log.Debug("PTY read ended", "error", err)
return
}
}
}