File: bastion.go

package info (click to toggle)
golang-github-containers-gvisor-tap-vsocks 0.8.1-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 800 kB
  • sloc: sh: 95; makefile: 59
file content (199 lines) | stat: -rw-r--r-- 4,384 bytes parent folder | download
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
package sshclient

import (
	"bufio"
	"context"
	"fmt"
	"net"
	"net/url"
	"os"
	"os/user"
	"path/filepath"
	"strconv"
	"sync"
	"time"

	"github.com/pkg/errors"
	"github.com/sirupsen/logrus"
	"golang.org/x/crypto/ssh"
	"golang.org/x/crypto/ssh/knownhosts"
)

var (
	homedirOnce sync.Once
	homedir     string
)

// Modified version of podman ssh client library, until a shared module exists

type Bastion struct {
	Client  *ssh.Client
	Config  *ssh.ClientConfig
	Host    string
	Port    string
	Path    string
	connect ConnectCallback
}

type ConnectCallback func(ctx context.Context, bastion *Bastion) (net.Conn, error)

func PublicKey(path string, passphrase []byte) (ssh.Signer, error) {
	key, err := os.ReadFile(path)
	if err != nil {
		return nil, err
	}

	signer, err := ssh.ParsePrivateKey(key)
	if err != nil {
		if _, ok := err.(*ssh.PassphraseMissingError); !ok {
			return nil, err
		}
		return ssh.ParsePrivateKeyWithPassphrase(key, passphrase)
	}
	return signer, nil
}

func HostKey(host string) ssh.PublicKey {
	// parse OpenSSH known_hosts file
	// ssh or use ssh-keyscan to get initial key
	knownHosts := filepath.Join(getHome(), ".ssh", "known_hosts")
	fd, err := os.Open(knownHosts)
	if err != nil {
		logrus.Error(err)
		return nil
	}

	// support -H parameter for ssh-keyscan
	hashhost := knownhosts.HashHostname(host)

	scanner := bufio.NewScanner(fd)
	for scanner.Scan() {
		_, hosts, key, _, _, err := ssh.ParseKnownHosts(scanner.Bytes())
		if err != nil {
			logrus.Errorf("Failed to parse known_hosts: %s", scanner.Text())
			continue
		}

		for _, h := range hosts {
			if h == host || h == hashhost {
				return key
			}
		}
	}

	return nil
}

func CreateBastion(_url *url.URL, passPhrase string, identity string, initial net.Conn, connect ConnectCallback) (*Bastion, error) {
	var authMethods []ssh.AuthMethod

	if len(identity) > 0 {
		s, err := PublicKey(identity, []byte(passPhrase))
		if err != nil {
			return nil, errors.Wrapf(err, "failed to parse identity %q", identity)
		}
		authMethods = append(authMethods, ssh.PublicKeys(s))
	}

	if pw, found := _url.User.Password(); found {
		authMethods = append(authMethods, ssh.Password(pw))
	}

	if len(authMethods) == 0 {
		return nil, errors.New("No available auth methods")
	}

	port := _url.Port()
	if port == "" {
		port = "22"
	}

	secure, _ := strconv.ParseBool(_url.Query().Get("secure"))

	callback := ssh.InsecureIgnoreHostKey() // #nosec
	if secure {
		host := _url.Hostname()
		if port != "22" {
			host = fmt.Sprintf("[%s]:%s", host, port)
		}
		key := HostKey(host)
		if key != nil {
			callback = ssh.FixedHostKey(key)
		}
	}

	config := &ssh.ClientConfig{
		User:            _url.User.Username(),
		Auth:            authMethods,
		HostKeyCallback: callback,
		HostKeyAlgorithms: []string{
			ssh.KeyAlgoRSA,
			ssh.KeyAlgoDSA,
			ssh.KeyAlgoECDSA256,
			ssh.KeyAlgoECDSA384,
			ssh.KeyAlgoECDSA521,
			ssh.KeyAlgoED25519,
		},
		Timeout: 5 * time.Second,
	}

	if connect == nil {
		connect = func(_ context.Context, bastion *Bastion) (net.Conn, error) {
			conn, err := net.DialTimeout("tcp",
				net.JoinHostPort(bastion.Host, bastion.Port),
				bastion.Config.Timeout,
			)

			return conn, err
		}
	}

	bastion := Bastion{nil, config, _url.Hostname(), port, _url.Path, connect}
	return &bastion, bastion.reconnect(context.Background(), initial)
}

func (bastion *Bastion) Reconnect(ctx context.Context) error {
	return bastion.reconnect(ctx, nil)
}

func (bastion *Bastion) Close() {
	if bastion.Client != nil {
		bastion.Client.Close()
	}
}

func (bastion *Bastion) reconnect(ctx context.Context, conn net.Conn) error {
	var err error
	if conn == nil {
		conn, err = bastion.connect(ctx, bastion)
	}
	if err != nil {
		return errors.Wrapf(err, "Connection to bastion host (%s) failed", bastion.Host)
	}
	addr := net.JoinHostPort(bastion.Host, bastion.Port)
	c, chans, reqs, err := ssh.NewClientConn(conn, addr, bastion.Config)
	if err != nil {
		return err
	}
	bastion.Client = ssh.NewClient(c, chans, reqs)
	return nil
}

func getHome() string {
	homedirOnce.Do(func() {
		env, err := os.UserHomeDir()
		if env == "" || err != nil {
			usr, err := user.LookupId(fmt.Sprintf("%d", os.Getuid()))
			if err != nil {
				logrus.Error("Could not determine user home directory!")
				homedir = ""
				return
			}

			homedir = usr.HomeDir
			return
		}
		homedir = env
	})
	return homedir
}