server.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688
  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. package ssh
  5. import (
  6. "bytes"
  7. "crypto/rand"
  8. "encoding/binary"
  9. "errors"
  10. "fmt"
  11. "io"
  12. "net"
  13. "sync"
  14. _ "crypto/sha1"
  15. )
  16. type ServerConfig struct {
  17. hostKeys []Signer
  18. // Rand provides the source of entropy for key exchange. If Rand is
  19. // nil, the cryptographic random reader in package crypto/rand will
  20. // be used.
  21. Rand io.Reader
  22. // NoClientAuth is true if clients are allowed to connect without
  23. // authenticating.
  24. NoClientAuth bool
  25. // PasswordCallback, if non-nil, is called when a user attempts to
  26. // authenticate using a password. It may be called concurrently from
  27. // several goroutines.
  28. PasswordCallback func(conn *ServerConn, user, password string) bool
  29. // PublicKeyCallback, if non-nil, is called when a client attempts public
  30. // key authentication. It must return true iff the given public key is
  31. // valid for the given user.
  32. PublicKeyCallback func(conn *ServerConn, user, algo string, pubkey []byte) bool
  33. // KeyboardInteractiveCallback, if non-nil, is called when
  34. // keyboard-interactive authentication is selected (RFC
  35. // 4256). The client object's Challenge function should be
  36. // used to query the user. The callback may offer multiple
  37. // Challenge rounds. To avoid information leaks, the client
  38. // should be presented a challenge even if the user is
  39. // unknown.
  40. KeyboardInteractiveCallback func(conn *ServerConn, user string, client ClientKeyboardInteractive) bool
  41. // Cryptographic-related configuration.
  42. Crypto CryptoConfig
  43. }
  44. func (c *ServerConfig) rand() io.Reader {
  45. if c.Rand == nil {
  46. return rand.Reader
  47. }
  48. return c.Rand
  49. }
  50. // AddHostKey adds a private key as a host key. If an existing host
  51. // key exists with the same algorithm, it is overwritten.
  52. func (s *ServerConfig) AddHostKey(key Signer) {
  53. for i, k := range s.hostKeys {
  54. if k.PublicKey().PublicKeyAlgo() == key.PublicKey().PublicKeyAlgo() {
  55. s.hostKeys[i] = key
  56. return
  57. }
  58. }
  59. s.hostKeys = append(s.hostKeys, key)
  60. }
  61. // SetRSAPrivateKey sets the private key for a Server. A Server must have a
  62. // private key configured in order to accept connections. The private key must
  63. // be in the form of a PEM encoded, PKCS#1, RSA private key. The file "id_rsa"
  64. // typically contains such a key.
  65. func (s *ServerConfig) SetRSAPrivateKey(pemBytes []byte) error {
  66. priv, err := ParsePrivateKey(pemBytes)
  67. if err != nil {
  68. return err
  69. }
  70. s.AddHostKey(priv)
  71. return nil
  72. }
  73. // cachedPubKey contains the results of querying whether a public key is
  74. // acceptable for a user. The cache only applies to a single ServerConn.
  75. type cachedPubKey struct {
  76. user, algo string
  77. pubKey []byte
  78. result bool
  79. }
  80. const maxCachedPubKeys = 16
  81. // A ServerConn represents an incoming connection.
  82. type ServerConn struct {
  83. *transport
  84. config *ServerConfig
  85. channels map[uint32]*serverChan
  86. nextChanId uint32
  87. // lock protects err and channels.
  88. lock sync.Mutex
  89. err error
  90. // cachedPubKeys contains the cache results of tests for public keys.
  91. // Since SSH clients will query whether a public key is acceptable
  92. // before attempting to authenticate with it, we end up with duplicate
  93. // queries for public key validity.
  94. cachedPubKeys []cachedPubKey
  95. // User holds the successfully authenticated user name.
  96. // It is empty if no authentication is used. It is populated before
  97. // any authentication callback is called and not assigned to after that.
  98. User string
  99. // ClientVersion is the client's version, populated after
  100. // Handshake is called. It should not be modified.
  101. ClientVersion []byte
  102. }
  103. // Server returns a new SSH server connection
  104. // using c as the underlying transport.
  105. func Server(c net.Conn, config *ServerConfig) *ServerConn {
  106. return &ServerConn{
  107. transport: newTransport(c, config.rand(), false /* not client */),
  108. channels: make(map[uint32]*serverChan),
  109. config: config,
  110. }
  111. }
  112. // signAndMarshal signs the data with the appropriate algorithm,
  113. // and serializes the result in SSH wire format.
  114. func signAndMarshal(k Signer, rand io.Reader, data []byte) ([]byte, error) {
  115. sig, err := k.Sign(rand, data)
  116. if err != nil {
  117. return nil, err
  118. }
  119. return serializeSignature(k.PublicKey().PrivateKeyAlgo(), sig), nil
  120. }
  121. // serverVersion is the fixed identification string that Server will use.
  122. var serverVersion = []byte("SSH-2.0-Go\r\n")
  123. // Handshake performs an SSH transport and client authentication on the given ServerConn.
  124. func (s *ServerConn) Handshake() (err error) {
  125. if _, err = s.Write(serverVersion); err != nil {
  126. return
  127. }
  128. if err := s.Flush(); err != nil {
  129. return err
  130. }
  131. s.ClientVersion, err = readVersion(s)
  132. if err != nil {
  133. return
  134. }
  135. if err = s.clientInitHandshake(nil, nil); err != nil {
  136. return
  137. }
  138. var packet []byte
  139. if packet, err = s.readPacket(); err != nil {
  140. return
  141. }
  142. var serviceRequest serviceRequestMsg
  143. if err = unmarshal(&serviceRequest, packet, msgServiceRequest); err != nil {
  144. return
  145. }
  146. if serviceRequest.Service != serviceUserAuth {
  147. return errors.New("ssh: requested service '" + serviceRequest.Service + "' before authenticating")
  148. }
  149. serviceAccept := serviceAcceptMsg{
  150. Service: serviceUserAuth,
  151. }
  152. if err = s.writePacket(marshal(msgServiceAccept, serviceAccept)); err != nil {
  153. return
  154. }
  155. if err = s.authenticate(s.transport.sessionID); err != nil {
  156. return
  157. }
  158. return
  159. }
  160. func (s *ServerConn) clientInitHandshake(clientKexInit *kexInitMsg, clientKexInitPacket []byte) (err error) {
  161. serverKexInit := kexInitMsg{
  162. KexAlgos: s.config.Crypto.kexes(),
  163. CiphersClientServer: s.config.Crypto.ciphers(),
  164. CiphersServerClient: s.config.Crypto.ciphers(),
  165. MACsClientServer: s.config.Crypto.macs(),
  166. MACsServerClient: s.config.Crypto.macs(),
  167. CompressionClientServer: supportedCompressions,
  168. CompressionServerClient: supportedCompressions,
  169. }
  170. for _, k := range s.config.hostKeys {
  171. serverKexInit.ServerHostKeyAlgos = append(
  172. serverKexInit.ServerHostKeyAlgos, k.PublicKey().PublicKeyAlgo())
  173. }
  174. serverKexInitPacket := marshal(msgKexInit, serverKexInit)
  175. if err = s.writePacket(serverKexInitPacket); err != nil {
  176. return
  177. }
  178. if clientKexInitPacket == nil {
  179. clientKexInit = new(kexInitMsg)
  180. if clientKexInitPacket, err = s.readPacket(); err != nil {
  181. return
  182. }
  183. if err = unmarshal(clientKexInit, clientKexInitPacket, msgKexInit); err != nil {
  184. return
  185. }
  186. }
  187. algs := findAgreedAlgorithms(clientKexInit, &serverKexInit)
  188. if algs == nil {
  189. return errors.New("ssh: no common algorithms")
  190. }
  191. if clientKexInit.FirstKexFollows && algs.kex != clientKexInit.KexAlgos[0] {
  192. // The client sent a Kex message for the wrong algorithm,
  193. // which we have to ignore.
  194. if _, err = s.readPacket(); err != nil {
  195. return
  196. }
  197. }
  198. var hostKey Signer
  199. for _, k := range s.config.hostKeys {
  200. if algs.hostKey == k.PublicKey().PublicKeyAlgo() {
  201. hostKey = k
  202. }
  203. }
  204. kex, ok := kexAlgoMap[algs.kex]
  205. if !ok {
  206. return fmt.Errorf("ssh: unexpected key exchange algorithm %v", algs.kex)
  207. }
  208. magics := handshakeMagics{
  209. serverVersion: serverVersion[:len(serverVersion)-2],
  210. clientVersion: s.ClientVersion,
  211. serverKexInit: marshal(msgKexInit, serverKexInit),
  212. clientKexInit: clientKexInitPacket,
  213. }
  214. result, err := kex.Server(s, s.config.rand(), &magics, hostKey)
  215. if err != nil {
  216. return err
  217. }
  218. if err = s.transport.prepareKeyChange(algs, result); err != nil {
  219. return err
  220. }
  221. if err = s.writePacket([]byte{msgNewKeys}); err != nil {
  222. return
  223. }
  224. if packet, err := s.readPacket(); err != nil {
  225. return err
  226. } else if packet[0] != msgNewKeys {
  227. return UnexpectedMessageError{msgNewKeys, packet[0]}
  228. }
  229. return
  230. }
  231. func isAcceptableAlgo(algo string) bool {
  232. switch algo {
  233. case KeyAlgoRSA, KeyAlgoDSA, KeyAlgoECDSA256, KeyAlgoECDSA384, KeyAlgoECDSA521,
  234. CertAlgoRSAv01, CertAlgoDSAv01, CertAlgoECDSA256v01, CertAlgoECDSA384v01, CertAlgoECDSA521v01:
  235. return true
  236. }
  237. return false
  238. }
  239. // testPubKey returns true if the given public key is acceptable for the user.
  240. func (s *ServerConn) testPubKey(user, algo string, pubKey []byte) bool {
  241. if s.config.PublicKeyCallback == nil || !isAcceptableAlgo(algo) {
  242. return false
  243. }
  244. for _, c := range s.cachedPubKeys {
  245. if c.user == user && c.algo == algo && bytes.Equal(c.pubKey, pubKey) {
  246. return c.result
  247. }
  248. }
  249. result := s.config.PublicKeyCallback(s, user, algo, pubKey)
  250. if len(s.cachedPubKeys) < maxCachedPubKeys {
  251. c := cachedPubKey{
  252. user: user,
  253. algo: algo,
  254. pubKey: make([]byte, len(pubKey)),
  255. result: result,
  256. }
  257. copy(c.pubKey, pubKey)
  258. s.cachedPubKeys = append(s.cachedPubKeys, c)
  259. }
  260. return result
  261. }
  262. func (s *ServerConn) authenticate(H []byte) error {
  263. var userAuthReq userAuthRequestMsg
  264. var err error
  265. var packet []byte
  266. userAuthLoop:
  267. for {
  268. if packet, err = s.readPacket(); err != nil {
  269. return err
  270. }
  271. if err = unmarshal(&userAuthReq, packet, msgUserAuthRequest); err != nil {
  272. return err
  273. }
  274. if userAuthReq.Service != serviceSSH {
  275. return errors.New("ssh: client attempted to negotiate for unknown service: " + userAuthReq.Service)
  276. }
  277. switch userAuthReq.Method {
  278. case "none":
  279. if s.config.NoClientAuth {
  280. break userAuthLoop
  281. }
  282. case "password":
  283. if s.config.PasswordCallback == nil {
  284. break
  285. }
  286. payload := userAuthReq.Payload
  287. if len(payload) < 1 || payload[0] != 0 {
  288. return ParseError{msgUserAuthRequest}
  289. }
  290. payload = payload[1:]
  291. password, payload, ok := parseString(payload)
  292. if !ok || len(payload) > 0 {
  293. return ParseError{msgUserAuthRequest}
  294. }
  295. s.User = userAuthReq.User
  296. if s.config.PasswordCallback(s, userAuthReq.User, string(password)) {
  297. break userAuthLoop
  298. }
  299. case "keyboard-interactive":
  300. if s.config.KeyboardInteractiveCallback == nil {
  301. break
  302. }
  303. s.User = userAuthReq.User
  304. if s.config.KeyboardInteractiveCallback(s, s.User, &sshClientKeyboardInteractive{s}) {
  305. break userAuthLoop
  306. }
  307. case "publickey":
  308. if s.config.PublicKeyCallback == nil {
  309. break
  310. }
  311. payload := userAuthReq.Payload
  312. if len(payload) < 1 {
  313. return ParseError{msgUserAuthRequest}
  314. }
  315. isQuery := payload[0] == 0
  316. payload = payload[1:]
  317. algoBytes, payload, ok := parseString(payload)
  318. if !ok {
  319. return ParseError{msgUserAuthRequest}
  320. }
  321. algo := string(algoBytes)
  322. pubKey, payload, ok := parseString(payload)
  323. if !ok {
  324. return ParseError{msgUserAuthRequest}
  325. }
  326. if isQuery {
  327. // The client can query if the given public key
  328. // would be ok.
  329. if len(payload) > 0 {
  330. return ParseError{msgUserAuthRequest}
  331. }
  332. if s.testPubKey(userAuthReq.User, algo, pubKey) {
  333. okMsg := userAuthPubKeyOkMsg{
  334. Algo: algo,
  335. PubKey: string(pubKey),
  336. }
  337. if err = s.writePacket(marshal(msgUserAuthPubKeyOk, okMsg)); err != nil {
  338. return err
  339. }
  340. continue userAuthLoop
  341. }
  342. } else {
  343. sig, payload, ok := parseSignature(payload)
  344. if !ok || len(payload) > 0 {
  345. return ParseError{msgUserAuthRequest}
  346. }
  347. // Ensure the public key algo and signature algo
  348. // are supported. Compare the private key
  349. // algorithm name that corresponds to algo with
  350. // sig.Format. This is usually the same, but
  351. // for certs, the names differ.
  352. if !isAcceptableAlgo(algo) || !isAcceptableAlgo(sig.Format) || pubAlgoToPrivAlgo(algo) != sig.Format {
  353. break
  354. }
  355. signedData := buildDataSignedForAuth(H, userAuthReq, algoBytes, pubKey)
  356. key, _, ok := ParsePublicKey(pubKey)
  357. if !ok {
  358. return ParseError{msgUserAuthRequest}
  359. }
  360. if !key.Verify(signedData, sig.Blob) {
  361. return ParseError{msgUserAuthRequest}
  362. }
  363. // TODO(jmpittman): Implement full validation for certificates.
  364. s.User = userAuthReq.User
  365. if s.testPubKey(userAuthReq.User, algo, pubKey) {
  366. break userAuthLoop
  367. }
  368. }
  369. }
  370. var failureMsg userAuthFailureMsg
  371. if s.config.PasswordCallback != nil {
  372. failureMsg.Methods = append(failureMsg.Methods, "password")
  373. }
  374. if s.config.PublicKeyCallback != nil {
  375. failureMsg.Methods = append(failureMsg.Methods, "publickey")
  376. }
  377. if s.config.KeyboardInteractiveCallback != nil {
  378. failureMsg.Methods = append(failureMsg.Methods, "keyboard-interactive")
  379. }
  380. if len(failureMsg.Methods) == 0 {
  381. return errors.New("ssh: no authentication methods configured but NoClientAuth is also false")
  382. }
  383. if err = s.writePacket(marshal(msgUserAuthFailure, failureMsg)); err != nil {
  384. return err
  385. }
  386. }
  387. packet = []byte{msgUserAuthSuccess}
  388. if err = s.writePacket(packet); err != nil {
  389. return err
  390. }
  391. return nil
  392. }
  393. // sshClientKeyboardInteractive implements a ClientKeyboardInteractive by
  394. // asking the client on the other side of a ServerConn.
  395. type sshClientKeyboardInteractive struct {
  396. *ServerConn
  397. }
  398. func (c *sshClientKeyboardInteractive) Challenge(user, instruction string, questions []string, echos []bool) (answers []string, err error) {
  399. if len(questions) != len(echos) {
  400. return nil, errors.New("ssh: echos and questions must have equal length")
  401. }
  402. var prompts []byte
  403. for i := range questions {
  404. prompts = appendString(prompts, questions[i])
  405. prompts = appendBool(prompts, echos[i])
  406. }
  407. if err := c.writePacket(marshal(msgUserAuthInfoRequest, userAuthInfoRequestMsg{
  408. Instruction: instruction,
  409. NumPrompts: uint32(len(questions)),
  410. Prompts: prompts,
  411. })); err != nil {
  412. return nil, err
  413. }
  414. packet, err := c.readPacket()
  415. if err != nil {
  416. return nil, err
  417. }
  418. if packet[0] != msgUserAuthInfoResponse {
  419. return nil, UnexpectedMessageError{msgUserAuthInfoResponse, packet[0]}
  420. }
  421. packet = packet[1:]
  422. n, packet, ok := parseUint32(packet)
  423. if !ok || int(n) != len(questions) {
  424. return nil, &ParseError{msgUserAuthInfoResponse}
  425. }
  426. for i := uint32(0); i < n; i++ {
  427. ans, rest, ok := parseString(packet)
  428. if !ok {
  429. return nil, &ParseError{msgUserAuthInfoResponse}
  430. }
  431. answers = append(answers, string(ans))
  432. packet = rest
  433. }
  434. if len(packet) != 0 {
  435. return nil, errors.New("ssh: junk at end of message")
  436. }
  437. return answers, nil
  438. }
  439. const defaultWindowSize = 32768
  440. // Accept reads and processes messages on a ServerConn. It must be called
  441. // in order to demultiplex messages to any resulting Channels.
  442. func (s *ServerConn) Accept() (Channel, error) {
  443. // TODO(dfc) s.lock is not held here so visibility of s.err is not guaranteed.
  444. if s.err != nil {
  445. return nil, s.err
  446. }
  447. for {
  448. packet, err := s.readPacket()
  449. if err != nil {
  450. s.lock.Lock()
  451. s.err = err
  452. s.lock.Unlock()
  453. // TODO(dfc) s.lock protects s.channels but isn't being held here.
  454. for _, c := range s.channels {
  455. c.setDead()
  456. c.handleData(nil)
  457. }
  458. return nil, err
  459. }
  460. switch packet[0] {
  461. case msgChannelData:
  462. if len(packet) < 9 {
  463. // malformed data packet
  464. return nil, ParseError{msgChannelData}
  465. }
  466. remoteId := binary.BigEndian.Uint32(packet[1:5])
  467. s.lock.Lock()
  468. c, ok := s.channels[remoteId]
  469. if !ok {
  470. s.lock.Unlock()
  471. continue
  472. }
  473. if length := binary.BigEndian.Uint32(packet[5:9]); length > 0 {
  474. packet = packet[9:]
  475. c.handleData(packet[:length])
  476. }
  477. s.lock.Unlock()
  478. default:
  479. decoded, err := decode(packet)
  480. if err != nil {
  481. return nil, err
  482. }
  483. switch msg := decoded.(type) {
  484. case *channelOpenMsg:
  485. if msg.MaxPacketSize < minPacketLength || msg.MaxPacketSize > 1<<31 {
  486. return nil, errors.New("ssh: invalid MaxPacketSize from peer")
  487. }
  488. c := &serverChan{
  489. channel: channel{
  490. packetConn: s,
  491. remoteId: msg.PeersId,
  492. remoteWin: window{Cond: newCond()},
  493. maxPacket: msg.MaxPacketSize,
  494. },
  495. chanType: msg.ChanType,
  496. extraData: msg.TypeSpecificData,
  497. myWindow: defaultWindowSize,
  498. serverConn: s,
  499. cond: newCond(),
  500. pendingData: make([]byte, defaultWindowSize),
  501. }
  502. c.remoteWin.add(msg.PeersWindow)
  503. s.lock.Lock()
  504. c.localId = s.nextChanId
  505. s.nextChanId++
  506. s.channels[c.localId] = c
  507. s.lock.Unlock()
  508. return c, nil
  509. case *channelRequestMsg:
  510. s.lock.Lock()
  511. c, ok := s.channels[msg.PeersId]
  512. if !ok {
  513. s.lock.Unlock()
  514. continue
  515. }
  516. c.handlePacket(msg)
  517. s.lock.Unlock()
  518. case *windowAdjustMsg:
  519. s.lock.Lock()
  520. c, ok := s.channels[msg.PeersId]
  521. if !ok {
  522. s.lock.Unlock()
  523. continue
  524. }
  525. c.handlePacket(msg)
  526. s.lock.Unlock()
  527. case *channelEOFMsg:
  528. s.lock.Lock()
  529. c, ok := s.channels[msg.PeersId]
  530. if !ok {
  531. s.lock.Unlock()
  532. continue
  533. }
  534. c.handlePacket(msg)
  535. s.lock.Unlock()
  536. case *channelCloseMsg:
  537. s.lock.Lock()
  538. c, ok := s.channels[msg.PeersId]
  539. if !ok {
  540. s.lock.Unlock()
  541. continue
  542. }
  543. c.handlePacket(msg)
  544. s.lock.Unlock()
  545. case *globalRequestMsg:
  546. if msg.WantReply {
  547. if err := s.writePacket([]byte{msgRequestFailure}); err != nil {
  548. return nil, err
  549. }
  550. }
  551. case *kexInitMsg:
  552. s.lock.Lock()
  553. if err := s.clientInitHandshake(msg, packet); err != nil {
  554. s.lock.Unlock()
  555. return nil, err
  556. }
  557. s.lock.Unlock()
  558. case *disconnectMsg:
  559. return nil, io.EOF
  560. default:
  561. // Unknown message. Ignore.
  562. }
  563. }
  564. }
  565. panic("unreachable")
  566. }
  567. // A Listener implements a network listener (net.Listener) for SSH connections.
  568. type Listener struct {
  569. listener net.Listener
  570. config *ServerConfig
  571. }
  572. // Addr returns the listener's network address.
  573. func (l *Listener) Addr() net.Addr {
  574. return l.listener.Addr()
  575. }
  576. // Close closes the listener.
  577. func (l *Listener) Close() error {
  578. return l.listener.Close()
  579. }
  580. // Accept waits for and returns the next incoming SSH connection.
  581. // The receiver should call Handshake() in another goroutine
  582. // to avoid blocking the accepter.
  583. func (l *Listener) Accept() (*ServerConn, error) {
  584. c, err := l.listener.Accept()
  585. if err != nil {
  586. return nil, err
  587. }
  588. return Server(c, l.config), nil
  589. }
  590. // Listen creates an SSH listener accepting connections on
  591. // the given network address using net.Listen.
  592. func Listen(network, addr string, config *ServerConfig) (*Listener, error) {
  593. l, err := net.Listen(network, addr)
  594. if err != nil {
  595. return nil, err
  596. }
  597. return &Listener{
  598. l,
  599. config,
  600. }, nil
  601. }