github.com/slspeek/camlistore_namedsearch@v0.0.0-20140519202248-ed6f70f7721a/third_party/code.google.com/p/go.crypto/ssh/server.go (about) 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 "bytes" 9 "crypto" 10 "crypto/rand" 11 "crypto/rsa" 12 "crypto/x509" 13 "encoding/pem" 14 "errors" 15 "io" 16 "math/big" 17 "net" 18 "sync" 19 ) 20 21 type ServerConfig struct { 22 rsa *rsa.PrivateKey 23 rsaSerialized []byte 24 25 // Rand provides the source of entropy for key exchange. If Rand is 26 // nil, the cryptographic random reader in package crypto/rand will 27 // be used. 28 Rand io.Reader 29 30 // NoClientAuth is true if clients are allowed to connect without 31 // authenticating. 32 NoClientAuth bool 33 34 // PasswordCallback, if non-nil, is called when a user attempts to 35 // authenticate using a password. It may be called concurrently from 36 // several goroutines. 37 PasswordCallback func(conn *ServerConn, user, password string) bool 38 39 // PublicKeyCallback, if non-nil, is called when a client attempts public 40 // key authentication. It must return true iff the given public key is 41 // valid for the given user. 42 PublicKeyCallback func(conn *ServerConn, user, algo string, pubkey []byte) bool 43 44 // Cryptographic-related configuration. 45 Crypto CryptoConfig 46 } 47 48 func (c *ServerConfig) rand() io.Reader { 49 if c.Rand == nil { 50 return rand.Reader 51 } 52 return c.Rand 53 } 54 55 // SetRSAPrivateKey sets the private key for a Server. A Server must have a 56 // private key configured in order to accept connections. The private key must 57 // be in the form of a PEM encoded, PKCS#1, RSA private key. The file "id_rsa" 58 // typically contains such a key. 59 func (s *ServerConfig) SetRSAPrivateKey(pemBytes []byte) error { 60 block, _ := pem.Decode(pemBytes) 61 if block == nil { 62 return errors.New("ssh: no key found") 63 } 64 var err error 65 s.rsa, err = x509.ParsePKCS1PrivateKey(block.Bytes) 66 if err != nil { 67 return err 68 } 69 70 s.rsaSerialized = marshalRSA(s.rsa) 71 return nil 72 } 73 74 // marshalRSA serializes an RSA private key according to RFC 4256, section 6.6. 75 func marshalRSA(priv *rsa.PrivateKey) []byte { 76 e := new(big.Int).SetInt64(int64(priv.E)) 77 length := stringLength([]byte(hostAlgoRSA)) 78 length += intLength(e) 79 length += intLength(priv.N) 80 81 ret := make([]byte, length) 82 r := marshalString(ret, []byte(hostAlgoRSA)) 83 r = marshalInt(r, e) 84 r = marshalInt(r, priv.N) 85 86 return ret 87 } 88 89 // parseRSA parses an RSA key according to RFC 4256, section 6.6. 90 func parseRSA(in []byte) (pubKey *rsa.PublicKey, ok bool) { 91 algo, in, ok := parseString(in) 92 if !ok || string(algo) != hostAlgoRSA { 93 return nil, false 94 } 95 bigE, in, ok := parseInt(in) 96 if !ok || bigE.BitLen() > 24 { 97 return nil, false 98 } 99 e := bigE.Int64() 100 if e < 3 || e&1 == 0 { 101 return nil, false 102 } 103 N, in, ok := parseInt(in) 104 if !ok || len(in) > 0 { 105 return nil, false 106 } 107 return &rsa.PublicKey{ 108 N: N, 109 E: int(e), 110 }, true 111 } 112 113 func parseRSASig(in []byte) (sig []byte, ok bool) { 114 algo, in, ok := parseString(in) 115 if !ok || string(algo) != hostAlgoRSA { 116 return nil, false 117 } 118 sig, in, ok = parseString(in) 119 if len(in) > 0 { 120 ok = false 121 } 122 return 123 } 124 125 // cachedPubKey contains the results of querying whether a public key is 126 // acceptable for a user. The cache only applies to a single ServerConn. 127 type cachedPubKey struct { 128 user, algo string 129 pubKey []byte 130 result bool 131 } 132 133 const maxCachedPubKeys = 16 134 135 // A ServerConn represents an incomming connection. 136 type ServerConn struct { 137 *transport 138 config *ServerConfig 139 140 channels map[uint32]*channel 141 nextChanId uint32 142 143 // lock protects err and also allows Channels to serialise their writes 144 // to out. 145 lock sync.RWMutex 146 err error 147 148 // cachedPubKeys contains the cache results of tests for public keys. 149 // Since SSH clients will query whether a public key is acceptable 150 // before attempting to authenticate with it, we end up with duplicate 151 // queries for public key validity. 152 cachedPubKeys []cachedPubKey 153 154 // User holds the successfully authenticated user name. 155 // It is empty if no authentication is used. It is populated before 156 // any authentication callback is called and not assigned to after that. 157 User string 158 } 159 160 // Server returns a new SSH server connection 161 // using c as the underlying transport. 162 func Server(c net.Conn, config *ServerConfig) *ServerConn { 163 conn := &ServerConn{ 164 transport: newTransport(c, config.rand()), 165 channels: make(map[uint32]*channel), 166 config: config, 167 } 168 return conn 169 } 170 171 // kexDH performs Diffie-Hellman key agreement on a ServerConnection. The 172 // returned values are given the same names as in RFC 4253, section 8. 173 func (s *ServerConn) kexDH(group *dhGroup, hashFunc crypto.Hash, magics *handshakeMagics, hostKeyAlgo string) (H, K []byte, err error) { 174 packet, err := s.readPacket() 175 if err != nil { 176 return 177 } 178 var kexDHInit kexDHInitMsg 179 if err = unmarshal(&kexDHInit, packet, msgKexDHInit); err != nil { 180 return 181 } 182 183 if kexDHInit.X.Sign() == 0 || kexDHInit.X.Cmp(group.p) >= 0 { 184 return nil, nil, errors.New("client DH parameter out of bounds") 185 } 186 187 y, err := rand.Int(s.config.rand(), group.p) 188 if err != nil { 189 return 190 } 191 192 Y := new(big.Int).Exp(group.g, y, group.p) 193 kInt := new(big.Int).Exp(kexDHInit.X, y, group.p) 194 195 var serializedHostKey []byte 196 switch hostKeyAlgo { 197 case hostAlgoRSA: 198 serializedHostKey = s.config.rsaSerialized 199 default: 200 return nil, nil, errors.New("internal error") 201 } 202 203 h := hashFunc.New() 204 writeString(h, magics.clientVersion) 205 writeString(h, magics.serverVersion) 206 writeString(h, magics.clientKexInit) 207 writeString(h, magics.serverKexInit) 208 writeString(h, serializedHostKey) 209 writeInt(h, kexDHInit.X) 210 writeInt(h, Y) 211 K = make([]byte, intLength(kInt)) 212 marshalInt(K, kInt) 213 h.Write(K) 214 215 H = h.Sum(nil) 216 217 h.Reset() 218 h.Write(H) 219 hh := h.Sum(nil) 220 221 var sig []byte 222 switch hostKeyAlgo { 223 case hostAlgoRSA: 224 sig, err = rsa.SignPKCS1v15(s.config.rand(), s.config.rsa, hashFunc, hh) 225 if err != nil { 226 return 227 } 228 default: 229 return nil, nil, errors.New("internal error") 230 } 231 232 serializedSig := serializeSignature(hostAlgoRSA, sig) 233 234 kexDHReply := kexDHReplyMsg{ 235 HostKey: serializedHostKey, 236 Y: Y, 237 Signature: serializedSig, 238 } 239 packet = marshal(msgKexDHReply, kexDHReply) 240 241 err = s.writePacket(packet) 242 return 243 } 244 245 // serverVersion is the fixed identification string that Server will use. 246 var serverVersion = []byte("SSH-2.0-Go\r\n") 247 248 // Handshake performs an SSH transport and client authentication on the given ServerConn. 249 func (s *ServerConn) Handshake() error { 250 var magics handshakeMagics 251 if _, err := s.Write(serverVersion); err != nil { 252 return err 253 } 254 if err := s.Flush(); err != nil { 255 return err 256 } 257 magics.serverVersion = serverVersion[:len(serverVersion)-2] 258 259 version, err := readVersion(s) 260 if err != nil { 261 return err 262 } 263 magics.clientVersion = version 264 265 serverKexInit := kexInitMsg{ 266 KexAlgos: supportedKexAlgos, 267 ServerHostKeyAlgos: supportedHostKeyAlgos, 268 CiphersClientServer: s.config.Crypto.ciphers(), 269 CiphersServerClient: s.config.Crypto.ciphers(), 270 MACsClientServer: supportedMACs, 271 MACsServerClient: supportedMACs, 272 CompressionClientServer: supportedCompressions, 273 CompressionServerClient: supportedCompressions, 274 } 275 kexInitPacket := marshal(msgKexInit, serverKexInit) 276 magics.serverKexInit = kexInitPacket 277 278 if err := s.writePacket(kexInitPacket); err != nil { 279 return err 280 } 281 282 packet, err := s.readPacket() 283 if err != nil { 284 return err 285 } 286 287 magics.clientKexInit = packet 288 289 var clientKexInit kexInitMsg 290 if err = unmarshal(&clientKexInit, packet, msgKexInit); err != nil { 291 return err 292 } 293 294 kexAlgo, hostKeyAlgo, ok := findAgreedAlgorithms(s.transport, &clientKexInit, &serverKexInit) 295 if !ok { 296 return errors.New("ssh: no common algorithms") 297 } 298 299 if clientKexInit.FirstKexFollows && kexAlgo != clientKexInit.KexAlgos[0] { 300 // The client sent a Kex message for the wrong algorithm, 301 // which we have to ignore. 302 if _, err := s.readPacket(); err != nil { 303 return err 304 } 305 } 306 307 var H, K []byte 308 var hashFunc crypto.Hash 309 switch kexAlgo { 310 case kexAlgoDH14SHA1: 311 hashFunc = crypto.SHA1 312 dhGroup14Once.Do(initDHGroup14) 313 H, K, err = s.kexDH(dhGroup14, hashFunc, &magics, hostKeyAlgo) 314 default: 315 err = errors.New("ssh: unexpected key exchange algorithm " + kexAlgo) 316 } 317 if err != nil { 318 return err 319 } 320 321 if err = s.writePacket([]byte{msgNewKeys}); err != nil { 322 return err 323 } 324 if err = s.transport.writer.setupKeys(serverKeys, K, H, H, hashFunc); err != nil { 325 return err 326 } 327 if packet, err = s.readPacket(); err != nil { 328 return err 329 } 330 331 if packet[0] != msgNewKeys { 332 return UnexpectedMessageError{msgNewKeys, packet[0]} 333 } 334 if err = s.transport.reader.setupKeys(clientKeys, K, H, H, hashFunc); err != nil { 335 return err 336 } 337 if packet, err = s.readPacket(); err != nil { 338 return err 339 } 340 341 var serviceRequest serviceRequestMsg 342 if err = unmarshal(&serviceRequest, packet, msgServiceRequest); err != nil { 343 return err 344 } 345 if serviceRequest.Service != serviceUserAuth { 346 return errors.New("ssh: requested service '" + serviceRequest.Service + "' before authenticating") 347 } 348 serviceAccept := serviceAcceptMsg{ 349 Service: serviceUserAuth, 350 } 351 if err = s.writePacket(marshal(msgServiceAccept, serviceAccept)); err != nil { 352 return err 353 } 354 355 if err = s.authenticate(H); err != nil { 356 return err 357 } 358 return nil 359 } 360 361 func isAcceptableAlgo(algo string) bool { 362 return algo == hostAlgoRSA 363 } 364 365 // testPubKey returns true if the given public key is acceptable for the user. 366 func (s *ServerConn) testPubKey(user, algo string, pubKey []byte) bool { 367 if s.config.PublicKeyCallback == nil || !isAcceptableAlgo(algo) { 368 return false 369 } 370 371 for _, c := range s.cachedPubKeys { 372 if c.user == user && c.algo == algo && bytes.Equal(c.pubKey, pubKey) { 373 return c.result 374 } 375 } 376 377 result := s.config.PublicKeyCallback(s, user, algo, pubKey) 378 if len(s.cachedPubKeys) < maxCachedPubKeys { 379 c := cachedPubKey{ 380 user: user, 381 algo: algo, 382 pubKey: make([]byte, len(pubKey)), 383 result: result, 384 } 385 copy(c.pubKey, pubKey) 386 s.cachedPubKeys = append(s.cachedPubKeys, c) 387 } 388 389 return result 390 } 391 392 func (s *ServerConn) authenticate(H []byte) error { 393 var userAuthReq userAuthRequestMsg 394 var err error 395 var packet []byte 396 397 userAuthLoop: 398 for { 399 if packet, err = s.readPacket(); err != nil { 400 return err 401 } 402 if err = unmarshal(&userAuthReq, packet, msgUserAuthRequest); err != nil { 403 return err 404 } 405 406 if userAuthReq.Service != serviceSSH { 407 return errors.New("ssh: client attempted to negotiate for unknown service: " + userAuthReq.Service) 408 } 409 410 switch userAuthReq.Method { 411 case "none": 412 if s.config.NoClientAuth { 413 break userAuthLoop 414 } 415 case "password": 416 if s.config.PasswordCallback == nil { 417 break 418 } 419 payload := userAuthReq.Payload 420 if len(payload) < 1 || payload[0] != 0 { 421 return ParseError{msgUserAuthRequest} 422 } 423 payload = payload[1:] 424 password, payload, ok := parseString(payload) 425 if !ok || len(payload) > 0 { 426 return ParseError{msgUserAuthRequest} 427 } 428 429 s.User = userAuthReq.User 430 if s.config.PasswordCallback(s, userAuthReq.User, string(password)) { 431 break userAuthLoop 432 } 433 case "publickey": 434 if s.config.PublicKeyCallback == nil { 435 break 436 } 437 payload := userAuthReq.Payload 438 if len(payload) < 1 { 439 return ParseError{msgUserAuthRequest} 440 } 441 isQuery := payload[0] == 0 442 payload = payload[1:] 443 algoBytes, payload, ok := parseString(payload) 444 if !ok { 445 return ParseError{msgUserAuthRequest} 446 } 447 algo := string(algoBytes) 448 449 pubKey, payload, ok := parseString(payload) 450 if !ok { 451 return ParseError{msgUserAuthRequest} 452 } 453 if isQuery { 454 // The client can query if the given public key 455 // would be ok. 456 if len(payload) > 0 { 457 return ParseError{msgUserAuthRequest} 458 } 459 if s.testPubKey(userAuthReq.User, algo, pubKey) { 460 okMsg := userAuthPubKeyOkMsg{ 461 Algo: algo, 462 PubKey: string(pubKey), 463 } 464 if err = s.writePacket(marshal(msgUserAuthPubKeyOk, okMsg)); err != nil { 465 return err 466 } 467 continue userAuthLoop 468 } 469 } else { 470 sig, payload, ok := parseString(payload) 471 if !ok || len(payload) > 0 { 472 return ParseError{msgUserAuthRequest} 473 } 474 if !isAcceptableAlgo(algo) { 475 break 476 } 477 rsaSig, ok := parseRSASig(sig) 478 if !ok { 479 return ParseError{msgUserAuthRequest} 480 } 481 signedData := buildDataSignedForAuth(H, userAuthReq, algoBytes, pubKey) 482 switch algo { 483 case hostAlgoRSA: 484 hashFunc := crypto.SHA1 485 h := hashFunc.New() 486 h.Write(signedData) 487 digest := h.Sum(nil) 488 rsaKey, ok := parseRSA(pubKey) 489 if !ok { 490 return ParseError{msgUserAuthRequest} 491 } 492 if rsa.VerifyPKCS1v15(rsaKey, hashFunc, digest, rsaSig) != nil { 493 return ParseError{msgUserAuthRequest} 494 } 495 default: 496 return errors.New("ssh: isAcceptableAlgo incorrect") 497 } 498 s.User = userAuthReq.User 499 if s.testPubKey(userAuthReq.User, algo, pubKey) { 500 break userAuthLoop 501 } 502 } 503 } 504 505 var failureMsg userAuthFailureMsg 506 if s.config.PasswordCallback != nil { 507 failureMsg.Methods = append(failureMsg.Methods, "password") 508 } 509 if s.config.PublicKeyCallback != nil { 510 failureMsg.Methods = append(failureMsg.Methods, "publickey") 511 } 512 513 if len(failureMsg.Methods) == 0 { 514 return errors.New("ssh: no authentication methods configured but NoClientAuth is also false") 515 } 516 517 if err = s.writePacket(marshal(msgUserAuthFailure, failureMsg)); err != nil { 518 return err 519 } 520 } 521 522 packet = []byte{msgUserAuthSuccess} 523 if err = s.writePacket(packet); err != nil { 524 return err 525 } 526 527 return nil 528 } 529 530 const defaultWindowSize = 32768 531 532 // Accept reads and processes messages on a ServerConn. It must be called 533 // in order to demultiplex messages to any resulting Channels. 534 func (s *ServerConn) Accept() (Channel, error) { 535 if s.err != nil { 536 return nil, s.err 537 } 538 539 for { 540 packet, err := s.readPacket() 541 if err != nil { 542 543 s.lock.Lock() 544 s.err = err 545 s.lock.Unlock() 546 547 for _, c := range s.channels { 548 c.dead = true 549 c.handleData(nil) 550 } 551 552 return nil, err 553 } 554 555 switch packet[0] { 556 case msgChannelData: 557 if len(packet) < 9 { 558 // malformed data packet 559 return nil, ParseError{msgChannelData} 560 } 561 peersId := uint32(packet[1])<<24 | uint32(packet[2])<<16 | uint32(packet[3])<<8 | uint32(packet[4]) 562 s.lock.Lock() 563 c, ok := s.channels[peersId] 564 if !ok { 565 s.lock.Unlock() 566 continue 567 } 568 if length := int(packet[5])<<24 | int(packet[6])<<16 | int(packet[7])<<8 | int(packet[8]); length > 0 { 569 packet = packet[9:] 570 c.handleData(packet[:length]) 571 } 572 s.lock.Unlock() 573 default: 574 switch msg := decode(packet).(type) { 575 case *channelOpenMsg: 576 c := new(channel) 577 c.chanType = msg.ChanType 578 c.theirId = msg.PeersId 579 c.theirWindow = msg.PeersWindow 580 c.maxPacketSize = msg.MaxPacketSize 581 c.extraData = msg.TypeSpecificData 582 c.myWindow = defaultWindowSize 583 c.serverConn = s 584 c.cond = sync.NewCond(&c.lock) 585 c.pendingData = make([]byte, c.myWindow) 586 587 s.lock.Lock() 588 c.myId = s.nextChanId 589 s.nextChanId++ 590 s.channels[c.myId] = c 591 s.lock.Unlock() 592 return c, nil 593 594 case *channelRequestMsg: 595 s.lock.Lock() 596 c, ok := s.channels[msg.PeersId] 597 if !ok { 598 s.lock.Unlock() 599 continue 600 } 601 c.handlePacket(msg) 602 s.lock.Unlock() 603 604 case *channelEOFMsg: 605 s.lock.Lock() 606 c, ok := s.channels[msg.PeersId] 607 if !ok { 608 s.lock.Unlock() 609 continue 610 } 611 c.handlePacket(msg) 612 s.lock.Unlock() 613 614 case *channelCloseMsg: 615 s.lock.Lock() 616 c, ok := s.channels[msg.PeersId] 617 if !ok { 618 s.lock.Unlock() 619 continue 620 } 621 c.handlePacket(msg) 622 s.lock.Unlock() 623 624 case *globalRequestMsg: 625 if msg.WantReply { 626 if err := s.writePacket([]byte{msgRequestFailure}); err != nil { 627 return nil, err 628 } 629 } 630 631 case UnexpectedMessageError: 632 return nil, msg 633 case *disconnectMsg: 634 return nil, io.EOF 635 default: 636 // Unknown message. Ignore. 637 } 638 } 639 } 640 641 panic("unreachable") 642 } 643 644 // A Listener implements a network listener (net.Listener) for SSH connections. 645 type Listener struct { 646 listener net.Listener 647 config *ServerConfig 648 } 649 650 // Accept waits for and returns the next incoming SSH connection. 651 // The receiver should call Handshake() in another goroutine 652 // to avoid blocking the accepter. 653 func (l *Listener) Accept() (*ServerConn, error) { 654 c, err := l.listener.Accept() 655 if err != nil { 656 return nil, err 657 } 658 conn := Server(c, l.config) 659 return conn, nil 660 } 661 662 // Addr returns the listener's network address. 663 func (l *Listener) Addr() net.Addr { 664 return l.listener.Addr() 665 } 666 667 // Close closes the listener. 668 func (l *Listener) Close() error { 669 return l.listener.Close() 670 } 671 672 // Listen creates an SSH listener accepting connections on 673 // the given network address using net.Listen. 674 func Listen(network, addr string, config *ServerConfig) (*Listener, error) { 675 l, err := net.Listen(network, addr) 676 if err != nil { 677 return nil, err 678 } 679 return &Listener{ 680 l, 681 config, 682 }, nil 683 }