]> git.immae.eu Git - github/fretlink/terraform-provider-statuscake.git/blob - vendor/golang.org/x/crypto/ssh/client.go
Initial transfer of provider code
[github/fretlink/terraform-provider-statuscake.git] / vendor / golang.org / x / crypto / ssh / client.go
1 // Copyright 2011 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package ssh
6
7 import (
8 "errors"
9 "fmt"
10 "net"
11 "sync"
12 "time"
13 )
14
15 // Client implements a traditional SSH client that supports shells,
16 // subprocesses, port forwarding and tunneled dialing.
17 type Client struct {
18 Conn
19
20 forwards forwardList // forwarded tcpip connections from the remote side
21 mu sync.Mutex
22 channelHandlers map[string]chan NewChannel
23 }
24
25 // HandleChannelOpen returns a channel on which NewChannel requests
26 // for the given type are sent. If the type already is being handled,
27 // nil is returned. The channel is closed when the connection is closed.
28 func (c *Client) HandleChannelOpen(channelType string) <-chan NewChannel {
29 c.mu.Lock()
30 defer c.mu.Unlock()
31 if c.channelHandlers == nil {
32 // The SSH channel has been closed.
33 c := make(chan NewChannel)
34 close(c)
35 return c
36 }
37
38 ch := c.channelHandlers[channelType]
39 if ch != nil {
40 return nil
41 }
42
43 ch = make(chan NewChannel, chanSize)
44 c.channelHandlers[channelType] = ch
45 return ch
46 }
47
48 // NewClient creates a Client on top of the given connection.
49 func NewClient(c Conn, chans <-chan NewChannel, reqs <-chan *Request) *Client {
50 conn := &Client{
51 Conn: c,
52 channelHandlers: make(map[string]chan NewChannel, 1),
53 }
54
55 go conn.handleGlobalRequests(reqs)
56 go conn.handleChannelOpens(chans)
57 go func() {
58 conn.Wait()
59 conn.forwards.closeAll()
60 }()
61 go conn.forwards.handleChannels(conn.HandleChannelOpen("forwarded-tcpip"))
62 return conn
63 }
64
65 // NewClientConn establishes an authenticated SSH connection using c
66 // as the underlying transport. The Request and NewChannel channels
67 // must be serviced or the connection will hang.
68 func NewClientConn(c net.Conn, addr string, config *ClientConfig) (Conn, <-chan NewChannel, <-chan *Request, error) {
69 fullConf := *config
70 fullConf.SetDefaults()
71 conn := &connection{
72 sshConn: sshConn{conn: c},
73 }
74
75 if err := conn.clientHandshake(addr, &fullConf); err != nil {
76 c.Close()
77 return nil, nil, nil, fmt.Errorf("ssh: handshake failed: %v", err)
78 }
79 conn.mux = newMux(conn.transport)
80 return conn, conn.mux.incomingChannels, conn.mux.incomingRequests, nil
81 }
82
83 // clientHandshake performs the client side key exchange. See RFC 4253 Section
84 // 7.
85 func (c *connection) clientHandshake(dialAddress string, config *ClientConfig) error {
86 if config.ClientVersion != "" {
87 c.clientVersion = []byte(config.ClientVersion)
88 } else {
89 c.clientVersion = []byte(packageVersion)
90 }
91 var err error
92 c.serverVersion, err = exchangeVersions(c.sshConn.conn, c.clientVersion)
93 if err != nil {
94 return err
95 }
96
97 c.transport = newClientTransport(
98 newTransport(c.sshConn.conn, config.Rand, true /* is client */),
99 c.clientVersion, c.serverVersion, config, dialAddress, c.sshConn.RemoteAddr())
100 if err := c.transport.waitSession(); err != nil {
101 return err
102 }
103
104 c.sessionID = c.transport.getSessionID()
105 return c.clientAuthenticate(config)
106 }
107
108 // verifyHostKeySignature verifies the host key obtained in the key
109 // exchange.
110 func verifyHostKeySignature(hostKey PublicKey, result *kexResult) error {
111 sig, rest, ok := parseSignatureBody(result.Signature)
112 if len(rest) > 0 || !ok {
113 return errors.New("ssh: signature parse error")
114 }
115
116 return hostKey.Verify(result.H, sig)
117 }
118
119 // NewSession opens a new Session for this client. (A session is a remote
120 // execution of a program.)
121 func (c *Client) NewSession() (*Session, error) {
122 ch, in, err := c.OpenChannel("session", nil)
123 if err != nil {
124 return nil, err
125 }
126 return newSession(ch, in)
127 }
128
129 func (c *Client) handleGlobalRequests(incoming <-chan *Request) {
130 for r := range incoming {
131 // This handles keepalive messages and matches
132 // the behaviour of OpenSSH.
133 r.Reply(false, nil)
134 }
135 }
136
137 // handleChannelOpens channel open messages from the remote side.
138 func (c *Client) handleChannelOpens(in <-chan NewChannel) {
139 for ch := range in {
140 c.mu.Lock()
141 handler := c.channelHandlers[ch.ChannelType()]
142 c.mu.Unlock()
143
144 if handler != nil {
145 handler <- ch
146 } else {
147 ch.Reject(UnknownChannelType, fmt.Sprintf("unknown channel type: %v", ch.ChannelType()))
148 }
149 }
150
151 c.mu.Lock()
152 for _, ch := range c.channelHandlers {
153 close(ch)
154 }
155 c.channelHandlers = nil
156 c.mu.Unlock()
157 }
158
159 // Dial starts a client connection to the given SSH server. It is a
160 // convenience function that connects to the given network address,
161 // initiates the SSH handshake, and then sets up a Client. For access
162 // to incoming channels and requests, use net.Dial with NewClientConn
163 // instead.
164 func Dial(network, addr string, config *ClientConfig) (*Client, error) {
165 conn, err := net.DialTimeout(network, addr, config.Timeout)
166 if err != nil {
167 return nil, err
168 }
169 c, chans, reqs, err := NewClientConn(conn, addr, config)
170 if err != nil {
171 return nil, err
172 }
173 return NewClient(c, chans, reqs), nil
174 }
175
176 // A ClientConfig structure is used to configure a Client. It must not be
177 // modified after having been passed to an SSH function.
178 type ClientConfig struct {
179 // Config contains configuration that is shared between clients and
180 // servers.
181 Config
182
183 // User contains the username to authenticate as.
184 User string
185
186 // Auth contains possible authentication methods to use with the
187 // server. Only the first instance of a particular RFC 4252 method will
188 // be used during authentication.
189 Auth []AuthMethod
190
191 // HostKeyCallback, if not nil, is called during the cryptographic
192 // handshake to validate the server's host key. A nil HostKeyCallback
193 // implies that all host keys are accepted.
194 HostKeyCallback func(hostname string, remote net.Addr, key PublicKey) error
195
196 // ClientVersion contains the version identification string that will
197 // be used for the connection. If empty, a reasonable default is used.
198 ClientVersion string
199
200 // HostKeyAlgorithms lists the key types that the client will
201 // accept from the server as host key, in order of
202 // preference. If empty, a reasonable default is used. Any
203 // string returned from PublicKey.Type method may be used, or
204 // any of the CertAlgoXxxx and KeyAlgoXxxx constants.
205 HostKeyAlgorithms []string
206
207 // Timeout is the maximum amount of time for the TCP connection to establish.
208 //
209 // A Timeout of zero means no timeout.
210 Timeout time.Duration
211 }