Debian Codegraph @

plumbing/transport/ssh/common.go

raw
1 // Package ssh implements the SSH transport protocol.
2 package ssh
3
4 import (
5 "context"
6 "fmt"
7 "net"
8 "reflect"
9 "strconv"
10 "strings"
11
12 "github.com/go-git/go-git/v5/plumbing/transport"
13 "github.com/go-git/go-git/v5/plumbing/transport/internal/common"
14
15 "github.com/kevinburke/ssh_config"
16 "golang.org/x/crypto/ssh"
17 "golang.org/x/net/proxy"
18 )
19
20 // DefaultClient is the default SSH client.
21 var DefaultClient = NewClient(nil)
22
23 // DefaultSSHConfig is the reader used to access parameters stored in the
24 // system's ssh_config files. If nil all the ssh_config are ignored.
25 var DefaultSSHConfig sshConfig = ssh_config.DefaultUserSettings
26
27 type sshConfig interface {
28 Get(alias, key string) string
29 }
30
31 // NewClient creates a new SSH client with an optional *ssh.ClientConfig.
32 func NewClient(config *ssh.ClientConfig) transport.Transport {
33 return common.NewClient(&runner{config: config})
34 }
35
36 // DefaultAuthBuilder is the function used to create a default AuthMethod, when
37 // the user doesn't provide any.
38 var DefaultAuthBuilder = func(user string) (AuthMethod, error) {
39 return NewSSHAgentAuth(user)
40 }
41
42 const DefaultPort = 22
43
44 type runner struct {
45 config *ssh.ClientConfig
46 }
47
48 func (r *runner) Command(cmd string, ep *transport.Endpoint, auth transport.AuthMethod) (common.Command, error) {
49 c := &command{command: cmd, endpoint: ep, config: r.config}
50 if auth != nil {
51 if err := c.setAuth(auth); err != nil {
52 return nil, err
53 }
54 }
55
56 if err := c.connect(); err != nil {
57 return nil, err
58 }
59 return c, nil
60 }
61
62 type command struct {
63 *ssh.Session
64 connected bool
65 command string
66 endpoint *transport.Endpoint
67 client *ssh.Client
68 auth AuthMethod
69 config *ssh.ClientConfig
70 }
71
72 func (c *command) setAuth(auth transport.AuthMethod) error {
73 a, ok := auth.(AuthMethod)
74 if !ok {
75 return transport.ErrInvalidAuthMethod
76 }
77
78 c.auth = a
79 return nil
80 }
81
82 func (c *command) Start() error {
83 return c.Session.Start(endpointToCommand(c.command, c.endpoint))
84 }
85
86 // Close closes the SSH session and connection.
87 func (c *command) Close() error {
88 if !c.connected {
89 return nil
90 }
91
92 c.connected = false
93
94 //XXX: If did read the full packfile, then the session might be already
95 // closed.
96 _ = c.Session.Close()
97 err := c.client.Close()
98
99 //XXX: in go1.16+ we can use errors.Is(err, net.ErrClosed)
100 if err != nil && strings.HasSuffix(err.Error(), "use of closed network connection") {
101 return nil
102 }
103
104 return err
105 }
106
107 // connect connects to the SSH server, unless a AuthMethod was set with
108 // SetAuth method, by default uses an auth method based on PublicKeysCallback,
109 // it connects to a SSH agent, using the address stored in the SSH_AUTH_SOCK
110 // environment var.
111 func (c *command) connect() error {
112 if c.connected {
113 return transport.ErrAlreadyConnected
114 }
115
116 if c.auth == nil {
117 if err := c.setAuthFromEndpoint(); err != nil {
118 return err
119 }
120 }
121
122 var err error
123 config, err := c.auth.ClientConfig()
124 if err != nil {
125 return err
126 }
127 hostWithPort := c.getHostWithPort()
128 if config.HostKeyCallback == nil {
129 db, err := NewKnownHostsDb()
130 if err != nil {
131 return err
132 }
133 config.HostKeyCallback = db.HostKeyCallback()
134 config.HostKeyAlgorithms = db.HostKeyAlgorithms(hostWithPort)
135 } else {
136 // If the user gave a custom HostKeyCallback, we do not try to detect host key algorithms
137 // based on knownhosts functionality, as the user may be requesting a FixedKey or using a
138 // different key approval strategy. In that case, the user is responsible for populating
139 // HostKeyAlgorithms appropriately
140 }
141
142 overrideConfig(c.config, config)
143
144 c.client, err = dial("tcp", hostWithPort, c.endpoint.Proxy, config)
145 if err != nil {
146 return err
147 }
148
149 c.Session, err = c.client.NewSession()
150 if err != nil {
151 _ = c.client.Close()
152 return err
153 }
154
155 c.connected = true
156 return nil
157 }
158
159 func dial(network, addr string, proxyOpts transport.ProxyOptions, config *ssh.ClientConfig) (*ssh.Client, error) {
160 var (
161 ctx = context.Background()
162 cancel context.CancelFunc
163 )
164 if config.Timeout > 0 {
165 ctx, cancel = context.WithTimeout(ctx, config.Timeout)
166 } else {
167 ctx, cancel = context.WithCancel(ctx)
168 }
169 defer cancel()
170
171 var conn net.Conn
172 var dialErr error
173
174 if proxyOpts.URL != "" {
175 proxyUrl, err := proxyOpts.FullURL()
176 if err != nil {
177 return nil, err
178 }
179 dialer, err := proxy.FromURL(proxyUrl, proxy.Direct)
180 if err != nil {
181 return nil, err
182 }
183
184 // Try to use a ContextDialer, but fall back to a Dialer if that goes south.
185 ctxDialer, ok := dialer.(proxy.ContextDialer)
186 if !ok {
187 return nil, fmt.Errorf("expected ssh proxy dialer to be of type %s; got %s",
188 reflect.TypeOf(ctxDialer), reflect.TypeOf(dialer))
189 }
190 conn, dialErr = ctxDialer.DialContext(ctx, "tcp", addr)
191 } else {
192 conn, dialErr = proxy.Dial(ctx, network, addr)
193 }
194 if dialErr != nil {
195 return nil, dialErr
196 }
197
198 c, chans, reqs, err := ssh.NewClientConn(conn, addr, config)
199 if err != nil {
200 return nil, err
201 }
202 return ssh.NewClient(c, chans, reqs), nil
203 }
204
205 func (c *command) getHostWithPort() string {
206 if addr, found := c.doGetHostWithPortFromSSHConfig(); found {
207 return addr
208 }
209
210 host := c.endpoint.Host
211 port := c.endpoint.Port
212 if port <= 0 {
213 port = DefaultPort
214 }
215
216 return net.JoinHostPort(host, strconv.Itoa(port))
217 }
218
219 func (c *command) doGetHostWithPortFromSSHConfig() (addr string, found bool) {
220 if DefaultSSHConfig == nil {
221 return
222 }
223
224 host := c.endpoint.Host
225 port := c.endpoint.Port
226
227 configHost := DefaultSSHConfig.Get(c.endpoint.Host, "Hostname")
228 if configHost != "" {
229 host = configHost
230 found = true
231 }
232
233 if !found {
234 return
235 }
236
237 configPort := DefaultSSHConfig.Get(c.endpoint.Host, "Port")
238 if configPort != "" {
239 if i, err := strconv.Atoi(configPort); err == nil {
240 port = i
241 }
242 }
243
244 addr = net.JoinHostPort(host, strconv.Itoa(port))
245 return
246 }
247
248 func (c *command) setAuthFromEndpoint() error {
249 var err error
250 c.auth, err = DefaultAuthBuilder(c.endpoint.User)
251 return err
252 }
253
254 func endpointToCommand(cmd string, ep *transport.Endpoint) string {
255 var b strings.Builder
256 b.WriteString(cmd)
257 b.WriteByte(' ')
258 writeShellQuote(&b, ep.Path)
259 return b.String()
260 }
261
262 // writeShellQuote writes s to b, wrapped in single quotes with
263 // embedded single quotes and exclamation marks escaped using the
264 // POSIX close-escape-reopen idiom:
265 //
266 // ' becomes '\''
267 // ! becomes '\!'
268 //
269 // It is a direct port of canonical Git's sq_quote_buf (quote.c).
270 // The bang escape keeps the result safe when re-evaluated under
271 // csh-derived shells that perform history expansion. The output is
272 // safe to pass as a single argument through any POSIX shell and
273 // round-trips through git-shell's sq_dequote_to_argv.
274 func writeShellQuote(b *strings.Builder, s string) {
275 b.Grow(len(s) + 2)
276 b.WriteByte('\'')
277 for i := 0; i < len(s); i++ {
278 c := s[i]
279 if c == '\'' || c == '!' {
280 b.WriteString(`'\`)
281 b.WriteByte(c)
282 b.WriteByte('\'')
283 continue
284 }
285 b.WriteByte(c)
286 }
287 b.WriteByte('\'')
288 }
289
290 func overrideConfig(overrides *ssh.ClientConfig, c *ssh.ClientConfig) {
291 if overrides == nil {
292 return
293 }
294
295 t := reflect.TypeOf(*c)
296 vc := reflect.ValueOf(c).Elem()
297 vo := reflect.ValueOf(overrides).Elem()
298
299 for i := 0; i < t.NumField(); i++ {
300 f := t.Field(i)
301 vcf := vc.FieldByName(f.Name)
302 vof := vo.FieldByName(f.Name)
303 vcf.Set(vof)
304 }
305
306 *c = vc.Interface().(ssh.ClientConfig)
307 }