| 1 | package sshclient |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "context" |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "net" |
| 9 | "net/url" |
| 10 | "os" |
| 11 | "os/user" |
| 12 | "path/filepath" |
| 13 | "strconv" |
| 14 | "sync" |
| 15 | "time" |
| 16 | |
| 17 | "github.com/sirupsen/logrus" |
| 18 | "golang.org/x/crypto/ssh" |
| 19 | "golang.org/x/crypto/ssh/knownhosts" |
| 20 | ) |
| 21 | |
| 22 | var ( |
| 23 | homedirOnce sync.Once |
| 24 | homedir string |
| 25 | ) |
| 26 | |
| 27 | |
| 28 | |
| 29 | type Bastion struct { |
| 30 | Client *ssh.Client |
| 31 | Config *ssh.ClientConfig |
| 32 | Host string |
| 33 | Port string |
| 34 | Path string |
| 35 | connect ConnectCallback |
| 36 | } |
| 37 | |
| 38 | type ConnectCallback func(ctx context.Context, bastion *Bastion) (net.Conn, error) |
| 39 | |
| 40 | func PublicKey(path string, passphrase []byte) (ssh.Signer, error) { |
| 41 | key, err := os.ReadFile(path) |
| 42 | if err != nil { |
| 43 | return nil, err |
| 44 | } |
| 45 | |
| 46 | signer, err := ssh.ParsePrivateKey(key) |
| 47 | if err != nil { |
| 48 | if _, ok := err.(*ssh.PassphraseMissingError); !ok { |
| 49 | return nil, err |
| 50 | } |
| 51 | return ssh.ParsePrivateKeyWithPassphrase(key, passphrase) |
| 52 | } |
| 53 | return signer, nil |
| 54 | } |
| 55 | |
| 56 | func HostKey(host string) ssh.PublicKey { |
| 57 | |
| 58 | |
| 59 | knownHosts := filepath.Join(getHome(), ".ssh", "known_hosts") |
| 60 | fd, err := os.Open(knownHosts) |
| 61 | if err != nil { |
| 62 | logrus.Error(err) |
| 63 | return nil |
| 64 | } |
| 65 | |
| 66 | |
| 67 | hashhost := knownhosts.HashHostname(host) |
| 68 | |
| 69 | scanner := bufio.NewScanner(fd) |
| 70 | for scanner.Scan() { |
| 71 | _, hosts, key, _, _, err := ssh.ParseKnownHosts(scanner.Bytes()) |
| 72 | if err != nil { |
| 73 | logrus.Errorf("Failed to parse known_hosts: %s", scanner.Text()) |
| 74 | continue |
| 75 | } |
| 76 | |
| 77 | for _, h := range hosts { |
| 78 | if h == host || h == hashhost { |
| 79 | return key |
| 80 | } |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | return nil |
| 85 | } |
| 86 | |
| 87 | func CreateBastion(_url *url.URL, passPhrase string, identity string, initial net.Conn, connect ConnectCallback) (*Bastion, error) { |
| 88 | var authMethods []ssh.AuthMethod |
| 89 | |
| 90 | if len(identity) > 0 { |
| 91 | s, err := PublicKey(identity, []byte(passPhrase)) |
| 92 | if err != nil { |
| 93 | return nil, fmt.Errorf("failed to parse identity %q: %w", identity, err) |
| 94 | } |
| 95 | authMethods = append(authMethods, ssh.PublicKeys(s)) |
| 96 | } |
| 97 | |
| 98 | if pw, found := _url.User.Password(); found { |
| 99 | authMethods = append(authMethods, ssh.Password(pw)) |
| 100 | } |
| 101 | |
| 102 | if len(authMethods) == 0 { |
| 103 | return nil, errors.New("no available auth methods") |
| 104 | } |
| 105 | |
| 106 | port := _url.Port() |
| 107 | if port == "" { |
| 108 | port = "22" |
| 109 | } |
| 110 | |
| 111 | secure, _ := strconv.ParseBool(_url.Query().Get("secure")) |
| 112 | |
| 113 | callback := ssh.InsecureIgnoreHostKey() |
| 114 | if secure { |
| 115 | host := _url.Hostname() |
| 116 | if port != "22" { |
| 117 | host = fmt.Sprintf("[%s]:%s", host, port) |
| 118 | } |
| 119 | key := HostKey(host) |
| 120 | if key != nil { |
| 121 | callback = ssh.FixedHostKey(key) |
| 122 | } |
| 123 | } |
| 124 | |
| 125 | config := &ssh.ClientConfig{ |
| 126 | User: _url.User.Username(), |
| 127 | Auth: authMethods, |
| 128 | HostKeyCallback: callback, |
| 129 | HostKeyAlgorithms: []string{ |
| 130 | ssh.KeyAlgoRSA, |
| 131 | ssh.KeyAlgoECDSA256, |
| 132 | ssh.KeyAlgoECDSA384, |
| 133 | ssh.KeyAlgoECDSA521, |
| 134 | ssh.KeyAlgoED25519, |
| 135 | }, |
| 136 | Timeout: 5 * time.Second, |
| 137 | } |
| 138 | |
| 139 | if connect == nil { |
| 140 | connect = func(_ context.Context, bastion *Bastion) (net.Conn, error) { |
| 141 | conn, err := net.DialTimeout("tcp", |
| 142 | net.JoinHostPort(bastion.Host, bastion.Port), |
| 143 | bastion.Config.Timeout, |
| 144 | ) |
| 145 | |
| 146 | return conn, err |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | bastion := Bastion{nil, config, _url.Hostname(), port, _url.Path, connect} |
| 151 | return &bastion, bastion.reconnect(context.Background(), initial) |
| 152 | } |
| 153 | |
| 154 | func (bastion *Bastion) Reconnect(ctx context.Context) error { |
| 155 | return bastion.reconnect(ctx, nil) |
| 156 | } |
| 157 | |
| 158 | func (bastion *Bastion) Close() { |
| 159 | if bastion.Client != nil { |
| 160 | bastion.Client.Close() |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | func (bastion *Bastion) reconnect(ctx context.Context, conn net.Conn) error { |
| 165 | var err error |
| 166 | if conn == nil { |
| 167 | conn, err = bastion.connect(ctx, bastion) |
| 168 | } |
| 169 | if err != nil { |
| 170 | return fmt.Errorf("connection to bastion host (%s) failed: %w", bastion.Host, err) |
| 171 | } |
| 172 | addr := net.JoinHostPort(bastion.Host, bastion.Port) |
| 173 | c, chans, reqs, err := ssh.NewClientConn(conn, addr, bastion.Config) |
| 174 | if err != nil { |
| 175 | return err |
| 176 | } |
| 177 | bastion.Client = ssh.NewClient(c, chans, reqs) |
| 178 | return nil |
| 179 | } |
| 180 | |
| 181 | func getHome() string { |
| 182 | homedirOnce.Do(func() { |
| 183 | env, err := os.UserHomeDir() |
| 184 | if env == "" || err != nil { |
| 185 | usr, err := user.LookupId(fmt.Sprintf("%d", os.Getuid())) |
| 186 | if err != nil { |
| 187 | logrus.Error("Could not determine user home directory!") |
| 188 | homedir = "" |
| 189 | return |
| 190 | } |
| 191 | |
| 192 | homedir = usr.HomeDir |
| 193 | return |
| 194 | } |
| 195 | homedir = env |
| 196 | }) |
| 197 | return homedir |
| 198 | } |