client_auth.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  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 in two stages. The first stage sends an
  156. // enquiry to test if each key is acceptable to the remote. The second
  157. // stage attempts to authenticate with the valid keys obtained in the
  158. // first stage.
  159. signers, err := cb()
  160. if err != nil {
  161. return false, nil, err
  162. }
  163. var validKeys []Signer
  164. for _, signer := range signers {
  165. if ok, err := validateKey(signer.PublicKey(), user, c); ok {
  166. validKeys = append(validKeys, signer)
  167. } else {
  168. if err != nil {
  169. return false, nil, err
  170. }
  171. }
  172. }
  173. // methods that may continue if this auth is not successful.
  174. var methods []string
  175. for _, signer := range validKeys {
  176. pub := signer.PublicKey()
  177. pubKey := pub.Marshal()
  178. sign, err := signer.Sign(rand, buildDataSignedForAuth(session, userAuthRequestMsg{
  179. User: user,
  180. Service: serviceSSH,
  181. Method: cb.method(),
  182. }, []byte(pub.Type()), pubKey))
  183. if err != nil {
  184. return false, nil, err
  185. }
  186. // manually wrap the serialized signature in a string
  187. s := Marshal(sign)
  188. sig := make([]byte, stringLength(len(s)))
  189. marshalString(sig, s)
  190. msg := publickeyAuthMsg{
  191. User: user,
  192. Service: serviceSSH,
  193. Method: cb.method(),
  194. HasSig: true,
  195. Algoname: pub.Type(),
  196. PubKey: pubKey,
  197. Sig: sig,
  198. }
  199. p := Marshal(&msg)
  200. if err := c.writePacket(p); err != nil {
  201. return false, nil, err
  202. }
  203. var success bool
  204. success, methods, err = handleAuthResponse(c)
  205. if err != nil {
  206. return false, nil, err
  207. }
  208. if success {
  209. return success, methods, err
  210. }
  211. }
  212. return false, methods, nil
  213. }
  214. // validateKey validates the key provided is acceptable to the server.
  215. func validateKey(key PublicKey, user string, c packetConn) (bool, error) {
  216. pubKey := key.Marshal()
  217. msg := publickeyAuthMsg{
  218. User: user,
  219. Service: serviceSSH,
  220. Method: "publickey",
  221. HasSig: false,
  222. Algoname: key.Type(),
  223. PubKey: pubKey,
  224. }
  225. if err := c.writePacket(Marshal(&msg)); err != nil {
  226. return false, err
  227. }
  228. return confirmKeyAck(key, c)
  229. }
  230. func confirmKeyAck(key PublicKey, c packetConn) (bool, error) {
  231. pubKey := key.Marshal()
  232. algoname := key.Type()
  233. for {
  234. packet, err := c.readPacket()
  235. if err != nil {
  236. return false, err
  237. }
  238. switch packet[0] {
  239. case msgUserAuthBanner:
  240. // TODO(gpaul): add callback to present the banner to the user
  241. case msgUserAuthPubKeyOk:
  242. var msg userAuthPubKeyOkMsg
  243. if err := Unmarshal(packet, &msg); err != nil {
  244. return false, err
  245. }
  246. if msg.Algo != algoname || !bytes.Equal(msg.PubKey, pubKey) {
  247. return false, nil
  248. }
  249. return true, nil
  250. case msgUserAuthFailure:
  251. return false, nil
  252. default:
  253. return false, unexpectedMessageError(msgUserAuthSuccess, packet[0])
  254. }
  255. }
  256. }
  257. // PublicKeys returns an AuthMethod that uses the given key
  258. // pairs.
  259. func PublicKeys(signers ...Signer) AuthMethod {
  260. return publicKeyCallback(func() ([]Signer, error) { return signers, nil })
  261. }
  262. // PublicKeysCallback returns an AuthMethod that runs the given
  263. // function to obtain a list of key pairs.
  264. func PublicKeysCallback(getSigners func() (signers []Signer, err error)) AuthMethod {
  265. return publicKeyCallback(getSigners)
  266. }
  267. // handleAuthResponse returns whether the preceding authentication request succeeded
  268. // along with a list of remaining authentication methods to try next and
  269. // an error if an unexpected response was received.
  270. func handleAuthResponse(c packetConn) (bool, []string, error) {
  271. for {
  272. packet, err := c.readPacket()
  273. if err != nil {
  274. return false, nil, err
  275. }
  276. switch packet[0] {
  277. case msgUserAuthBanner:
  278. // TODO: add callback to present the banner to the user
  279. case msgUserAuthFailure:
  280. var msg userAuthFailureMsg
  281. if err := Unmarshal(packet, &msg); err != nil {
  282. return false, nil, err
  283. }
  284. return false, msg.Methods, nil
  285. case msgUserAuthSuccess:
  286. return true, nil, nil
  287. default:
  288. return false, nil, unexpectedMessageError(msgUserAuthSuccess, packet[0])
  289. }
  290. }
  291. }
  292. // KeyboardInteractiveChallenge should print questions, optionally
  293. // disabling echoing (e.g. for passwords), and return all the answers.
  294. // Challenge may be called multiple times in a single session. After
  295. // successful authentication, the server may send a challenge with no
  296. // questions, for which the user and instruction messages should be
  297. // printed. RFC 4256 section 3.3 details how the UI should behave for
  298. // both CLI and GUI environments.
  299. type KeyboardInteractiveChallenge func(user, instruction string, questions []string, echos []bool) (answers []string, err error)
  300. // KeyboardInteractive returns a AuthMethod using a prompt/response
  301. // sequence controlled by the server.
  302. func KeyboardInteractive(challenge KeyboardInteractiveChallenge) AuthMethod {
  303. return challenge
  304. }
  305. func (cb KeyboardInteractiveChallenge) method() string {
  306. return "keyboard-interactive"
  307. }
  308. func (cb KeyboardInteractiveChallenge) auth(session []byte, user string, c packetConn, rand io.Reader) (bool, []string, error) {
  309. type initiateMsg struct {
  310. User string `sshtype:"50"`
  311. Service string
  312. Method string
  313. Language string
  314. Submethods string
  315. }
  316. if err := c.writePacket(Marshal(&initiateMsg{
  317. User: user,
  318. Service: serviceSSH,
  319. Method: "keyboard-interactive",
  320. })); err != nil {
  321. return false, nil, err
  322. }
  323. for {
  324. packet, err := c.readPacket()
  325. if err != nil {
  326. return false, nil, err
  327. }
  328. // like handleAuthResponse, but with less options.
  329. switch packet[0] {
  330. case msgUserAuthBanner:
  331. // TODO: Print banners during userauth.
  332. continue
  333. case msgUserAuthInfoRequest:
  334. // OK
  335. case msgUserAuthFailure:
  336. var msg userAuthFailureMsg
  337. if err := Unmarshal(packet, &msg); err != nil {
  338. return false, nil, err
  339. }
  340. return false, msg.Methods, nil
  341. case msgUserAuthSuccess:
  342. return true, nil, nil
  343. default:
  344. return false, nil, unexpectedMessageError(msgUserAuthInfoRequest, packet[0])
  345. }
  346. var msg userAuthInfoRequestMsg
  347. if err := Unmarshal(packet, &msg); err != nil {
  348. return false, nil, err
  349. }
  350. // Manually unpack the prompt/echo pairs.
  351. rest := msg.Prompts
  352. var prompts []string
  353. var echos []bool
  354. for i := 0; i < int(msg.NumPrompts); i++ {
  355. prompt, r, ok := parseString(rest)
  356. if !ok || len(r) == 0 {
  357. return false, nil, errors.New("ssh: prompt format error")
  358. }
  359. prompts = append(prompts, string(prompt))
  360. echos = append(echos, r[0] != 0)
  361. rest = r[1:]
  362. }
  363. if len(rest) != 0 {
  364. return false, nil, errors.New("ssh: extra data following keyboard-interactive pairs")
  365. }
  366. answers, err := cb(msg.User, msg.Instruction, prompts, echos)
  367. if err != nil {
  368. return false, nil, err
  369. }
  370. if len(answers) != len(prompts) {
  371. return false, nil, errors.New("ssh: not enough answers from keyboard-interactive callback")
  372. }
  373. responseLength := 1 + 4
  374. for _, a := range answers {
  375. responseLength += stringLength(len(a))
  376. }
  377. serialized := make([]byte, responseLength)
  378. p := serialized
  379. p[0] = msgUserAuthInfoResponse
  380. p = p[1:]
  381. p = marshalUint32(p, uint32(len(answers)))
  382. for _, a := range answers {
  383. p = marshalString(p, []byte(a))
  384. }
  385. if err := c.writePacket(serialized); err != nil {
  386. return false, nil, err
  387. }
  388. }
  389. }
  390. type retryableAuthMethod struct {
  391. authMethod AuthMethod
  392. maxTries int
  393. }
  394. func (r *retryableAuthMethod) auth(session []byte, user string, c packetConn, rand io.Reader) (ok bool, methods []string, err error) {
  395. for i := 0; r.maxTries <= 0 || i < r.maxTries; i++ {
  396. ok, methods, err = r.authMethod.auth(session, user, c, rand)
  397. if ok || err != nil { // either success or error terminate
  398. return ok, methods, err
  399. }
  400. }
  401. return ok, methods, err
  402. }
  403. func (r *retryableAuthMethod) method() string {
  404. return r.authMethod.method()
  405. }
  406. // RetryableAuthMethod is a decorator for other auth methods enabling them to
  407. // be retried up to maxTries before considering that AuthMethod itself failed.
  408. // If maxTries is <= 0, will retry indefinitely
  409. //
  410. // This is useful for interactive clients using challenge/response type
  411. // authentication (e.g. Keyboard-Interactive, Password, etc) where the user
  412. // could mistype their response resulting in the server issuing a
  413. // SSH_MSG_USERAUTH_FAILURE (rfc4252 #8 [password] and rfc4256 #3.4
  414. // [keyboard-interactive]); Without this decorator, the non-retryable
  415. // AuthMethod would be removed from future consideration, and never tried again
  416. // (and so the user would never be able to retry their entry).
  417. func RetryableAuthMethod(auth AuthMethod, maxTries int) AuthMethod {
  418. return &retryableAuthMethod{authMethod: auth, maxTries: maxTries}
  419. }