server.go 23 KB

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