You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

510 lines
14 KiB

  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. "errors"
  8. "fmt"
  9. "io"
  10. )
  11. // clientAuthenticate authenticates with the remote server. See RFC 4252.
  12. func (c *connection) clientAuthenticate(config *ClientConfig) error {
  13. // initiate user auth session
  14. if err := c.transport.writePacket(Marshal(&serviceRequestMsg{serviceUserAuth})); err != nil {
  15. return err
  16. }
  17. packet, err := c.transport.readPacket()
  18. if err != nil {
  19. return err
  20. }
  21. var serviceAccept serviceAcceptMsg
  22. if err := Unmarshal(packet, &serviceAccept); err != nil {
  23. return err
  24. }
  25. // during the authentication phase the client first attempts the "none" method
  26. // then any untried methods suggested by the server.
  27. tried := make(map[string]bool)
  28. var lastMethods []string
  29. sessionID := c.transport.getSessionID()
  30. for auth := AuthMethod(new(noneAuth)); auth != nil; {
  31. ok, methods, err := auth.auth(sessionID, config.User, c.transport, config.Rand)
  32. if err != nil {
  33. return err
  34. }
  35. if ok {
  36. // success
  37. return nil
  38. }
  39. tried[auth.method()] = true
  40. if methods == nil {
  41. methods = lastMethods
  42. }
  43. lastMethods = methods
  44. auth = nil
  45. findNext:
  46. for _, a := range config.Auth {
  47. candidateMethod := a.method()
  48. if tried[candidateMethod] {
  49. continue
  50. }
  51. for _, meth := range methods {
  52. if meth == candidateMethod {
  53. auth = a
  54. break findNext
  55. }
  56. }
  57. }
  58. }
  59. return fmt.Errorf("ssh: unable to authenticate, attempted methods %v, no supported methods remain", keys(tried))
  60. }
  61. func keys(m map[string]bool) []string {
  62. s := make([]string, 0, len(m))
  63. for key := range m {
  64. s = append(s, key)
  65. }
  66. return s
  67. }
  68. // An AuthMethod represents an instance of an RFC 4252 authentication method.
  69. type AuthMethod interface {
  70. // auth authenticates user over transport t.
  71. // Returns true if authentication is successful.
  72. // If authentication is not successful, a []string of alternative
  73. // method names is returned. If the slice is nil, it will be ignored
  74. // and the previous set of possible methods will be reused.
  75. auth(session []byte, user string, p packetConn, rand io.Reader) (bool, []string, error)
  76. // method returns the RFC 4252 method name.
  77. method() string
  78. }
  79. // "none" authentication, RFC 4252 section 5.2.
  80. type noneAuth int
  81. func (n *noneAuth) auth(session []byte, user string, c packetConn, rand io.Reader) (bool, []string, error) {
  82. if err := c.writePacket(Marshal(&userAuthRequestMsg{
  83. User: user,
  84. Service: serviceSSH,
  85. Method: "none",
  86. })); err != nil {
  87. return false, nil, err
  88. }
  89. return handleAuthResponse(c)
  90. }
  91. func (n *noneAuth) method() string {
  92. return "none"
  93. }
  94. // passwordCallback is an AuthMethod that fetches the password through
  95. // a function call, e.g. by prompting the user.
  96. type passwordCallback func() (password string, err error)
  97. func (cb passwordCallback) auth(session []byte, user string, c packetConn, rand io.Reader) (bool, []string, error) {
  98. type passwordAuthMsg struct {
  99. User string `sshtype:"50"`
  100. Service string
  101. Method string
  102. Reply bool
  103. Password string
  104. }
  105. pw, err := cb()
  106. // REVIEW NOTE: is there a need to support skipping a password attempt?
  107. // The program may only find out that the user doesn't have a password
  108. // when prompting.
  109. if err != nil {
  110. return false, nil, err
  111. }
  112. if err := c.writePacket(Marshal(&passwordAuthMsg{
  113. User: user,
  114. Service: serviceSSH,
  115. Method: cb.method(),
  116. Reply: false,
  117. Password: pw,
  118. })); err != nil {
  119. return false, nil, err
  120. }
  121. return handleAuthResponse(c)
  122. }
  123. func (cb passwordCallback) method() string {
  124. return "password"
  125. }
  126. // Password returns an AuthMethod using the given password.
  127. func Password(secret string) AuthMethod {
  128. return passwordCallback(func() (string, error) { return secret, nil })
  129. }
  130. // PasswordCallback returns an AuthMethod that uses a callback for
  131. // fetching a password.
  132. func PasswordCallback(prompt func() (secret string, err error)) AuthMethod {
  133. return passwordCallback(prompt)
  134. }
  135. type publickeyAuthMsg struct {
  136. User string `sshtype:"50"`
  137. Service string
  138. Method string
  139. // HasSig indicates to the receiver packet that the auth request is signed and
  140. // should be used for authentication of the request.
  141. HasSig bool
  142. Algoname string
  143. PubKey []byte
  144. // Sig is tagged with "rest" so Marshal will exclude it during
  145. // validateKey
  146. Sig []byte `ssh:"rest"`
  147. }
  148. // publicKeyCallback is an AuthMethod that uses a set of key
  149. // pairs for authentication.
  150. type publicKeyCallback func() ([]Signer, error)
  151. func (cb publicKeyCallback) method() string {
  152. return "publickey"
  153. }
  154. func (cb publicKeyCallback) auth(session []byte, user string, c packetConn, rand io.Reader) (bool, []string, error) {
  155. // Authentication is performed by sending an enquiry to test if a key is
  156. // acceptable to the remote. If the key is acceptable, the client will
  157. // attempt to authenticate with the valid key. If not the client will repeat
  158. // the process with the remaining keys.
  159. signers, err := cb()
  160. if err != nil {
  161. return false, nil, err
  162. }
  163. var methods []string
  164. for _, signer := range signers {
  165. ok, err := validateKey(signer.PublicKey(), user, c)
  166. if err != nil {
  167. return false, nil, err
  168. }
  169. if !ok {
  170. continue
  171. }
  172. pub := signer.PublicKey()
  173. pubKey := pub.Marshal()
  174. sign, err := signer.Sign(rand, buildDataSignedForAuth(session, userAuthRequestMsg{
  175. User: user,
  176. Service: serviceSSH,
  177. Method: cb.method(),
  178. }, []byte(pub.Type()), pubKey))
  179. if err != nil {
  180. return false, nil, err
  181. }
  182. // manually wrap the serialized signature in a string
  183. s := Marshal(sign)
  184. sig := make([]byte, stringLength(len(s)))
  185. marshalString(sig, s)
  186. msg := publickeyAuthMsg{
  187. User: user,
  188. Service: serviceSSH,
  189. Method: cb.method(),
  190. HasSig: true,
  191. Algoname: pub.Type(),
  192. PubKey: pubKey,
  193. Sig: sig,
  194. }
  195. p := Marshal(&msg)
  196. if err := c.writePacket(p); err != nil {
  197. return false, nil, err
  198. }
  199. var success bool
  200. success, methods, err = handleAuthResponse(c)
  201. if err != nil {
  202. return false, nil, err
  203. }
  204. // If authentication succeeds or the list of available methods does not
  205. // contain the "publickey" method, do not attempt to authenticate with any
  206. // other keys. According to RFC 4252 Section 7, the latter can occur when
  207. // additional authentication methods are required.
  208. if success || !containsMethod(methods, cb.method()) {
  209. return success, methods, err
  210. }
  211. }
  212. return false, methods, nil
  213. }
  214. func containsMethod(methods []string, method string) bool {
  215. for _, m := range methods {
  216. if m == method {
  217. return true
  218. }
  219. }
  220. return false
  221. }
  222. // validateKey validates the key provided is acceptable to the server.
  223. func validateKey(key PublicKey, user string, c packetConn) (bool, error) {
  224. pubKey := key.Marshal()
  225. msg := publickeyAuthMsg{
  226. User: user,
  227. Service: serviceSSH,
  228. Method: "publickey",
  229. HasSig: false,
  230. Algoname: key.Type(),
  231. PubKey: pubKey,
  232. }
  233. if err := c.writePacket(Marshal(&msg)); err != nil {
  234. return false, err
  235. }
  236. return confirmKeyAck(key, c)
  237. }
  238. func confirmKeyAck(key PublicKey, c packetConn) (bool, error) {
  239. pubKey := key.Marshal()
  240. algoname := key.Type()
  241. for {
  242. packet, err := c.readPacket()
  243. if err != nil {
  244. return false, err
  245. }
  246. switch packet[0] {
  247. case msgUserAuthBanner:
  248. if err := handleBannerResponse(c, packet); err != nil {
  249. return false, err
  250. }
  251. case msgUserAuthPubKeyOk:
  252. var msg userAuthPubKeyOkMsg
  253. if err := Unmarshal(packet, &msg); err != nil {
  254. return false, err
  255. }
  256. if msg.Algo != algoname || !bytes.Equal(msg.PubKey, pubKey) {
  257. return false, nil
  258. }
  259. return true, nil
  260. case msgUserAuthFailure:
  261. return false, nil
  262. default:
  263. return false, unexpectedMessageError(msgUserAuthSuccess, packet[0])
  264. }
  265. }
  266. }
  267. // PublicKeys returns an AuthMethod that uses the given key
  268. // pairs.
  269. func PublicKeys(signers ...Signer) AuthMethod {
  270. return publicKeyCallback(func() ([]Signer, error) { return signers, nil })
  271. }
  272. // PublicKeysCallback returns an AuthMethod that runs the given
  273. // function to obtain a list of key pairs.
  274. func PublicKeysCallback(getSigners func() (signers []Signer, err error)) AuthMethod {
  275. return publicKeyCallback(getSigners)
  276. }
  277. // handleAuthResponse returns whether the preceding authentication request succeeded
  278. // along with a list of remaining authentication methods to try next and
  279. // an error if an unexpected response was received.
  280. func handleAuthResponse(c packetConn) (bool, []string, error) {
  281. for {
  282. packet, err := c.readPacket()
  283. if err != nil {
  284. return false, nil, err
  285. }
  286. switch packet[0] {
  287. case msgUserAuthBanner:
  288. if err := handleBannerResponse(c, packet); err != nil {
  289. return false, nil, err
  290. }
  291. case msgUserAuthFailure:
  292. var msg userAuthFailureMsg
  293. if err := Unmarshal(packet, &msg); err != nil {
  294. return false, nil, err
  295. }
  296. return false, msg.Methods, nil
  297. case msgUserAuthSuccess:
  298. return true, nil, nil
  299. default:
  300. return false, nil, unexpectedMessageError(msgUserAuthSuccess, packet[0])
  301. }
  302. }
  303. }
  304. func handleBannerResponse(c packetConn, packet []byte) error {
  305. var msg userAuthBannerMsg
  306. if err := Unmarshal(packet, &msg); err != nil {
  307. return err
  308. }
  309. transport, ok := c.(*handshakeTransport)
  310. if !ok {
  311. return nil
  312. }
  313. if transport.bannerCallback != nil {
  314. return transport.bannerCallback(msg.Message)
  315. }
  316. return nil
  317. }
  318. // KeyboardInteractiveChallenge should print questions, optionally
  319. // disabling echoing (e.g. for passwords), and return all the answers.
  320. // Challenge may be called multiple times in a single session. After
  321. // successful authentication, the server may send a challenge with no
  322. // questions, for which the user and instruction messages should be
  323. // printed. RFC 4256 section 3.3 details how the UI should behave for
  324. // both CLI and GUI environments.
  325. type KeyboardInteractiveChallenge func(user, instruction string, questions []string, echos []bool) (answers []string, err error)
  326. // KeyboardInteractive returns an AuthMethod using a prompt/response
  327. // sequence controlled by the server.
  328. func KeyboardInteractive(challenge KeyboardInteractiveChallenge) AuthMethod {
  329. return challenge
  330. }
  331. func (cb KeyboardInteractiveChallenge) method() string {
  332. return "keyboard-interactive"
  333. }
  334. func (cb KeyboardInteractiveChallenge) auth(session []byte, user string, c packetConn, rand io.Reader) (bool, []string, error) {
  335. type initiateMsg struct {
  336. User string `sshtype:"50"`
  337. Service string
  338. Method string
  339. Language string
  340. Submethods string
  341. }
  342. if err := c.writePacket(Marshal(&initiateMsg{
  343. User: user,
  344. Service: serviceSSH,
  345. Method: "keyboard-interactive",
  346. })); err != nil {
  347. return false, nil, err
  348. }
  349. for {
  350. packet, err := c.readPacket()
  351. if err != nil {
  352. return false, nil, err
  353. }
  354. // like handleAuthResponse, but with less options.
  355. switch packet[0] {
  356. case msgUserAuthBanner:
  357. if err := handleBannerResponse(c, packet); err != nil {
  358. return false, nil, err
  359. }
  360. continue
  361. case msgUserAuthInfoRequest:
  362. // OK
  363. case msgUserAuthFailure:
  364. var msg userAuthFailureMsg
  365. if err := Unmarshal(packet, &msg); err != nil {
  366. return false, nil, err
  367. }
  368. return false, msg.Methods, nil
  369. case msgUserAuthSuccess:
  370. return true, nil, nil
  371. default:
  372. return false, nil, unexpectedMessageError(msgUserAuthInfoRequest, packet[0])
  373. }
  374. var msg userAuthInfoRequestMsg
  375. if err := Unmarshal(packet, &msg); err != nil {
  376. return false, nil, err
  377. }
  378. // Manually unpack the prompt/echo pairs.
  379. rest := msg.Prompts
  380. var prompts []string
  381. var echos []bool
  382. for i := 0; i < int(msg.NumPrompts); i++ {
  383. prompt, r, ok := parseString(rest)
  384. if !ok || len(r) == 0 {
  385. return false, nil, errors.New("ssh: prompt format error")
  386. }
  387. prompts = append(prompts, string(prompt))
  388. echos = append(echos, r[0] != 0)
  389. rest = r[1:]
  390. }
  391. if len(rest) != 0 {
  392. return false, nil, errors.New("ssh: extra data following keyboard-interactive pairs")
  393. }
  394. answers, err := cb(msg.User, msg.Instruction, prompts, echos)
  395. if err != nil {
  396. return false, nil, err
  397. }
  398. if len(answers) != len(prompts) {
  399. return false, nil, errors.New("ssh: not enough answers from keyboard-interactive callback")
  400. }
  401. responseLength := 1 + 4
  402. for _, a := range answers {
  403. responseLength += stringLength(len(a))
  404. }
  405. serialized := make([]byte, responseLength)
  406. p := serialized
  407. p[0] = msgUserAuthInfoResponse
  408. p = p[1:]
  409. p = marshalUint32(p, uint32(len(answers)))
  410. for _, a := range answers {
  411. p = marshalString(p, []byte(a))
  412. }
  413. if err := c.writePacket(serialized); err != nil {
  414. return false, nil, err
  415. }
  416. }
  417. }
  418. type retryableAuthMethod struct {
  419. authMethod AuthMethod
  420. maxTries int
  421. }
  422. func (r *retryableAuthMethod) auth(session []byte, user string, c packetConn, rand io.Reader) (ok bool, methods []string, err error) {
  423. for i := 0; r.maxTries <= 0 || i < r.maxTries; i++ {
  424. ok, methods, err = r.authMethod.auth(session, user, c, rand)
  425. if ok || err != nil { // either success or error terminate
  426. return ok, methods, err
  427. }
  428. }
  429. return ok, methods, err
  430. }
  431. func (r *retryableAuthMethod) method() string {
  432. return r.authMethod.method()
  433. }
  434. // RetryableAuthMethod is a decorator for other auth methods enabling them to
  435. // be retried up to maxTries before considering that AuthMethod itself failed.
  436. // If maxTries is <= 0, will retry indefinitely
  437. //
  438. // This is useful for interactive clients using challenge/response type
  439. // authentication (e.g. Keyboard-Interactive, Password, etc) where the user
  440. // could mistype their response resulting in the server issuing a
  441. // SSH_MSG_USERAUTH_FAILURE (rfc4252 #8 [password] and rfc4256 #3.4
  442. // [keyboard-interactive]); Without this decorator, the non-retryable
  443. // AuthMethod would be removed from future consideration, and never tried again
  444. // (and so the user would never be able to retry their entry).
  445. func RetryableAuthMethod(auth AuthMethod, maxTries int) AuthMethod {
  446. return &retryableAuthMethod{authMethod: auth, maxTries: maxTries}
  447. }