client_auth.go 11 KB

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