client_auth.go 13 KB

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