client_auth.go 11 KB

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