server.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912
  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"
  8. "crypto/ecdsa"
  9. "crypto/elliptic"
  10. "crypto/rand"
  11. "crypto/rsa"
  12. "crypto/x509"
  13. "encoding/binary"
  14. "encoding/pem"
  15. "errors"
  16. "io"
  17. "math/big"
  18. "net"
  19. "sync"
  20. _ "crypto/sha256"
  21. _ "crypto/sha512"
  22. )
  23. type ServerConfig struct {
  24. rsa *rsa.PrivateKey
  25. rsaSerialized []byte
  26. // Rand provides the source of entropy for key exchange. If Rand is
  27. // nil, the cryptographic random reader in package crypto/rand will
  28. // be used.
  29. Rand io.Reader
  30. // NoClientAuth is true if clients are allowed to connect without
  31. // authenticating.
  32. NoClientAuth bool
  33. // PasswordCallback, if non-nil, is called when a user attempts to
  34. // authenticate using a password. It may be called concurrently from
  35. // several goroutines.
  36. PasswordCallback func(conn *ServerConn, user, password string) bool
  37. // PublicKeyCallback, if non-nil, is called when a client attempts public
  38. // key authentication. It must return true iff the given public key is
  39. // valid for the given user.
  40. PublicKeyCallback func(conn *ServerConn, user, algo string, pubkey []byte) bool
  41. // KeyboardInteractiveCallback, if non-nil, is called when
  42. // keyboard-interactive authentication is selected (RFC
  43. // 4256). The client object's Challenge function should be
  44. // used to query the user. The callback may offer multiple
  45. // Challenge rounds. To avoid information leaks, the client
  46. // should be presented a challenge even if the user is
  47. // unknown.
  48. KeyboardInteractiveCallback func(conn *ServerConn, user string, client ClientKeyboardInteractive) bool
  49. // Cryptographic-related configuration.
  50. Crypto CryptoConfig
  51. }
  52. func (c *ServerConfig) rand() io.Reader {
  53. if c.Rand == nil {
  54. return rand.Reader
  55. }
  56. return c.Rand
  57. }
  58. // SetRSAPrivateKey sets the private key for a Server. A Server must have a
  59. // private key configured in order to accept connections. The private key must
  60. // be in the form of a PEM encoded, PKCS#1, RSA private key. The file "id_rsa"
  61. // typically contains such a key.
  62. func (s *ServerConfig) SetRSAPrivateKey(pemBytes []byte) error {
  63. block, _ := pem.Decode(pemBytes)
  64. if block == nil {
  65. return errors.New("ssh: no key found")
  66. }
  67. var err error
  68. s.rsa, err = x509.ParsePKCS1PrivateKey(block.Bytes)
  69. if err != nil {
  70. return err
  71. }
  72. s.rsaSerialized = serializePublicKey(&s.rsa.PublicKey)
  73. return nil
  74. }
  75. func parseRSASig(in []byte) (sig []byte, ok bool) {
  76. algo, in, ok := parseString(in)
  77. if !ok || string(algo) != hostAlgoRSA {
  78. return nil, false
  79. }
  80. sig, in, ok = parseString(in)
  81. if len(in) > 0 {
  82. ok = false
  83. }
  84. return
  85. }
  86. // cachedPubKey contains the results of querying whether a public key is
  87. // acceptable for a user. The cache only applies to a single ServerConn.
  88. type cachedPubKey struct {
  89. user, algo string
  90. pubKey []byte
  91. result bool
  92. }
  93. const maxCachedPubKeys = 16
  94. // A ServerConn represents an incoming connection.
  95. type ServerConn struct {
  96. *transport
  97. config *ServerConfig
  98. channels map[uint32]*serverChan
  99. nextChanId uint32
  100. // lock protects err and channels.
  101. lock sync.Mutex
  102. err error
  103. // cachedPubKeys contains the cache results of tests for public keys.
  104. // Since SSH clients will query whether a public key is acceptable
  105. // before attempting to authenticate with it, we end up with duplicate
  106. // queries for public key validity.
  107. cachedPubKeys []cachedPubKey
  108. // User holds the successfully authenticated user name.
  109. // It is empty if no authentication is used. It is populated before
  110. // any authentication callback is called and not assigned to after that.
  111. User string
  112. // ClientVersion is the client's version, populated after
  113. // Handshake is called. It should not be modified.
  114. ClientVersion []byte
  115. // Initial H used for the session ID. Once assigned this must not change
  116. // even during subsequent key exchanges.
  117. sessionId []byte
  118. }
  119. // Server returns a new SSH server connection
  120. // using c as the underlying transport.
  121. func Server(c net.Conn, config *ServerConfig) *ServerConn {
  122. return &ServerConn{
  123. transport: newTransport(c, config.rand()),
  124. channels: make(map[uint32]*serverChan),
  125. config: config,
  126. }
  127. }
  128. // kexECDH performs Elliptic Curve Diffie-Hellman key agreement on a
  129. // ServerConnection, as documented in RFC 5656, section 4.
  130. func (s *ServerConn) kexECDH(curve elliptic.Curve, magics *handshakeMagics, hostKeyAlgo string) (result *kexResult, err error) {
  131. packet, err := s.readPacket()
  132. if err != nil {
  133. return
  134. }
  135. var kexECDHInit kexECDHInitMsg
  136. if err = unmarshal(&kexECDHInit, packet, msgKexECDHInit); err != nil {
  137. return
  138. }
  139. clientX, clientY := elliptic.Unmarshal(curve, kexECDHInit.ClientPubKey)
  140. if clientX == nil {
  141. return nil, errors.New("ssh: elliptic.Unmarshal failure")
  142. }
  143. if !validateECPublicKey(curve, clientX, clientY) {
  144. return nil, errors.New("ssh: not a valid EC public key")
  145. }
  146. // We could cache this key across multiple users/multiple
  147. // connection attempts, but the benefit is small. OpenSSH
  148. // generates a new key for each incoming connection.
  149. ephKey, err := ecdsa.GenerateKey(curve, s.config.rand())
  150. if err != nil {
  151. return nil, err
  152. }
  153. hostKey, err := s.serializedHostKey(hostKeyAlgo)
  154. if err != nil {
  155. return nil, err
  156. }
  157. serializedEphKey := elliptic.Marshal(curve, ephKey.PublicKey.X, ephKey.PublicKey.Y)
  158. // generate shared secret
  159. secret, _ := curve.ScalarMult(clientX, clientY, ephKey.D.Bytes())
  160. hashFunc := ecHash(curve)
  161. h := hashFunc.New()
  162. writeString(h, magics.clientVersion)
  163. writeString(h, magics.serverVersion)
  164. writeString(h, magics.clientKexInit)
  165. writeString(h, magics.serverKexInit)
  166. writeString(h, hostKey)
  167. writeString(h, kexECDHInit.ClientPubKey)
  168. writeString(h, serializedEphKey)
  169. K := make([]byte, intLength(secret))
  170. marshalInt(K, secret)
  171. h.Write(K)
  172. H := h.Sum(nil)
  173. serializedSig, err := s.serializedHostKeySignature(hostKeyAlgo, H)
  174. if err != nil {
  175. return nil, err
  176. }
  177. reply := kexECDHReplyMsg{
  178. EphemeralPubKey: serializedEphKey,
  179. HostKey: hostKey,
  180. Signature: serializedSig,
  181. }
  182. serialized := marshal(msgKexECDHReply, reply)
  183. if err := s.writePacket(serialized); err != nil {
  184. return nil, err
  185. }
  186. return &kexResult{
  187. H: H,
  188. K: K,
  189. HostKey: reply.HostKey,
  190. Hash: hashFunc,
  191. }, nil
  192. }
  193. func (s *ServerConn) serializedHostKey(hostKeyAlgo string) ([]byte, error) {
  194. switch hostKeyAlgo {
  195. case hostAlgoRSA:
  196. return s.config.rsaSerialized, nil
  197. }
  198. return nil, errors.New("ssh: internal error")
  199. }
  200. // validateECPublicKey checks that the point is a valid public key for
  201. // the given curve. See [SEC1], 3.2.2
  202. func validateECPublicKey(curve elliptic.Curve, x, y *big.Int) bool {
  203. if x.Sign() == 0 && y.Sign() == 0 {
  204. return false
  205. }
  206. if x.Cmp(curve.Params().P) >= 0 {
  207. return false
  208. }
  209. if y.Cmp(curve.Params().P) >= 0 {
  210. return false
  211. }
  212. if !curve.IsOnCurve(x, y) {
  213. return false
  214. }
  215. // We don't check if N * PubKey == 0, since
  216. //
  217. // - the NIST curves have cofactor = 1, so this is implicit.
  218. // (We don't forsee an implementation that supports non NIST
  219. // curves)
  220. //
  221. // - for ephemeral keys, we don't need to worry about small
  222. // subgroup attacks.
  223. return true
  224. }
  225. // kexDH performs Diffie-Hellman key agreement on a ServerConnection.
  226. func (s *ServerConn) kexDH(group *dhGroup, hashFunc crypto.Hash, magics *handshakeMagics, hostKeyAlgo string) (result *kexResult, err error) {
  227. packet, err := s.readPacket()
  228. if err != nil {
  229. return
  230. }
  231. var kexDHInit kexDHInitMsg
  232. if err = unmarshal(&kexDHInit, packet, msgKexDHInit); err != nil {
  233. return
  234. }
  235. y, err := rand.Int(s.config.rand(), group.p)
  236. if err != nil {
  237. return
  238. }
  239. Y := new(big.Int).Exp(group.g, y, group.p)
  240. kInt, err := group.diffieHellman(kexDHInit.X, y)
  241. if err != nil {
  242. return nil, err
  243. }
  244. hostKey, err := s.serializedHostKey(hostKeyAlgo)
  245. if err != nil {
  246. return nil, err
  247. }
  248. h := hashFunc.New()
  249. writeString(h, magics.clientVersion)
  250. writeString(h, magics.serverVersion)
  251. writeString(h, magics.clientKexInit)
  252. writeString(h, magics.serverKexInit)
  253. writeString(h, hostKey)
  254. writeInt(h, kexDHInit.X)
  255. writeInt(h, Y)
  256. K := make([]byte, intLength(kInt))
  257. marshalInt(K, kInt)
  258. h.Write(K)
  259. H := h.Sum(nil)
  260. serializedSig, err := s.serializedHostKeySignature(hostKeyAlgo, H)
  261. if err != nil {
  262. return nil, err
  263. }
  264. kexDHReply := kexDHReplyMsg{
  265. HostKey: hostKey,
  266. Y: Y,
  267. Signature: serializedSig,
  268. }
  269. packet = marshal(msgKexDHReply, kexDHReply)
  270. err = s.writePacket(packet)
  271. return &kexResult{
  272. H: H,
  273. K: K,
  274. HostKey: hostKey,
  275. Hash: hashFunc,
  276. }, nil
  277. }
  278. // serializedHostKeySignature signs the hashed data, and serializes
  279. // the signature according to SSH conventions.
  280. func (s *ServerConn) serializedHostKeySignature(hostKeyAlgo string, hashed []byte) ([]byte, error) {
  281. var sig []byte
  282. switch hostKeyAlgo {
  283. case hostAlgoRSA:
  284. hashFunc := crypto.SHA1
  285. hh := hashFunc.New()
  286. hh.Write(hashed)
  287. var err error
  288. sig, err = rsa.SignPKCS1v15(s.config.rand(), s.config.rsa, hashFunc, hh.Sum(nil))
  289. if err != nil {
  290. return nil, err
  291. }
  292. default:
  293. return nil, errors.New("ssh: internal error")
  294. }
  295. return serializeSignature(hostKeyAlgo, sig), nil
  296. }
  297. // serverVersion is the fixed identification string that Server will use.
  298. var serverVersion = []byte("SSH-2.0-Go\r\n")
  299. // Handshake performs an SSH transport and client authentication on the given ServerConn.
  300. func (s *ServerConn) Handshake() (err error) {
  301. if _, err = s.Write(serverVersion); err != nil {
  302. return
  303. }
  304. if err = s.Flush(); err != nil {
  305. return
  306. }
  307. s.ClientVersion, err = readVersion(s)
  308. if err != nil {
  309. return
  310. }
  311. if err = s.clientInitHandshake(nil, nil); err != nil {
  312. return
  313. }
  314. var packet []byte
  315. if packet, err = s.readPacket(); err != nil {
  316. return
  317. }
  318. var serviceRequest serviceRequestMsg
  319. if err = unmarshal(&serviceRequest, packet, msgServiceRequest); err != nil {
  320. return
  321. }
  322. if serviceRequest.Service != serviceUserAuth {
  323. return errors.New("ssh: requested service '" + serviceRequest.Service + "' before authenticating")
  324. }
  325. serviceAccept := serviceAcceptMsg{
  326. Service: serviceUserAuth,
  327. }
  328. if err = s.writePacket(marshal(msgServiceAccept, serviceAccept)); err != nil {
  329. return
  330. }
  331. if err = s.authenticate(s.sessionId); err != nil {
  332. return
  333. }
  334. return
  335. }
  336. func (s *ServerConn) clientInitHandshake(clientKexInit *kexInitMsg, clientKexInitPacket []byte) (err error) {
  337. serverKexInit := kexInitMsg{
  338. KexAlgos: s.config.Crypto.kexes(),
  339. ServerHostKeyAlgos: supportedHostKeyAlgos,
  340. CiphersClientServer: s.config.Crypto.ciphers(),
  341. CiphersServerClient: s.config.Crypto.ciphers(),
  342. MACsClientServer: s.config.Crypto.macs(),
  343. MACsServerClient: s.config.Crypto.macs(),
  344. CompressionClientServer: supportedCompressions,
  345. CompressionServerClient: supportedCompressions,
  346. }
  347. serverKexInitPacket := marshal(msgKexInit, serverKexInit)
  348. if err = s.writePacket(serverKexInitPacket); err != nil {
  349. return
  350. }
  351. if clientKexInitPacket == nil {
  352. clientKexInit = new(kexInitMsg)
  353. if clientKexInitPacket, err = s.readPacket(); err != nil {
  354. return
  355. }
  356. if err = unmarshal(clientKexInit, clientKexInitPacket, msgKexInit); err != nil {
  357. return
  358. }
  359. }
  360. kexAlgo, hostKeyAlgo, ok := findAgreedAlgorithms(s.transport, clientKexInit, &serverKexInit)
  361. if !ok {
  362. return errors.New("ssh: no common algorithms")
  363. }
  364. if clientKexInit.FirstKexFollows && kexAlgo != clientKexInit.KexAlgos[0] {
  365. // The client sent a Kex message for the wrong algorithm,
  366. // which we have to ignore.
  367. if _, err = s.readPacket(); err != nil {
  368. return
  369. }
  370. }
  371. var magics handshakeMagics
  372. magics.serverVersion = serverVersion[:len(serverVersion)-2]
  373. magics.clientVersion = s.ClientVersion
  374. magics.serverKexInit = marshal(msgKexInit, serverKexInit)
  375. magics.clientKexInit = clientKexInitPacket
  376. var result *kexResult
  377. switch kexAlgo {
  378. case kexAlgoECDH256:
  379. result, err = s.kexECDH(elliptic.P256(), &magics, hostKeyAlgo)
  380. case kexAlgoECDH384:
  381. result, err = s.kexECDH(elliptic.P384(), &magics, hostKeyAlgo)
  382. case kexAlgoECDH521:
  383. result, err = s.kexECDH(elliptic.P521(), &magics, hostKeyAlgo)
  384. case kexAlgoDH14SHA1:
  385. dhGroup14Once.Do(initDHGroup14)
  386. result, err = s.kexDH(dhGroup14, crypto.SHA1, &magics, hostKeyAlgo)
  387. case kexAlgoDH1SHA1:
  388. dhGroup1Once.Do(initDHGroup1)
  389. result, err = s.kexDH(dhGroup1, crypto.SHA1, &magics, hostKeyAlgo)
  390. default:
  391. err = errors.New("ssh: unexpected key exchange algorithm " + kexAlgo)
  392. }
  393. if err != nil {
  394. return
  395. }
  396. // sessionId must only be assigned during initial handshake.
  397. if s.sessionId == nil {
  398. s.sessionId = result.H
  399. }
  400. var packet []byte
  401. if err = s.writePacket([]byte{msgNewKeys}); err != nil {
  402. return
  403. }
  404. if err = s.transport.writer.setupKeys(serverKeys, result.K, result.H, s.sessionId, result.Hash); err != nil {
  405. return
  406. }
  407. if packet, err = s.readPacket(); err != nil {
  408. return
  409. }
  410. if packet[0] != msgNewKeys {
  411. return UnexpectedMessageError{msgNewKeys, packet[0]}
  412. }
  413. if err = s.transport.reader.setupKeys(clientKeys, result.K, result.H, s.sessionId, result.Hash); err != nil {
  414. return
  415. }
  416. return
  417. }
  418. func isAcceptableAlgo(algo string) bool {
  419. return algo == hostAlgoRSA
  420. }
  421. // testPubKey returns true if the given public key is acceptable for the user.
  422. func (s *ServerConn) testPubKey(user, algo string, pubKey []byte) bool {
  423. if s.config.PublicKeyCallback == nil || !isAcceptableAlgo(algo) {
  424. return false
  425. }
  426. for _, c := range s.cachedPubKeys {
  427. if c.user == user && c.algo == algo && bytes.Equal(c.pubKey, pubKey) {
  428. return c.result
  429. }
  430. }
  431. result := s.config.PublicKeyCallback(s, user, algo, pubKey)
  432. if len(s.cachedPubKeys) < maxCachedPubKeys {
  433. c := cachedPubKey{
  434. user: user,
  435. algo: algo,
  436. pubKey: make([]byte, len(pubKey)),
  437. result: result,
  438. }
  439. copy(c.pubKey, pubKey)
  440. s.cachedPubKeys = append(s.cachedPubKeys, c)
  441. }
  442. return result
  443. }
  444. func (s *ServerConn) authenticate(H []byte) error {
  445. var userAuthReq userAuthRequestMsg
  446. var err error
  447. var packet []byte
  448. userAuthLoop:
  449. for {
  450. if packet, err = s.readPacket(); err != nil {
  451. return err
  452. }
  453. if err = unmarshal(&userAuthReq, packet, msgUserAuthRequest); err != nil {
  454. return err
  455. }
  456. if userAuthReq.Service != serviceSSH {
  457. return errors.New("ssh: client attempted to negotiate for unknown service: " + userAuthReq.Service)
  458. }
  459. switch userAuthReq.Method {
  460. case "none":
  461. if s.config.NoClientAuth {
  462. break userAuthLoop
  463. }
  464. case "password":
  465. if s.config.PasswordCallback == nil {
  466. break
  467. }
  468. payload := userAuthReq.Payload
  469. if len(payload) < 1 || payload[0] != 0 {
  470. return ParseError{msgUserAuthRequest}
  471. }
  472. payload = payload[1:]
  473. password, payload, ok := parseString(payload)
  474. if !ok || len(payload) > 0 {
  475. return ParseError{msgUserAuthRequest}
  476. }
  477. s.User = userAuthReq.User
  478. if s.config.PasswordCallback(s, userAuthReq.User, string(password)) {
  479. break userAuthLoop
  480. }
  481. case "keyboard-interactive":
  482. if s.config.KeyboardInteractiveCallback == nil {
  483. break
  484. }
  485. s.User = userAuthReq.User
  486. if s.config.KeyboardInteractiveCallback(s, s.User, &sshClientKeyboardInteractive{s}) {
  487. break userAuthLoop
  488. }
  489. case "publickey":
  490. if s.config.PublicKeyCallback == nil {
  491. break
  492. }
  493. payload := userAuthReq.Payload
  494. if len(payload) < 1 {
  495. return ParseError{msgUserAuthRequest}
  496. }
  497. isQuery := payload[0] == 0
  498. payload = payload[1:]
  499. algoBytes, payload, ok := parseString(payload)
  500. if !ok {
  501. return ParseError{msgUserAuthRequest}
  502. }
  503. algo := string(algoBytes)
  504. pubKey, payload, ok := parseString(payload)
  505. if !ok {
  506. return ParseError{msgUserAuthRequest}
  507. }
  508. if isQuery {
  509. // The client can query if the given public key
  510. // would be ok.
  511. if len(payload) > 0 {
  512. return ParseError{msgUserAuthRequest}
  513. }
  514. if s.testPubKey(userAuthReq.User, algo, pubKey) {
  515. okMsg := userAuthPubKeyOkMsg{
  516. Algo: algo,
  517. PubKey: string(pubKey),
  518. }
  519. if err = s.writePacket(marshal(msgUserAuthPubKeyOk, okMsg)); err != nil {
  520. return err
  521. }
  522. continue userAuthLoop
  523. }
  524. } else {
  525. sig, payload, ok := parseString(payload)
  526. if !ok || len(payload) > 0 {
  527. return ParseError{msgUserAuthRequest}
  528. }
  529. if !isAcceptableAlgo(algo) {
  530. break
  531. }
  532. rsaSig, ok := parseRSASig(sig)
  533. if !ok {
  534. return ParseError{msgUserAuthRequest}
  535. }
  536. signedData := buildDataSignedForAuth(H, userAuthReq, algoBytes, pubKey)
  537. switch algo {
  538. case hostAlgoRSA:
  539. hashFunc := crypto.SHA1
  540. h := hashFunc.New()
  541. h.Write(signedData)
  542. digest := h.Sum(nil)
  543. key, _, ok := parsePubKey(pubKey)
  544. if !ok {
  545. return ParseError{msgUserAuthRequest}
  546. }
  547. rsaKey, ok := key.(*rsa.PublicKey)
  548. if !ok {
  549. return ParseError{msgUserAuthRequest}
  550. }
  551. if rsa.VerifyPKCS1v15(rsaKey, hashFunc, digest, rsaSig) != nil {
  552. return ParseError{msgUserAuthRequest}
  553. }
  554. default:
  555. return errors.New("ssh: isAcceptableAlgo incorrect")
  556. }
  557. s.User = userAuthReq.User
  558. if s.testPubKey(userAuthReq.User, algo, pubKey) {
  559. break userAuthLoop
  560. }
  561. }
  562. }
  563. var failureMsg userAuthFailureMsg
  564. if s.config.PasswordCallback != nil {
  565. failureMsg.Methods = append(failureMsg.Methods, "password")
  566. }
  567. if s.config.PublicKeyCallback != nil {
  568. failureMsg.Methods = append(failureMsg.Methods, "publickey")
  569. }
  570. if s.config.KeyboardInteractiveCallback != nil {
  571. failureMsg.Methods = append(failureMsg.Methods, "keyboard-interactive")
  572. }
  573. if len(failureMsg.Methods) == 0 {
  574. return errors.New("ssh: no authentication methods configured but NoClientAuth is also false")
  575. }
  576. if err = s.writePacket(marshal(msgUserAuthFailure, failureMsg)); err != nil {
  577. return err
  578. }
  579. }
  580. packet = []byte{msgUserAuthSuccess}
  581. if err = s.writePacket(packet); err != nil {
  582. return err
  583. }
  584. return nil
  585. }
  586. // sshClientKeyboardInteractive implements a ClientKeyboardInteractive by
  587. // asking the client on the other side of a ServerConn.
  588. type sshClientKeyboardInteractive struct {
  589. *ServerConn
  590. }
  591. func (c *sshClientKeyboardInteractive) Challenge(user, instruction string, questions []string, echos []bool) (answers []string, err error) {
  592. if len(questions) != len(echos) {
  593. return nil, errors.New("ssh: echos and questions must have equal length")
  594. }
  595. var prompts []byte
  596. for i := range questions {
  597. prompts = appendString(prompts, questions[i])
  598. prompts = appendBool(prompts, echos[i])
  599. }
  600. if err := c.writePacket(marshal(msgUserAuthInfoRequest, userAuthInfoRequestMsg{
  601. Instruction: instruction,
  602. NumPrompts: uint32(len(questions)),
  603. Prompts: prompts,
  604. })); err != nil {
  605. return nil, err
  606. }
  607. packet, err := c.readPacket()
  608. if err != nil {
  609. return nil, err
  610. }
  611. if packet[0] != msgUserAuthInfoResponse {
  612. return nil, UnexpectedMessageError{msgUserAuthInfoResponse, packet[0]}
  613. }
  614. packet = packet[1:]
  615. n, packet, ok := parseUint32(packet)
  616. if !ok || int(n) != len(questions) {
  617. return nil, &ParseError{msgUserAuthInfoResponse}
  618. }
  619. for i := uint32(0); i < n; i++ {
  620. ans, rest, ok := parseString(packet)
  621. if !ok {
  622. return nil, &ParseError{msgUserAuthInfoResponse}
  623. }
  624. answers = append(answers, string(ans))
  625. packet = rest
  626. }
  627. if len(packet) != 0 {
  628. return nil, errors.New("ssh: junk at end of message")
  629. }
  630. return answers, nil
  631. }
  632. const defaultWindowSize = 32768
  633. // Accept reads and processes messages on a ServerConn. It must be called
  634. // in order to demultiplex messages to any resulting Channels.
  635. func (s *ServerConn) Accept() (Channel, error) {
  636. // TODO(dfc) s.lock is not held here so visibility of s.err is not guaranteed.
  637. if s.err != nil {
  638. return nil, s.err
  639. }
  640. for {
  641. packet, err := s.readPacket()
  642. if err != nil {
  643. s.lock.Lock()
  644. s.err = err
  645. s.lock.Unlock()
  646. // TODO(dfc) s.lock protects s.channels but isn't being held here.
  647. for _, c := range s.channels {
  648. c.setDead()
  649. c.handleData(nil)
  650. }
  651. return nil, err
  652. }
  653. switch packet[0] {
  654. case msgChannelData:
  655. if len(packet) < 9 {
  656. // malformed data packet
  657. return nil, ParseError{msgChannelData}
  658. }
  659. remoteId := binary.BigEndian.Uint32(packet[1:5])
  660. s.lock.Lock()
  661. c, ok := s.channels[remoteId]
  662. if !ok {
  663. s.lock.Unlock()
  664. continue
  665. }
  666. if length := binary.BigEndian.Uint32(packet[5:9]); length > 0 {
  667. packet = packet[9:]
  668. c.handleData(packet[:length])
  669. }
  670. s.lock.Unlock()
  671. default:
  672. decoded, err := decode(packet)
  673. if err != nil {
  674. return nil, err
  675. }
  676. switch msg := decoded.(type) {
  677. case *channelOpenMsg:
  678. if msg.MaxPacketSize < minPacketLength || msg.MaxPacketSize > 1<<31 {
  679. return nil, errors.New("ssh: invalid MaxPacketSize from peer")
  680. }
  681. c := &serverChan{
  682. channel: channel{
  683. conn: s,
  684. remoteId: msg.PeersId,
  685. remoteWin: window{Cond: newCond()},
  686. maxPacket: msg.MaxPacketSize,
  687. },
  688. chanType: msg.ChanType,
  689. extraData: msg.TypeSpecificData,
  690. myWindow: defaultWindowSize,
  691. serverConn: s,
  692. cond: newCond(),
  693. pendingData: make([]byte, defaultWindowSize),
  694. }
  695. c.remoteWin.add(msg.PeersWindow)
  696. s.lock.Lock()
  697. c.localId = s.nextChanId
  698. s.nextChanId++
  699. s.channels[c.localId] = c
  700. s.lock.Unlock()
  701. return c, nil
  702. case *channelRequestMsg:
  703. s.lock.Lock()
  704. c, ok := s.channels[msg.PeersId]
  705. if !ok {
  706. s.lock.Unlock()
  707. continue
  708. }
  709. c.handlePacket(msg)
  710. s.lock.Unlock()
  711. case *windowAdjustMsg:
  712. s.lock.Lock()
  713. c, ok := s.channels[msg.PeersId]
  714. if !ok {
  715. s.lock.Unlock()
  716. continue
  717. }
  718. c.handlePacket(msg)
  719. s.lock.Unlock()
  720. case *channelEOFMsg:
  721. s.lock.Lock()
  722. c, ok := s.channels[msg.PeersId]
  723. if !ok {
  724. s.lock.Unlock()
  725. continue
  726. }
  727. c.handlePacket(msg)
  728. s.lock.Unlock()
  729. case *channelCloseMsg:
  730. s.lock.Lock()
  731. c, ok := s.channels[msg.PeersId]
  732. if !ok {
  733. s.lock.Unlock()
  734. continue
  735. }
  736. c.handlePacket(msg)
  737. s.lock.Unlock()
  738. case *globalRequestMsg:
  739. if msg.WantReply {
  740. if err := s.writePacket([]byte{msgRequestFailure}); err != nil {
  741. return nil, err
  742. }
  743. }
  744. case *kexInitMsg:
  745. s.lock.Lock()
  746. if err := s.clientInitHandshake(msg, packet); err != nil {
  747. s.lock.Unlock()
  748. return nil, err
  749. }
  750. s.lock.Unlock()
  751. case *disconnectMsg:
  752. return nil, io.EOF
  753. default:
  754. // Unknown message. Ignore.
  755. }
  756. }
  757. }
  758. panic("unreachable")
  759. }
  760. // A Listener implements a network listener (net.Listener) for SSH connections.
  761. type Listener struct {
  762. listener net.Listener
  763. config *ServerConfig
  764. }
  765. // Addr returns the listener's network address.
  766. func (l *Listener) Addr() net.Addr {
  767. return l.listener.Addr()
  768. }
  769. // Close closes the listener.
  770. func (l *Listener) Close() error {
  771. return l.listener.Close()
  772. }
  773. // Accept waits for and returns the next incoming SSH connection.
  774. // The receiver should call Handshake() in another goroutine
  775. // to avoid blocking the accepter.
  776. func (l *Listener) Accept() (*ServerConn, error) {
  777. c, err := l.listener.Accept()
  778. if err != nil {
  779. return nil, err
  780. }
  781. return Server(c, l.config), nil
  782. }
  783. // Listen creates an SSH listener accepting connections on
  784. // the given network address using net.Listen.
  785. func Listen(network, addr string, config *ServerConfig) (*Listener, error) {
  786. l, err := net.Listen(network, addr)
  787. if err != nil {
  788. return nil, err
  789. }
  790. return &Listener{
  791. l,
  792. config,
  793. }, nil
  794. }