You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

441 lines
12 KiB

  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. case msgDisconnect:
  287. return false, nil, io.EOF
  288. default:
  289. return false, nil, unexpectedMessageError(msgUserAuthSuccess, packet[0])
  290. }
  291. }
  292. }
  293. // KeyboardInteractiveChallenge should print questions, optionally
  294. // disabling echoing (e.g. for passwords), and return all the answers.
  295. // Challenge may be called multiple times in a single session. After
  296. // successful authentication, the server may send a challenge with no
  297. // questions, for which the user and instruction messages should be
  298. // printed. RFC 4256 section 3.3 details how the UI should behave for
  299. // both CLI and GUI environments.
  300. type KeyboardInteractiveChallenge func(user, instruction string, questions []string, echos []bool) (answers []string, err error)
  301. // KeyboardInteractive returns a AuthMethod using a prompt/response
  302. // sequence controlled by the server.
  303. func KeyboardInteractive(challenge KeyboardInteractiveChallenge) AuthMethod {
  304. return challenge
  305. }
  306. func (cb KeyboardInteractiveChallenge) method() string {
  307. return "keyboard-interactive"
  308. }
  309. func (cb KeyboardInteractiveChallenge) auth(session []byte, user string, c packetConn, rand io.Reader) (bool, []string, error) {
  310. type initiateMsg struct {
  311. User string `sshtype:"50"`
  312. Service string
  313. Method string
  314. Language string
  315. Submethods string
  316. }
  317. if err := c.writePacket(Marshal(&initiateMsg{
  318. User: user,
  319. Service: serviceSSH,
  320. Method: "keyboard-interactive",
  321. })); err != nil {
  322. return false, nil, err
  323. }
  324. for {
  325. packet, err := c.readPacket()
  326. if err != nil {
  327. return false, nil, err
  328. }
  329. // like handleAuthResponse, but with less options.
  330. switch packet[0] {
  331. case msgUserAuthBanner:
  332. // TODO: Print banners during userauth.
  333. continue
  334. case msgUserAuthInfoRequest:
  335. // OK
  336. case msgUserAuthFailure:
  337. var msg userAuthFailureMsg
  338. if err := Unmarshal(packet, &msg); err != nil {
  339. return false, nil, err
  340. }
  341. return false, msg.Methods, nil
  342. case msgUserAuthSuccess:
  343. return true, nil, nil
  344. default:
  345. return false, nil, unexpectedMessageError(msgUserAuthInfoRequest, packet[0])
  346. }
  347. var msg userAuthInfoRequestMsg
  348. if err := Unmarshal(packet, &msg); err != nil {
  349. return false, nil, err
  350. }
  351. // Manually unpack the prompt/echo pairs.
  352. rest := msg.Prompts
  353. var prompts []string
  354. var echos []bool
  355. for i := 0; i < int(msg.NumPrompts); i++ {
  356. prompt, r, ok := parseString(rest)
  357. if !ok || len(r) == 0 {
  358. return false, nil, errors.New("ssh: prompt format error")
  359. }
  360. prompts = append(prompts, string(prompt))
  361. echos = append(echos, r[0] != 0)
  362. rest = r[1:]
  363. }
  364. if len(rest) != 0 {
  365. return false, nil, errors.New("ssh: extra data following keyboard-interactive pairs")
  366. }
  367. answers, err := cb(msg.User, msg.Instruction, prompts, echos)
  368. if err != nil {
  369. return false, nil, err
  370. }
  371. if len(answers) != len(prompts) {
  372. return false, nil, errors.New("ssh: not enough answers from keyboard-interactive callback")
  373. }
  374. responseLength := 1 + 4
  375. for _, a := range answers {
  376. responseLength += stringLength(len(a))
  377. }
  378. serialized := make([]byte, responseLength)
  379. p := serialized
  380. p[0] = msgUserAuthInfoResponse
  381. p = p[1:]
  382. p = marshalUint32(p, uint32(len(answers)))
  383. for _, a := range answers {
  384. p = marshalString(p, []byte(a))
  385. }
  386. if err := c.writePacket(serialized); err != nil {
  387. return false, nil, err
  388. }
  389. }
  390. }