]> git.immae.eu Git - github/fretlink/terraform-provider-statuscake.git/blob - vendor/golang.org/x/crypto/ssh/handshake.go
Initial transfer of provider code
[github/fretlink/terraform-provider-statuscake.git] / vendor / golang.org / x / crypto / ssh / handshake.go
1 // Copyright 2013 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 "crypto/rand"
9 "errors"
10 "fmt"
11 "io"
12 "log"
13 "net"
14 "sync"
15 )
16
17 // debugHandshake, if set, prints messages sent and received. Key
18 // exchange messages are printed as if DH were used, so the debug
19 // messages are wrong when using ECDH.
20 const debugHandshake = false
21
22 // chanSize sets the amount of buffering SSH connections. This is
23 // primarily for testing: setting chanSize=0 uncovers deadlocks more
24 // quickly.
25 const chanSize = 16
26
27 // keyingTransport is a packet based transport that supports key
28 // changes. It need not be thread-safe. It should pass through
29 // msgNewKeys in both directions.
30 type keyingTransport interface {
31 packetConn
32
33 // prepareKeyChange sets up a key change. The key change for a
34 // direction will be effected if a msgNewKeys message is sent
35 // or received.
36 prepareKeyChange(*algorithms, *kexResult) error
37 }
38
39 // handshakeTransport implements rekeying on top of a keyingTransport
40 // and offers a thread-safe writePacket() interface.
41 type handshakeTransport struct {
42 conn keyingTransport
43 config *Config
44
45 serverVersion []byte
46 clientVersion []byte
47
48 // hostKeys is non-empty if we are the server. In that case,
49 // it contains all host keys that can be used to sign the
50 // connection.
51 hostKeys []Signer
52
53 // hostKeyAlgorithms is non-empty if we are the client. In that case,
54 // we accept these key types from the server as host key.
55 hostKeyAlgorithms []string
56
57 // On read error, incoming is closed, and readError is set.
58 incoming chan []byte
59 readError error
60
61 mu sync.Mutex
62 writeError error
63 sentInitPacket []byte
64 sentInitMsg *kexInitMsg
65 pendingPackets [][]byte // Used when a key exchange is in progress.
66
67 // If the read loop wants to schedule a kex, it pings this
68 // channel, and the write loop will send out a kex
69 // message.
70 requestKex chan struct{}
71
72 // If the other side requests or confirms a kex, its kexInit
73 // packet is sent here for the write loop to find it.
74 startKex chan *pendingKex
75
76 // data for host key checking
77 hostKeyCallback func(hostname string, remote net.Addr, key PublicKey) error
78 dialAddress string
79 remoteAddr net.Addr
80
81 // Algorithms agreed in the last key exchange.
82 algorithms *algorithms
83
84 readPacketsLeft uint32
85 readBytesLeft int64
86
87 writePacketsLeft uint32
88 writeBytesLeft int64
89
90 // The session ID or nil if first kex did not complete yet.
91 sessionID []byte
92 }
93
94 type pendingKex struct {
95 otherInit []byte
96 done chan error
97 }
98
99 func newHandshakeTransport(conn keyingTransport, config *Config, clientVersion, serverVersion []byte) *handshakeTransport {
100 t := &handshakeTransport{
101 conn: conn,
102 serverVersion: serverVersion,
103 clientVersion: clientVersion,
104 incoming: make(chan []byte, chanSize),
105 requestKex: make(chan struct{}, 1),
106 startKex: make(chan *pendingKex, 1),
107
108 config: config,
109 }
110
111 // We always start with a mandatory key exchange.
112 t.requestKex <- struct{}{}
113 return t
114 }
115
116 func newClientTransport(conn keyingTransport, clientVersion, serverVersion []byte, config *ClientConfig, dialAddr string, addr net.Addr) *handshakeTransport {
117 t := newHandshakeTransport(conn, &config.Config, clientVersion, serverVersion)
118 t.dialAddress = dialAddr
119 t.remoteAddr = addr
120 t.hostKeyCallback = config.HostKeyCallback
121 if config.HostKeyAlgorithms != nil {
122 t.hostKeyAlgorithms = config.HostKeyAlgorithms
123 } else {
124 t.hostKeyAlgorithms = supportedHostKeyAlgos
125 }
126 go t.readLoop()
127 go t.kexLoop()
128 return t
129 }
130
131 func newServerTransport(conn keyingTransport, clientVersion, serverVersion []byte, config *ServerConfig) *handshakeTransport {
132 t := newHandshakeTransport(conn, &config.Config, clientVersion, serverVersion)
133 t.hostKeys = config.hostKeys
134 go t.readLoop()
135 go t.kexLoop()
136 return t
137 }
138
139 func (t *handshakeTransport) getSessionID() []byte {
140 return t.sessionID
141 }
142
143 // waitSession waits for the session to be established. This should be
144 // the first thing to call after instantiating handshakeTransport.
145 func (t *handshakeTransport) waitSession() error {
146 p, err := t.readPacket()
147 if err != nil {
148 return err
149 }
150 if p[0] != msgNewKeys {
151 return fmt.Errorf("ssh: first packet should be msgNewKeys")
152 }
153
154 return nil
155 }
156
157 func (t *handshakeTransport) id() string {
158 if len(t.hostKeys) > 0 {
159 return "server"
160 }
161 return "client"
162 }
163
164 func (t *handshakeTransport) printPacket(p []byte, write bool) {
165 action := "got"
166 if write {
167 action = "sent"
168 }
169
170 if p[0] == msgChannelData || p[0] == msgChannelExtendedData {
171 log.Printf("%s %s data (packet %d bytes)", t.id(), action, len(p))
172 } else {
173 msg, err := decode(p)
174 log.Printf("%s %s %T %v (%v)", t.id(), action, msg, msg, err)
175 }
176 }
177
178 func (t *handshakeTransport) readPacket() ([]byte, error) {
179 p, ok := <-t.incoming
180 if !ok {
181 return nil, t.readError
182 }
183 return p, nil
184 }
185
186 func (t *handshakeTransport) readLoop() {
187 first := true
188 for {
189 p, err := t.readOnePacket(first)
190 first = false
191 if err != nil {
192 t.readError = err
193 close(t.incoming)
194 break
195 }
196 if p[0] == msgIgnore || p[0] == msgDebug {
197 continue
198 }
199 t.incoming <- p
200 }
201
202 // Stop writers too.
203 t.recordWriteError(t.readError)
204
205 // Unblock the writer should it wait for this.
206 close(t.startKex)
207
208 // Don't close t.requestKex; it's also written to from writePacket.
209 }
210
211 func (t *handshakeTransport) pushPacket(p []byte) error {
212 if debugHandshake {
213 t.printPacket(p, true)
214 }
215 return t.conn.writePacket(p)
216 }
217
218 func (t *handshakeTransport) getWriteError() error {
219 t.mu.Lock()
220 defer t.mu.Unlock()
221 return t.writeError
222 }
223
224 func (t *handshakeTransport) recordWriteError(err error) {
225 t.mu.Lock()
226 defer t.mu.Unlock()
227 if t.writeError == nil && err != nil {
228 t.writeError = err
229 }
230 }
231
232 func (t *handshakeTransport) requestKeyExchange() {
233 select {
234 case t.requestKex <- struct{}{}:
235 default:
236 // something already requested a kex, so do nothing.
237 }
238 }
239
240 func (t *handshakeTransport) kexLoop() {
241
242 write:
243 for t.getWriteError() == nil {
244 var request *pendingKex
245 var sent bool
246
247 for request == nil || !sent {
248 var ok bool
249 select {
250 case request, ok = <-t.startKex:
251 if !ok {
252 break write
253 }
254 case <-t.requestKex:
255 break
256 }
257
258 if !sent {
259 if err := t.sendKexInit(); err != nil {
260 t.recordWriteError(err)
261 break
262 }
263 sent = true
264 }
265 }
266
267 if err := t.getWriteError(); err != nil {
268 if request != nil {
269 request.done <- err
270 }
271 break
272 }
273
274 // We're not servicing t.requestKex, but that is OK:
275 // we never block on sending to t.requestKex.
276
277 // We're not servicing t.startKex, but the remote end
278 // has just sent us a kexInitMsg, so it can't send
279 // another key change request, until we close the done
280 // channel on the pendingKex request.
281
282 err := t.enterKeyExchange(request.otherInit)
283
284 t.mu.Lock()
285 t.writeError = err
286 t.sentInitPacket = nil
287 t.sentInitMsg = nil
288 t.writePacketsLeft = packetRekeyThreshold
289 if t.config.RekeyThreshold > 0 {
290 t.writeBytesLeft = int64(t.config.RekeyThreshold)
291 } else if t.algorithms != nil {
292 t.writeBytesLeft = t.algorithms.w.rekeyBytes()
293 }
294
295 // we have completed the key exchange. Since the
296 // reader is still blocked, it is safe to clear out
297 // the requestKex channel. This avoids the situation
298 // where: 1) we consumed our own request for the
299 // initial kex, and 2) the kex from the remote side
300 // caused another send on the requestKex channel,
301 clear:
302 for {
303 select {
304 case <-t.requestKex:
305 //
306 default:
307 break clear
308 }
309 }
310
311 request.done <- t.writeError
312
313 // kex finished. Push packets that we received while
314 // the kex was in progress. Don't look at t.startKex
315 // and don't increment writtenSinceKex: if we trigger
316 // another kex while we are still busy with the last
317 // one, things will become very confusing.
318 for _, p := range t.pendingPackets {
319 t.writeError = t.pushPacket(p)
320 if t.writeError != nil {
321 break
322 }
323 }
324 t.pendingPackets = t.pendingPackets[:0]
325 t.mu.Unlock()
326 }
327
328 // drain startKex channel. We don't service t.requestKex
329 // because nobody does blocking sends there.
330 go func() {
331 for init := range t.startKex {
332 init.done <- t.writeError
333 }
334 }()
335
336 // Unblock reader.
337 t.conn.Close()
338 }
339
340 // The protocol uses uint32 for packet counters, so we can't let them
341 // reach 1<<32. We will actually read and write more packets than
342 // this, though: the other side may send more packets, and after we
343 // hit this limit on writing we will send a few more packets for the
344 // key exchange itself.
345 const packetRekeyThreshold = (1 << 31)
346
347 func (t *handshakeTransport) readOnePacket(first bool) ([]byte, error) {
348 p, err := t.conn.readPacket()
349 if err != nil {
350 return nil, err
351 }
352
353 if t.readPacketsLeft > 0 {
354 t.readPacketsLeft--
355 } else {
356 t.requestKeyExchange()
357 }
358
359 if t.readBytesLeft > 0 {
360 t.readBytesLeft -= int64(len(p))
361 } else {
362 t.requestKeyExchange()
363 }
364
365 if debugHandshake {
366 t.printPacket(p, false)
367 }
368
369 if first && p[0] != msgKexInit {
370 return nil, fmt.Errorf("ssh: first packet should be msgKexInit")
371 }
372
373 if p[0] != msgKexInit {
374 return p, nil
375 }
376
377 firstKex := t.sessionID == nil
378
379 kex := pendingKex{
380 done: make(chan error, 1),
381 otherInit: p,
382 }
383 t.startKex <- &kex
384 err = <-kex.done
385
386 if debugHandshake {
387 log.Printf("%s exited key exchange (first %v), err %v", t.id(), firstKex, err)
388 }
389
390 if err != nil {
391 return nil, err
392 }
393
394 t.readPacketsLeft = packetRekeyThreshold
395 if t.config.RekeyThreshold > 0 {
396 t.readBytesLeft = int64(t.config.RekeyThreshold)
397 } else {
398 t.readBytesLeft = t.algorithms.r.rekeyBytes()
399 }
400
401 // By default, a key exchange is hidden from higher layers by
402 // translating it into msgIgnore.
403 successPacket := []byte{msgIgnore}
404 if firstKex {
405 // sendKexInit() for the first kex waits for
406 // msgNewKeys so the authentication process is
407 // guaranteed to happen over an encrypted transport.
408 successPacket = []byte{msgNewKeys}
409 }
410
411 return successPacket, nil
412 }
413
414 // sendKexInit sends a key change message.
415 func (t *handshakeTransport) sendKexInit() error {
416 t.mu.Lock()
417 defer t.mu.Unlock()
418 if t.sentInitMsg != nil {
419 // kexInits may be sent either in response to the other side,
420 // or because our side wants to initiate a key change, so we
421 // may have already sent a kexInit. In that case, don't send a
422 // second kexInit.
423 return nil
424 }
425
426 msg := &kexInitMsg{
427 KexAlgos: t.config.KeyExchanges,
428 CiphersClientServer: t.config.Ciphers,
429 CiphersServerClient: t.config.Ciphers,
430 MACsClientServer: t.config.MACs,
431 MACsServerClient: t.config.MACs,
432 CompressionClientServer: supportedCompressions,
433 CompressionServerClient: supportedCompressions,
434 }
435 io.ReadFull(rand.Reader, msg.Cookie[:])
436
437 if len(t.hostKeys) > 0 {
438 for _, k := range t.hostKeys {
439 msg.ServerHostKeyAlgos = append(
440 msg.ServerHostKeyAlgos, k.PublicKey().Type())
441 }
442 } else {
443 msg.ServerHostKeyAlgos = t.hostKeyAlgorithms
444 }
445 packet := Marshal(msg)
446
447 // writePacket destroys the contents, so save a copy.
448 packetCopy := make([]byte, len(packet))
449 copy(packetCopy, packet)
450
451 if err := t.pushPacket(packetCopy); err != nil {
452 return err
453 }
454
455 t.sentInitMsg = msg
456 t.sentInitPacket = packet
457
458 return nil
459 }
460
461 func (t *handshakeTransport) writePacket(p []byte) error {
462 switch p[0] {
463 case msgKexInit:
464 return errors.New("ssh: only handshakeTransport can send kexInit")
465 case msgNewKeys:
466 return errors.New("ssh: only handshakeTransport can send newKeys")
467 }
468
469 t.mu.Lock()
470 defer t.mu.Unlock()
471 if t.writeError != nil {
472 return t.writeError
473 }
474
475 if t.sentInitMsg != nil {
476 // Copy the packet so the writer can reuse the buffer.
477 cp := make([]byte, len(p))
478 copy(cp, p)
479 t.pendingPackets = append(t.pendingPackets, cp)
480 return nil
481 }
482
483 if t.writeBytesLeft > 0 {
484 t.writeBytesLeft -= int64(len(p))
485 } else {
486 t.requestKeyExchange()
487 }
488
489 if t.writePacketsLeft > 0 {
490 t.writePacketsLeft--
491 } else {
492 t.requestKeyExchange()
493 }
494
495 if err := t.pushPacket(p); err != nil {
496 t.writeError = err
497 }
498
499 return nil
500 }
501
502 func (t *handshakeTransport) Close() error {
503 return t.conn.Close()
504 }
505
506 func (t *handshakeTransport) enterKeyExchange(otherInitPacket []byte) error {
507 if debugHandshake {
508 log.Printf("%s entered key exchange", t.id())
509 }
510
511 otherInit := &kexInitMsg{}
512 if err := Unmarshal(otherInitPacket, otherInit); err != nil {
513 return err
514 }
515
516 magics := handshakeMagics{
517 clientVersion: t.clientVersion,
518 serverVersion: t.serverVersion,
519 clientKexInit: otherInitPacket,
520 serverKexInit: t.sentInitPacket,
521 }
522
523 clientInit := otherInit
524 serverInit := t.sentInitMsg
525 if len(t.hostKeys) == 0 {
526 clientInit, serverInit = serverInit, clientInit
527
528 magics.clientKexInit = t.sentInitPacket
529 magics.serverKexInit = otherInitPacket
530 }
531
532 var err error
533 t.algorithms, err = findAgreedAlgorithms(clientInit, serverInit)
534 if err != nil {
535 return err
536 }
537
538 // We don't send FirstKexFollows, but we handle receiving it.
539 //
540 // RFC 4253 section 7 defines the kex and the agreement method for
541 // first_kex_packet_follows. It states that the guessed packet
542 // should be ignored if the "kex algorithm and/or the host
543 // key algorithm is guessed wrong (server and client have
544 // different preferred algorithm), or if any of the other
545 // algorithms cannot be agreed upon". The other algorithms have
546 // already been checked above so the kex algorithm and host key
547 // algorithm are checked here.
548 if otherInit.FirstKexFollows && (clientInit.KexAlgos[0] != serverInit.KexAlgos[0] || clientInit.ServerHostKeyAlgos[0] != serverInit.ServerHostKeyAlgos[0]) {
549 // other side sent a kex message for the wrong algorithm,
550 // which we have to ignore.
551 if _, err := t.conn.readPacket(); err != nil {
552 return err
553 }
554 }
555
556 kex, ok := kexAlgoMap[t.algorithms.kex]
557 if !ok {
558 return fmt.Errorf("ssh: unexpected key exchange algorithm %v", t.algorithms.kex)
559 }
560
561 var result *kexResult
562 if len(t.hostKeys) > 0 {
563 result, err = t.server(kex, t.algorithms, &magics)
564 } else {
565 result, err = t.client(kex, t.algorithms, &magics)
566 }
567
568 if err != nil {
569 return err
570 }
571
572 if t.sessionID == nil {
573 t.sessionID = result.H
574 }
575 result.SessionID = t.sessionID
576
577 t.conn.prepareKeyChange(t.algorithms, result)
578 if err = t.conn.writePacket([]byte{msgNewKeys}); err != nil {
579 return err
580 }
581 if packet, err := t.conn.readPacket(); err != nil {
582 return err
583 } else if packet[0] != msgNewKeys {
584 return unexpectedMessageError(msgNewKeys, packet[0])
585 }
586
587 return nil
588 }
589
590 func (t *handshakeTransport) server(kex kexAlgorithm, algs *algorithms, magics *handshakeMagics) (*kexResult, error) {
591 var hostKey Signer
592 for _, k := range t.hostKeys {
593 if algs.hostKey == k.PublicKey().Type() {
594 hostKey = k
595 }
596 }
597
598 r, err := kex.Server(t.conn, t.config.Rand, magics, hostKey)
599 return r, err
600 }
601
602 func (t *handshakeTransport) client(kex kexAlgorithm, algs *algorithms, magics *handshakeMagics) (*kexResult, error) {
603 result, err := kex.Client(t.conn, t.config.Rand, magics)
604 if err != nil {
605 return nil, err
606 }
607
608 hostKey, err := ParsePublicKey(result.HostKey)
609 if err != nil {
610 return nil, err
611 }
612
613 if err := verifyHostKeySignature(hostKey, result); err != nil {
614 return nil, err
615 }
616
617 if t.hostKeyCallback != nil {
618 err = t.hostKeyCallback(t.dialAddress, t.remoteAddr, hostKey)
619 if err != nil {
620 return nil, err
621 }
622 }
623
624 return result, nil
625 }