handshake.go (19753B)
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 writePacketsLeft uint32 67 writeBytesLeft int64 68 69 // If the read loop wants to schedule a kex, it pings this 70 // channel, and the write loop will send out a kex 71 // message. 72 requestKex chan struct{} 73 74 // If the other side requests or confirms a kex, its kexInit 75 // packet is sent here for the write loop to find it. 76 startKex chan *pendingKex 77 kexLoopDone chan struct{} // closed (with writeError non-nil) when kexLoop exits 78 79 // data for host key checking 80 hostKeyCallback HostKeyCallback 81 dialAddress string 82 remoteAddr net.Addr 83 84 // bannerCallback is non-empty if we are the client and it has been set in 85 // ClientConfig. In that case it is called during the user authentication 86 // dance to handle a custom server's message. 87 bannerCallback BannerCallback 88 89 // Algorithms agreed in the last key exchange. 90 algorithms *algorithms 91 92 // Counters exclusively owned by readLoop. 93 readPacketsLeft uint32 94 readBytesLeft int64 95 96 // The session ID or nil if first kex did not complete yet. 97 sessionID []byte 98 } 99 100 type pendingKex struct { 101 otherInit []byte 102 done chan error 103 } 104 105 func newHandshakeTransport(conn keyingTransport, config *Config, clientVersion, serverVersion []byte) *handshakeTransport { 106 t := &handshakeTransport{ 107 conn: conn, 108 serverVersion: serverVersion, 109 clientVersion: clientVersion, 110 incoming: make(chan []byte, chanSize), 111 requestKex: make(chan struct{}, 1), 112 startKex: make(chan *pendingKex), 113 kexLoopDone: make(chan struct{}), 114 115 config: config, 116 } 117 t.resetReadThresholds() 118 t.resetWriteThresholds() 119 120 // We always start with a mandatory key exchange. 121 t.requestKex <- struct{}{} 122 return t 123 } 124 125 func newClientTransport(conn keyingTransport, clientVersion, serverVersion []byte, config *ClientConfig, dialAddr string, addr net.Addr) *handshakeTransport { 126 t := newHandshakeTransport(conn, &config.Config, clientVersion, serverVersion) 127 t.dialAddress = dialAddr 128 t.remoteAddr = addr 129 t.hostKeyCallback = config.HostKeyCallback 130 t.bannerCallback = config.BannerCallback 131 if config.HostKeyAlgorithms != nil { 132 t.hostKeyAlgorithms = config.HostKeyAlgorithms 133 } else { 134 t.hostKeyAlgorithms = supportedHostKeyAlgos 135 } 136 go t.readLoop() 137 go t.kexLoop() 138 return t 139 } 140 141 func newServerTransport(conn keyingTransport, clientVersion, serverVersion []byte, config *ServerConfig) *handshakeTransport { 142 t := newHandshakeTransport(conn, &config.Config, clientVersion, serverVersion) 143 t.hostKeys = config.hostKeys 144 go t.readLoop() 145 go t.kexLoop() 146 return t 147 } 148 149 func (t *handshakeTransport) getSessionID() []byte { 150 return t.sessionID 151 } 152 153 // waitSession waits for the session to be established. This should be 154 // the first thing to call after instantiating handshakeTransport. 155 func (t *handshakeTransport) waitSession() error { 156 p, err := t.readPacket() 157 if err != nil { 158 return err 159 } 160 if p[0] != msgNewKeys { 161 return fmt.Errorf("ssh: first packet should be msgNewKeys") 162 } 163 164 return nil 165 } 166 167 func (t *handshakeTransport) id() string { 168 if len(t.hostKeys) > 0 { 169 return "server" 170 } 171 return "client" 172 } 173 174 func (t *handshakeTransport) printPacket(p []byte, write bool) { 175 action := "got" 176 if write { 177 action = "sent" 178 } 179 180 if p[0] == msgChannelData || p[0] == msgChannelExtendedData { 181 log.Printf("%s %s data (packet %d bytes)", t.id(), action, len(p)) 182 } else { 183 msg, err := decode(p) 184 log.Printf("%s %s %T %v (%v)", t.id(), action, msg, msg, err) 185 } 186 } 187 188 func (t *handshakeTransport) readPacket() ([]byte, error) { 189 p, ok := <-t.incoming 190 if !ok { 191 return nil, t.readError 192 } 193 return p, nil 194 } 195 196 func (t *handshakeTransport) readLoop() { 197 first := true 198 for { 199 p, err := t.readOnePacket(first) 200 first = false 201 if err != nil { 202 t.readError = err 203 close(t.incoming) 204 break 205 } 206 if p[0] == msgIgnore || p[0] == msgDebug { 207 continue 208 } 209 t.incoming <- p 210 } 211 212 // Stop writers too. 213 t.recordWriteError(t.readError) 214 215 // Unblock the writer should it wait for this. 216 close(t.startKex) 217 218 // Don't close t.requestKex; it's also written to from writePacket. 219 } 220 221 func (t *handshakeTransport) pushPacket(p []byte) error { 222 if debugHandshake { 223 t.printPacket(p, true) 224 } 225 return t.conn.writePacket(p) 226 } 227 228 func (t *handshakeTransport) getWriteError() error { 229 t.mu.Lock() 230 defer t.mu.Unlock() 231 return t.writeError 232 } 233 234 func (t *handshakeTransport) recordWriteError(err error) { 235 t.mu.Lock() 236 defer t.mu.Unlock() 237 if t.writeError == nil && err != nil { 238 t.writeError = err 239 } 240 } 241 242 func (t *handshakeTransport) requestKeyExchange() { 243 select { 244 case t.requestKex <- struct{}{}: 245 default: 246 // something already requested a kex, so do nothing. 247 } 248 } 249 250 func (t *handshakeTransport) resetWriteThresholds() { 251 t.writePacketsLeft = packetRekeyThreshold 252 if t.config.RekeyThreshold > 0 { 253 t.writeBytesLeft = int64(t.config.RekeyThreshold) 254 } else if t.algorithms != nil { 255 t.writeBytesLeft = t.algorithms.w.rekeyBytes() 256 } else { 257 t.writeBytesLeft = 1 << 30 258 } 259 } 260 261 func (t *handshakeTransport) kexLoop() { 262 263 write: 264 for t.getWriteError() == nil { 265 var request *pendingKex 266 var sent bool 267 268 for request == nil || !sent { 269 var ok bool 270 select { 271 case request, ok = <-t.startKex: 272 if !ok { 273 break write 274 } 275 case <-t.requestKex: 276 break 277 } 278 279 if !sent { 280 if err := t.sendKexInit(); err != nil { 281 t.recordWriteError(err) 282 break 283 } 284 sent = true 285 } 286 } 287 288 if err := t.getWriteError(); err != nil { 289 if request != nil { 290 request.done <- err 291 } 292 break 293 } 294 295 // We're not servicing t.requestKex, but that is OK: 296 // we never block on sending to t.requestKex. 297 298 // We're not servicing t.startKex, but the remote end 299 // has just sent us a kexInitMsg, so it can't send 300 // another key change request, until we close the done 301 // channel on the pendingKex request. 302 303 err := t.enterKeyExchange(request.otherInit) 304 305 t.mu.Lock() 306 t.writeError = err 307 t.sentInitPacket = nil 308 t.sentInitMsg = nil 309 310 t.resetWriteThresholds() 311 312 // we have completed the key exchange. Since the 313 // reader is still blocked, it is safe to clear out 314 // the requestKex channel. This avoids the situation 315 // where: 1) we consumed our own request for the 316 // initial kex, and 2) the kex from the remote side 317 // caused another send on the requestKex channel, 318 clear: 319 for { 320 select { 321 case <-t.requestKex: 322 // 323 default: 324 break clear 325 } 326 } 327 328 request.done <- t.writeError 329 330 // kex finished. Push packets that we received while 331 // the kex was in progress. Don't look at t.startKex 332 // and don't increment writtenSinceKex: if we trigger 333 // another kex while we are still busy with the last 334 // one, things will become very confusing. 335 for _, p := range t.pendingPackets { 336 t.writeError = t.pushPacket(p) 337 if t.writeError != nil { 338 break 339 } 340 } 341 t.pendingPackets = t.pendingPackets[:0] 342 t.mu.Unlock() 343 } 344 345 // Unblock reader. 346 t.conn.Close() 347 348 // drain startKex channel. We don't service t.requestKex 349 // because nobody does blocking sends there. 350 for request := range t.startKex { 351 request.done <- t.getWriteError() 352 } 353 354 // Mark that the loop is done so that Close can return. 355 close(t.kexLoopDone) 356 } 357 358 // The protocol uses uint32 for packet counters, so we can't let them 359 // reach 1<<32. We will actually read and write more packets than 360 // this, though: the other side may send more packets, and after we 361 // hit this limit on writing we will send a few more packets for the 362 // key exchange itself. 363 const packetRekeyThreshold = (1 << 31) 364 365 func (t *handshakeTransport) resetReadThresholds() { 366 t.readPacketsLeft = packetRekeyThreshold 367 if t.config.RekeyThreshold > 0 { 368 t.readBytesLeft = int64(t.config.RekeyThreshold) 369 } else if t.algorithms != nil { 370 t.readBytesLeft = t.algorithms.r.rekeyBytes() 371 } else { 372 t.readBytesLeft = 1 << 30 373 } 374 } 375 376 func (t *handshakeTransport) readOnePacket(first bool) ([]byte, error) { 377 p, err := t.conn.readPacket() 378 if err != nil { 379 return nil, err 380 } 381 382 if t.readPacketsLeft > 0 { 383 t.readPacketsLeft-- 384 } else { 385 t.requestKeyExchange() 386 } 387 388 if t.readBytesLeft > 0 { 389 t.readBytesLeft -= int64(len(p)) 390 } else { 391 t.requestKeyExchange() 392 } 393 394 if debugHandshake { 395 t.printPacket(p, false) 396 } 397 398 if first && p[0] != msgKexInit { 399 return nil, fmt.Errorf("ssh: first packet should be msgKexInit") 400 } 401 402 if p[0] != msgKexInit { 403 return p, nil 404 } 405 406 firstKex := t.sessionID == nil 407 408 kex := pendingKex{ 409 done: make(chan error, 1), 410 otherInit: p, 411 } 412 t.startKex <- &kex 413 err = <-kex.done 414 415 if debugHandshake { 416 log.Printf("%s exited key exchange (first %v), err %v", t.id(), firstKex, err) 417 } 418 419 if err != nil { 420 return nil, err 421 } 422 423 t.resetReadThresholds() 424 425 // By default, a key exchange is hidden from higher layers by 426 // translating it into msgIgnore. 427 successPacket := []byte{msgIgnore} 428 if firstKex { 429 // sendKexInit() for the first kex waits for 430 // msgNewKeys so the authentication process is 431 // guaranteed to happen over an encrypted transport. 432 successPacket = []byte{msgNewKeys} 433 } 434 435 return successPacket, nil 436 } 437 438 // sendKexInit sends a key change message. 439 func (t *handshakeTransport) sendKexInit() error { 440 t.mu.Lock() 441 defer t.mu.Unlock() 442 if t.sentInitMsg != nil { 443 // kexInits may be sent either in response to the other side, 444 // or because our side wants to initiate a key change, so we 445 // may have already sent a kexInit. In that case, don't send a 446 // second kexInit. 447 return nil 448 } 449 450 msg := &kexInitMsg{ 451 KexAlgos: t.config.KeyExchanges, 452 CiphersClientServer: t.config.Ciphers, 453 CiphersServerClient: t.config.Ciphers, 454 MACsClientServer: t.config.MACs, 455 MACsServerClient: t.config.MACs, 456 CompressionClientServer: supportedCompressions, 457 CompressionServerClient: supportedCompressions, 458 } 459 io.ReadFull(rand.Reader, msg.Cookie[:]) 460 461 isServer := len(t.hostKeys) > 0 462 if isServer { 463 for _, k := range t.hostKeys { 464 // If k is an AlgorithmSigner, presume it supports all signature algorithms 465 // associated with the key format. (Ideally AlgorithmSigner would have a 466 // method to advertise supported algorithms, but it doesn't. This means that 467 // adding support for a new algorithm is a breaking change, as we will 468 // immediately negotiate it even if existing implementations don't support 469 // it. If that ever happens, we'll have to figure something out.) 470 // If k is not an AlgorithmSigner, we can only assume it only supports the 471 // algorithms that matches the key format. (This means that Sign can't pick 472 // a different default.) 473 keyFormat := k.PublicKey().Type() 474 if _, ok := k.(AlgorithmSigner); ok { 475 msg.ServerHostKeyAlgos = append(msg.ServerHostKeyAlgos, algorithmsForKeyFormat(keyFormat)...) 476 } else { 477 msg.ServerHostKeyAlgos = append(msg.ServerHostKeyAlgos, keyFormat) 478 } 479 } 480 } else { 481 msg.ServerHostKeyAlgos = t.hostKeyAlgorithms 482 483 // As a client we opt in to receiving SSH_MSG_EXT_INFO so we know what 484 // algorithms the server supports for public key authentication. See RFC 485 // 8308, Section 2.1. 486 if firstKeyExchange := t.sessionID == nil; firstKeyExchange { 487 msg.KexAlgos = make([]string, 0, len(t.config.KeyExchanges)+1) 488 msg.KexAlgos = append(msg.KexAlgos, t.config.KeyExchanges...) 489 msg.KexAlgos = append(msg.KexAlgos, "ext-info-c") 490 } 491 } 492 493 packet := Marshal(msg) 494 495 // writePacket destroys the contents, so save a copy. 496 packetCopy := make([]byte, len(packet)) 497 copy(packetCopy, packet) 498 499 if err := t.pushPacket(packetCopy); err != nil { 500 return err 501 } 502 503 t.sentInitMsg = msg 504 t.sentInitPacket = packet 505 506 return nil 507 } 508 509 func (t *handshakeTransport) writePacket(p []byte) error { 510 switch p[0] { 511 case msgKexInit: 512 return errors.New("ssh: only handshakeTransport can send kexInit") 513 case msgNewKeys: 514 return errors.New("ssh: only handshakeTransport can send newKeys") 515 } 516 517 t.mu.Lock() 518 defer t.mu.Unlock() 519 if t.writeError != nil { 520 return t.writeError 521 } 522 523 if t.sentInitMsg != nil { 524 // Copy the packet so the writer can reuse the buffer. 525 cp := make([]byte, len(p)) 526 copy(cp, p) 527 t.pendingPackets = append(t.pendingPackets, cp) 528 return nil 529 } 530 531 if t.writeBytesLeft > 0 { 532 t.writeBytesLeft -= int64(len(p)) 533 } else { 534 t.requestKeyExchange() 535 } 536 537 if t.writePacketsLeft > 0 { 538 t.writePacketsLeft-- 539 } else { 540 t.requestKeyExchange() 541 } 542 543 if err := t.pushPacket(p); err != nil { 544 t.writeError = err 545 } 546 547 return nil 548 } 549 550 func (t *handshakeTransport) Close() error { 551 // Close the connection. This should cause the readLoop goroutine to wake up 552 // and close t.startKex, which will shut down kexLoop if running. 553 err := t.conn.Close() 554 555 // Wait for the kexLoop goroutine to complete. 556 // At that point we know that the readLoop goroutine is complete too, 557 // because kexLoop itself waits for readLoop to close the startKex channel. 558 <-t.kexLoopDone 559 560 return err 561 } 562 563 func (t *handshakeTransport) enterKeyExchange(otherInitPacket []byte) error { 564 if debugHandshake { 565 log.Printf("%s entered key exchange", t.id()) 566 } 567 568 otherInit := &kexInitMsg{} 569 if err := Unmarshal(otherInitPacket, otherInit); err != nil { 570 return err 571 } 572 573 magics := handshakeMagics{ 574 clientVersion: t.clientVersion, 575 serverVersion: t.serverVersion, 576 clientKexInit: otherInitPacket, 577 serverKexInit: t.sentInitPacket, 578 } 579 580 clientInit := otherInit 581 serverInit := t.sentInitMsg 582 isClient := len(t.hostKeys) == 0 583 if isClient { 584 clientInit, serverInit = serverInit, clientInit 585 586 magics.clientKexInit = t.sentInitPacket 587 magics.serverKexInit = otherInitPacket 588 } 589 590 var err error 591 t.algorithms, err = findAgreedAlgorithms(isClient, clientInit, serverInit) 592 if err != nil { 593 return err 594 } 595 596 // We don't send FirstKexFollows, but we handle receiving it. 597 // 598 // RFC 4253 section 7 defines the kex and the agreement method for 599 // first_kex_packet_follows. It states that the guessed packet 600 // should be ignored if the "kex algorithm and/or the host 601 // key algorithm is guessed wrong (server and client have 602 // different preferred algorithm), or if any of the other 603 // algorithms cannot be agreed upon". The other algorithms have 604 // already been checked above so the kex algorithm and host key 605 // algorithm are checked here. 606 if otherInit.FirstKexFollows && (clientInit.KexAlgos[0] != serverInit.KexAlgos[0] || clientInit.ServerHostKeyAlgos[0] != serverInit.ServerHostKeyAlgos[0]) { 607 // other side sent a kex message for the wrong algorithm, 608 // which we have to ignore. 609 if _, err := t.conn.readPacket(); err != nil { 610 return err 611 } 612 } 613 614 kex, ok := kexAlgoMap[t.algorithms.kex] 615 if !ok { 616 return fmt.Errorf("ssh: unexpected key exchange algorithm %v", t.algorithms.kex) 617 } 618 619 var result *kexResult 620 if len(t.hostKeys) > 0 { 621 result, err = t.server(kex, &magics) 622 } else { 623 result, err = t.client(kex, &magics) 624 } 625 626 if err != nil { 627 return err 628 } 629 630 firstKeyExchange := t.sessionID == nil 631 if firstKeyExchange { 632 t.sessionID = result.H 633 } 634 result.SessionID = t.sessionID 635 636 if err := t.conn.prepareKeyChange(t.algorithms, result); err != nil { 637 return err 638 } 639 if err = t.conn.writePacket([]byte{msgNewKeys}); err != nil { 640 return err 641 } 642 643 // On the server side, after the first SSH_MSG_NEWKEYS, send a SSH_MSG_EXT_INFO 644 // message with the server-sig-algs extension if the client supports it. See 645 // RFC 8308, Sections 2.4 and 3.1. 646 if !isClient && firstKeyExchange && contains(clientInit.KexAlgos, "ext-info-c") { 647 extInfo := &extInfoMsg{ 648 NumExtensions: 1, 649 Payload: make([]byte, 0, 4+15+4+len(supportedPubKeyAuthAlgosList)), 650 } 651 extInfo.Payload = appendInt(extInfo.Payload, len("server-sig-algs")) 652 extInfo.Payload = append(extInfo.Payload, "server-sig-algs"...) 653 extInfo.Payload = appendInt(extInfo.Payload, len(supportedPubKeyAuthAlgosList)) 654 extInfo.Payload = append(extInfo.Payload, supportedPubKeyAuthAlgosList...) 655 if err := t.conn.writePacket(Marshal(extInfo)); err != nil { 656 return err 657 } 658 } 659 660 if packet, err := t.conn.readPacket(); err != nil { 661 return err 662 } else if packet[0] != msgNewKeys { 663 return unexpectedMessageError(msgNewKeys, packet[0]) 664 } 665 666 return nil 667 } 668 669 // algorithmSignerWrapper is an AlgorithmSigner that only supports the default 670 // key format algorithm. 671 // 672 // This is technically a violation of the AlgorithmSigner interface, but it 673 // should be unreachable given where we use this. Anyway, at least it returns an 674 // error instead of panicing or producing an incorrect signature. 675 type algorithmSignerWrapper struct { 676 Signer 677 } 678 679 func (a algorithmSignerWrapper) SignWithAlgorithm(rand io.Reader, data []byte, algorithm string) (*Signature, error) { 680 if algorithm != underlyingAlgo(a.PublicKey().Type()) { 681 return nil, errors.New("ssh: internal error: algorithmSignerWrapper invoked with non-default algorithm") 682 } 683 return a.Sign(rand, data) 684 } 685 686 func pickHostKey(hostKeys []Signer, algo string) AlgorithmSigner { 687 for _, k := range hostKeys { 688 if algo == k.PublicKey().Type() { 689 return algorithmSignerWrapper{k} 690 } 691 k, ok := k.(AlgorithmSigner) 692 if !ok { 693 continue 694 } 695 for _, a := range algorithmsForKeyFormat(k.PublicKey().Type()) { 696 if algo == a { 697 return k 698 } 699 } 700 } 701 return nil 702 } 703 704 func (t *handshakeTransport) server(kex kexAlgorithm, magics *handshakeMagics) (*kexResult, error) { 705 hostKey := pickHostKey(t.hostKeys, t.algorithms.hostKey) 706 if hostKey == nil { 707 return nil, errors.New("ssh: internal error: negotiated unsupported signature type") 708 } 709 710 r, err := kex.Server(t.conn, t.config.Rand, magics, hostKey, t.algorithms.hostKey) 711 return r, err 712 } 713 714 func (t *handshakeTransport) client(kex kexAlgorithm, magics *handshakeMagics) (*kexResult, error) { 715 result, err := kex.Client(t.conn, t.config.Rand, magics) 716 if err != nil { 717 return nil, err 718 } 719 720 hostKey, err := ParsePublicKey(result.HostKey) 721 if err != nil { 722 return nil, err 723 } 724 725 if err := verifyHostKeySignature(hostKey, t.algorithms.hostKey, result); err != nil { 726 return nil, err 727 } 728 729 err = t.hostKeyCallback(t.dialAddress, t.remoteAddr, hostKey) 730 if err != nil { 731 return nil, err 732 } 733 734 return result, nil 735 }