client_auth.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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. // TODO(gpaul): add callback to present the banner to the user
  249. case msgUserAuthPubKeyOk:
  250. var msg userAuthPubKeyOkMsg
  251. if err := Unmarshal(packet, &msg); err != nil {
  252. return false, err
  253. }
  254. if msg.Algo != algoname || !bytes.Equal(msg.PubKey, pubKey) {
  255. return false, nil
  256. }
  257. return true, nil
  258. case msgUserAuthFailure:
  259. return false, nil
  260. default:
  261. return false, unexpectedMessageError(msgUserAuthSuccess, packet[0])
  262. }
  263. }
  264. }
  265. // PublicKeys returns an AuthMethod that uses the given key
  266. // pairs.
  267. func PublicKeys(signers ...Signer) AuthMethod {
  268. return publicKeyCallback(func() ([]Signer, error) { return signers, nil })
  269. }
  270. // PublicKeysCallback returns an AuthMethod that runs the given
  271. // function to obtain a list of key pairs.
  272. func PublicKeysCallback(getSigners func() (signers []Signer, err error)) AuthMethod {
  273. return publicKeyCallback(getSigners)
  274. }
  275. // handleAuthResponse returns whether the preceding authentication request succeeded
  276. // along with a list of remaining authentication methods to try next and
  277. // an error if an unexpected response was received.
  278. func handleAuthResponse(c packetConn) (bool, []string, error) {
  279. for {
  280. packet, err := c.readPacket()
  281. if err != nil {
  282. return false, nil, err
  283. }
  284. switch packet[0] {
  285. case msgUserAuthBanner:
  286. // TODO: add callback to present the banner to the user
  287. case msgUserAuthFailure:
  288. var msg userAuthFailureMsg
  289. if err := Unmarshal(packet, &msg); err != nil {
  290. return false, nil, err
  291. }
  292. return false, msg.Methods, nil
  293. case msgUserAuthSuccess:
  294. return true, nil, nil
  295. default:
  296. return false, nil, unexpectedMessageError(msgUserAuthSuccess, packet[0])
  297. }
  298. }
  299. }
  300. // KeyboardInteractiveChallenge should print questions, optionally
  301. // disabling echoing (e.g. for passwords), and return all the answers.
  302. // Challenge may be called multiple times in a single session. After
  303. // successful authentication, the server may send a challenge with no
  304. // questions, for which the user and instruction messages should be
  305. // printed. RFC 4256 section 3.3 details how the UI should behave for
  306. // both CLI and GUI environments.
  307. type KeyboardInteractiveChallenge func(user, instruction string, questions []string, echos []bool) (answers []string, err error)
  308. // KeyboardInteractive returns a AuthMethod using a prompt/response
  309. // sequence controlled by the server.
  310. func KeyboardInteractive(challenge KeyboardInteractiveChallenge) AuthMethod {
  311. return challenge
  312. }
  313. func (cb KeyboardInteractiveChallenge) method() string {
  314. return "keyboard-interactive"
  315. }
  316. func (cb KeyboardInteractiveChallenge) auth(session []byte, user string, c packetConn, rand io.Reader) (bool, []string, error) {
  317. type initiateMsg struct {
  318. User string `sshtype:"50"`
  319. Service string
  320. Method string
  321. Language string
  322. Submethods string
  323. }
  324. if err := c.writePacket(Marshal(&initiateMsg{
  325. User: user,
  326. Service: serviceSSH,
  327. Method: "keyboard-interactive",
  328. })); err != nil {
  329. return false, nil, err
  330. }
  331. for {
  332. packet, err := c.readPacket()
  333. if err != nil {
  334. return false, nil, err
  335. }
  336. // like handleAuthResponse, but with less options.
  337. switch packet[0] {
  338. case msgUserAuthBanner:
  339. // TODO: Print banners during userauth.
  340. continue
  341. case msgUserAuthInfoRequest:
  342. // OK
  343. case msgUserAuthFailure:
  344. var msg userAuthFailureMsg
  345. if err := Unmarshal(packet, &msg); err != nil {
  346. return false, nil, err
  347. }
  348. return false, msg.Methods, nil
  349. case msgUserAuthSuccess:
  350. return true, nil, nil
  351. default:
  352. return false, nil, unexpectedMessageError(msgUserAuthInfoRequest, packet[0])
  353. }
  354. var msg userAuthInfoRequestMsg
  355. if err := Unmarshal(packet, &msg); err != nil {
  356. return false, nil, err
  357. }
  358. // Manually unpack the prompt/echo pairs.
  359. rest := msg.Prompts
  360. var prompts []string
  361. var echos []bool
  362. for i := 0; i < int(msg.NumPrompts); i++ {
  363. prompt, r, ok := parseString(rest)
  364. if !ok || len(r) == 0 {
  365. return false, nil, errors.New("ssh: prompt format error")
  366. }
  367. prompts = append(prompts, string(prompt))
  368. echos = append(echos, r[0] != 0)
  369. rest = r[1:]
  370. }
  371. if len(rest) != 0 {
  372. return false, nil, errors.New("ssh: extra data following keyboard-interactive pairs")
  373. }
  374. answers, err := cb(msg.User, msg.Instruction, prompts, echos)
  375. if err != nil {
  376. return false, nil, err
  377. }
  378. if len(answers) != len(prompts) {
  379. return false, nil, errors.New("ssh: not enough answers from keyboard-interactive callback")
  380. }
  381. responseLength := 1 + 4
  382. for _, a := range answers {
  383. responseLength += stringLength(len(a))
  384. }
  385. serialized := make([]byte, responseLength)
  386. p := serialized
  387. p[0] = msgUserAuthInfoResponse
  388. p = p[1:]
  389. p = marshalUint32(p, uint32(len(answers)))
  390. for _, a := range answers {
  391. p = marshalString(p, []byte(a))
  392. }
  393. if err := c.writePacket(serialized); err != nil {
  394. return false, nil, err
  395. }
  396. }
  397. }
  398. type retryableAuthMethod struct {
  399. authMethod AuthMethod
  400. maxTries int
  401. }
  402. func (r *retryableAuthMethod) auth(session []byte, user string, c packetConn, rand io.Reader) (ok bool, methods []string, err error) {
  403. for i := 0; r.maxTries <= 0 || i < r.maxTries; i++ {
  404. ok, methods, err = r.authMethod.auth(session, user, c, rand)
  405. if ok || err != nil { // either success or error terminate
  406. return ok, methods, err
  407. }
  408. }
  409. return ok, methods, err
  410. }
  411. func (r *retryableAuthMethod) method() string {
  412. return r.authMethod.method()
  413. }
  414. // RetryableAuthMethod is a decorator for other auth methods enabling them to
  415. // be retried up to maxTries before considering that AuthMethod itself failed.
  416. // If maxTries is <= 0, will retry indefinitely
  417. //
  418. // This is useful for interactive clients using challenge/response type
  419. // authentication (e.g. Keyboard-Interactive, Password, etc) where the user
  420. // could mistype their response resulting in the server issuing a
  421. // SSH_MSG_USERAUTH_FAILURE (rfc4252 #8 [password] and rfc4256 #3.4
  422. // [keyboard-interactive]); Without this decorator, the non-retryable
  423. // AuthMethod would be removed from future consideration, and never tried again
  424. // (and so the user would never be able to retry their entry).
  425. func RetryableAuthMethod(auth AuthMethod, maxTries int) AuthMethod {
  426. return &retryableAuthMethod{authMethod: auth, maxTries: maxTries}
  427. }