client_auth.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  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. "errors"
  7. "fmt"
  8. "io"
  9. "net"
  10. )
  11. // authenticate authenticates with the remote server. See RFC 4252.
  12. func (c *ClientConn) authenticate(session []byte) error {
  13. // initiate user auth session
  14. if err := c.writePacket(marshal(msgServiceRequest, serviceRequestMsg{serviceUserAuth})); err != nil {
  15. return err
  16. }
  17. packet, err := c.readPacket()
  18. if err != nil {
  19. return err
  20. }
  21. var serviceAccept serviceAcceptMsg
  22. if err := unmarshal(&serviceAccept, packet, msgServiceAccept); 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, remain := make(map[string]bool), make(map[string]bool)
  28. for auth := ClientAuth(new(noneAuth)); auth != nil; {
  29. ok, methods, err := auth.auth(session, c.config.User, c.transport, c.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. delete(remain, auth.method())
  39. for _, meth := range methods {
  40. if tried[meth] {
  41. // if we've tried meth already, skip it.
  42. continue
  43. }
  44. remain[meth] = true
  45. }
  46. auth = nil
  47. for _, a := range c.config.Auth {
  48. if remain[a.method()] {
  49. auth = a
  50. break
  51. }
  52. }
  53. }
  54. return fmt.Errorf("ssh: unable to authenticate, attempted methods %v, no supported methods remain", keys(tried))
  55. }
  56. func keys(m map[string]bool) (s []string) {
  57. for k := range m {
  58. s = append(s, k)
  59. }
  60. return
  61. }
  62. // HostKeyChecker represents a database of known server host keys.
  63. type HostKeyChecker interface {
  64. // Check is called during the handshake to check server's
  65. // public key for unexpected changes. The hostKey argument is
  66. // in SSH wire format. It can be parsed using
  67. // ssh.ParsePublicKey. The address before DNS resolution is
  68. // passed in the addr argument, so the key can also be checked
  69. // against the hostname.
  70. Check(addr string, remote net.Addr, algorithm string, hostKey []byte) error
  71. }
  72. // A ClientAuth represents an instance of an RFC 4252 authentication method.
  73. type ClientAuth interface {
  74. // auth authenticates user over transport t.
  75. // Returns true if authentication is successful.
  76. // If authentication is not successful, a []string of alternative
  77. // method names is returned.
  78. auth(session []byte, user string, t *transport, rand io.Reader) (bool, []string, error)
  79. // method returns the RFC 4252 method name.
  80. method() string
  81. }
  82. // "none" authentication, RFC 4252 section 5.2.
  83. type noneAuth int
  84. func (n *noneAuth) auth(session []byte, user string, t *transport, rand io.Reader) (bool, []string, error) {
  85. if err := t.writePacket(marshal(msgUserAuthRequest, userAuthRequestMsg{
  86. User: user,
  87. Service: serviceSSH,
  88. Method: "none",
  89. })); err != nil {
  90. return false, nil, err
  91. }
  92. return handleAuthResponse(t)
  93. }
  94. func (n *noneAuth) method() string {
  95. return "none"
  96. }
  97. // "password" authentication, RFC 4252 Section 8.
  98. type passwordAuth struct {
  99. ClientPassword
  100. }
  101. func (p *passwordAuth) auth(session []byte, user string, t *transport, rand io.Reader) (bool, []string, error) {
  102. type passwordAuthMsg struct {
  103. User string
  104. Service string
  105. Method string
  106. Reply bool
  107. Password string
  108. }
  109. pw, err := p.Password(user)
  110. if err != nil {
  111. return false, nil, err
  112. }
  113. if err := t.writePacket(marshal(msgUserAuthRequest, passwordAuthMsg{
  114. User: user,
  115. Service: serviceSSH,
  116. Method: "password",
  117. Reply: false,
  118. Password: pw,
  119. })); err != nil {
  120. return false, nil, err
  121. }
  122. return handleAuthResponse(t)
  123. }
  124. func (p *passwordAuth) method() string {
  125. return "password"
  126. }
  127. // A ClientPassword implements access to a client's passwords.
  128. type ClientPassword interface {
  129. // Password returns the password to use for user.
  130. Password(user string) (password string, err error)
  131. }
  132. // ClientAuthPassword returns a ClientAuth using password authentication.
  133. func ClientAuthPassword(impl ClientPassword) ClientAuth {
  134. return &passwordAuth{impl}
  135. }
  136. // ClientKeyring implements access to a client key ring.
  137. type ClientKeyring interface {
  138. // Key returns the i'th *rsa.Publickey or *dsa.Publickey, or nil if
  139. // no key exists at i.
  140. Key(i int) (key interface{}, err error)
  141. // Sign returns a signature of the given data using the i'th key
  142. // and the supplied random source.
  143. Sign(i int, rand io.Reader, data []byte) (sig []byte, err error)
  144. }
  145. // "publickey" authentication, RFC 4252 Section 7.
  146. type publickeyAuth struct {
  147. ClientKeyring
  148. }
  149. type publickeyAuthMsg struct {
  150. User string
  151. Service string
  152. Method string
  153. // HasSig indicates to the reciver packet that the auth request is signed and
  154. // should be used for authentication of the request.
  155. HasSig bool
  156. Algoname string
  157. Pubkey string
  158. // Sig is defined as []byte so marshal will exclude it during validateKey
  159. Sig []byte `ssh:"rest"`
  160. }
  161. func (p *publickeyAuth) auth(session []byte, user string, t *transport, rand io.Reader) (bool, []string, error) {
  162. // Authentication is performed in two stages. The first stage sends an
  163. // enquiry to test if each key is acceptable to the remote. The second
  164. // stage attempts to authenticate with the valid keys obtained in the
  165. // first stage.
  166. var index int
  167. // a map of public keys to their index in the keyring
  168. validKeys := make(map[int]interface{})
  169. for {
  170. key, err := p.Key(index)
  171. if err != nil {
  172. return false, nil, err
  173. }
  174. if key == nil {
  175. // no more keys in the keyring
  176. break
  177. }
  178. if ok, err := p.validateKey(key, user, t); ok {
  179. validKeys[index] = key
  180. } else {
  181. if err != nil {
  182. return false, nil, err
  183. }
  184. }
  185. index++
  186. }
  187. // methods that may continue if this auth is not successful.
  188. var methods []string
  189. for i, key := range validKeys {
  190. pubkey := serializePublicKey(key)
  191. algoname := algoName(key)
  192. sign, err := p.Sign(i, rand, buildDataSignedForAuth(session, userAuthRequestMsg{
  193. User: user,
  194. Service: serviceSSH,
  195. Method: p.method(),
  196. }, []byte(algoname), pubkey))
  197. if err != nil {
  198. return false, nil, err
  199. }
  200. // manually wrap the serialized signature in a string
  201. s := serializeSignature(algoname, sign)
  202. sig := make([]byte, stringLength(len(s)))
  203. marshalString(sig, s)
  204. msg := publickeyAuthMsg{
  205. User: user,
  206. Service: serviceSSH,
  207. Method: p.method(),
  208. HasSig: true,
  209. Algoname: algoname,
  210. Pubkey: string(pubkey),
  211. Sig: sig,
  212. }
  213. p := marshal(msgUserAuthRequest, msg)
  214. if err := t.writePacket(p); err != nil {
  215. return false, nil, err
  216. }
  217. success, methods, err := handleAuthResponse(t)
  218. if err != nil {
  219. return false, nil, err
  220. }
  221. if success {
  222. return success, methods, err
  223. }
  224. }
  225. return false, methods, nil
  226. }
  227. // validateKey validates the key provided it is acceptable to the server.
  228. func (p *publickeyAuth) validateKey(key interface{}, user string, t *transport) (bool, error) {
  229. pubkey := serializePublicKey(key)
  230. algoname := algoName(key)
  231. msg := publickeyAuthMsg{
  232. User: user,
  233. Service: serviceSSH,
  234. Method: p.method(),
  235. HasSig: false,
  236. Algoname: algoname,
  237. Pubkey: string(pubkey),
  238. }
  239. if err := t.writePacket(marshal(msgUserAuthRequest, msg)); err != nil {
  240. return false, err
  241. }
  242. return p.confirmKeyAck(key, t)
  243. }
  244. func (p *publickeyAuth) confirmKeyAck(key interface{}, t *transport) (bool, error) {
  245. pubkey := serializePublicKey(key)
  246. algoname := algoName(key)
  247. for {
  248. packet, err := t.readPacket()
  249. if err != nil {
  250. return false, err
  251. }
  252. switch packet[0] {
  253. case msgUserAuthBanner:
  254. // TODO(gpaul): add callback to present the banner to the user
  255. case msgUserAuthPubKeyOk:
  256. msg := userAuthPubKeyOkMsg{}
  257. if err := unmarshal(&msg, packet, msgUserAuthPubKeyOk); err != nil {
  258. return false, err
  259. }
  260. if msg.Algo != algoname || msg.PubKey != string(pubkey) {
  261. return false, nil
  262. }
  263. return true, nil
  264. case msgUserAuthFailure:
  265. return false, nil
  266. default:
  267. return false, UnexpectedMessageError{msgUserAuthSuccess, packet[0]}
  268. }
  269. }
  270. panic("unreachable")
  271. }
  272. func (p *publickeyAuth) method() string {
  273. return "publickey"
  274. }
  275. // ClientAuthKeyring returns a ClientAuth using public key authentication.
  276. func ClientAuthKeyring(impl ClientKeyring) ClientAuth {
  277. return &publickeyAuth{impl}
  278. }
  279. // handleAuthResponse returns whether the preceding authentication request succeeded
  280. // along with a list of remaining authentication methods to try next and
  281. // an error if an unexpected response was received.
  282. func handleAuthResponse(t *transport) (bool, []string, error) {
  283. for {
  284. packet, err := t.readPacket()
  285. if err != nil {
  286. return false, nil, err
  287. }
  288. switch packet[0] {
  289. case msgUserAuthBanner:
  290. // TODO: add callback to present the banner to the user
  291. case msgUserAuthFailure:
  292. msg := userAuthFailureMsg{}
  293. if err := unmarshal(&msg, packet, msgUserAuthFailure); err != nil {
  294. return false, nil, err
  295. }
  296. return false, msg.Methods, nil
  297. case msgUserAuthSuccess:
  298. return true, nil, nil
  299. case msgDisconnect:
  300. return false, nil, io.EOF
  301. default:
  302. return false, nil, UnexpectedMessageError{msgUserAuthSuccess, packet[0]}
  303. }
  304. }
  305. panic("unreachable")
  306. }
  307. // ClientAuthAgent returns a ClientAuth using public key authentication via
  308. // an agent.
  309. func ClientAuthAgent(agent *AgentClient) ClientAuth {
  310. return ClientAuthKeyring(&agentKeyring{agent: agent})
  311. }
  312. // agentKeyring implements ClientKeyring.
  313. type agentKeyring struct {
  314. agent *AgentClient
  315. keys []*AgentKey
  316. }
  317. func (kr *agentKeyring) Key(i int) (key interface{}, err error) {
  318. if kr.keys == nil {
  319. if kr.keys, err = kr.agent.RequestIdentities(); err != nil {
  320. return
  321. }
  322. }
  323. if i >= len(kr.keys) {
  324. return
  325. }
  326. return kr.keys[i].Key()
  327. }
  328. func (kr *agentKeyring) Sign(i int, rand io.Reader, data []byte) (sig []byte, err error) {
  329. var key interface{}
  330. if key, err = kr.Key(i); err != nil {
  331. return
  332. }
  333. if key == nil {
  334. return nil, errors.New("ssh: key index out of range")
  335. }
  336. if sig, err = kr.agent.SignRequest(key, data); err != nil {
  337. return
  338. }
  339. // Unmarshal the signature.
  340. var ok bool
  341. if _, sig, ok = parseString(sig); !ok {
  342. return nil, errors.New("ssh: malformed signature response from agent")
  343. }
  344. if sig, _, ok = parseString(sig); !ok {
  345. return nil, errors.New("ssh: malformed signature response from agent")
  346. }
  347. return sig, nil
  348. }
  349. // ClientKeyboardInteractive should prompt the user for the given
  350. // questions.
  351. type ClientKeyboardInteractive interface {
  352. // Challenge should print the questions, optionally disabling
  353. // echoing (eg. for passwords), and return all the answers.
  354. // Challenge may be called multiple times in a single
  355. // session. After successful authentication, the server may
  356. // send a challenge with no questions, for which the user and
  357. // instruction messages should be printed. RFC 4256 section
  358. // 3.3 details how the UI should behave for both CLI and
  359. // GUI environments.
  360. Challenge(user, instruction string, questions []string, echos []bool) ([]string, error)
  361. }
  362. // ClientAuthKeyboardInteractive returns a ClientAuth using a
  363. // prompt/response sequence controlled by the server.
  364. func ClientAuthKeyboardInteractive(impl ClientKeyboardInteractive) ClientAuth {
  365. return &keyboardInteractiveAuth{impl}
  366. }
  367. type keyboardInteractiveAuth struct {
  368. ClientKeyboardInteractive
  369. }
  370. func (c *keyboardInteractiveAuth) method() string {
  371. return "keyboard-interactive"
  372. }
  373. func (c *keyboardInteractiveAuth) auth(session []byte, user string, t *transport, rand io.Reader) (bool, []string, error) {
  374. type initiateMsg struct {
  375. User string
  376. Service string
  377. Method string
  378. Language string
  379. Submethods string
  380. }
  381. if err := t.writePacket(marshal(msgUserAuthRequest, initiateMsg{
  382. User: user,
  383. Service: serviceSSH,
  384. Method: "keyboard-interactive",
  385. })); err != nil {
  386. return false, nil, err
  387. }
  388. for {
  389. packet, err := t.readPacket()
  390. if err != nil {
  391. return false, nil, err
  392. }
  393. // like handleAuthResponse, but with less options.
  394. switch packet[0] {
  395. case msgUserAuthBanner:
  396. // TODO: Print banners during userauth.
  397. continue
  398. case msgUserAuthInfoRequest:
  399. // OK
  400. case msgUserAuthFailure:
  401. var msg userAuthFailureMsg
  402. if err := unmarshal(&msg, packet, msgUserAuthFailure); err != nil {
  403. return false, nil, err
  404. }
  405. return false, msg.Methods, nil
  406. case msgUserAuthSuccess:
  407. return true, nil, nil
  408. default:
  409. return false, nil, UnexpectedMessageError{msgUserAuthInfoRequest, packet[0]}
  410. }
  411. var msg userAuthInfoRequestMsg
  412. if err := unmarshal(&msg, packet, packet[0]); err != nil {
  413. return false, nil, err
  414. }
  415. // Manually unpack the prompt/echo pairs.
  416. rest := msg.Prompts
  417. var prompts []string
  418. var echos []bool
  419. for i := 0; i < int(msg.NumPrompts); i++ {
  420. prompt, r, ok := parseString(rest)
  421. if !ok || len(r) == 0 {
  422. return false, nil, errors.New("ssh: prompt format error")
  423. }
  424. prompts = append(prompts, string(prompt))
  425. echos = append(echos, r[0] != 0)
  426. rest = r[1:]
  427. }
  428. if len(rest) != 0 {
  429. return false, nil, fmt.Errorf("ssh: junk following message %q", rest)
  430. }
  431. answers, err := c.Challenge(msg.User, msg.Instruction, prompts, echos)
  432. if err != nil {
  433. return false, nil, err
  434. }
  435. if len(answers) != len(prompts) {
  436. return false, nil, errors.New("ssh: not enough answers from keyboard-interactive callback")
  437. }
  438. responseLength := 1 + 4
  439. for _, a := range answers {
  440. responseLength += stringLength(len(a))
  441. }
  442. serialized := make([]byte, responseLength)
  443. p := serialized
  444. p[0] = msgUserAuthInfoResponse
  445. p = p[1:]
  446. p = marshalUint32(p, uint32(len(answers)))
  447. for _, a := range answers {
  448. p = marshalString(p, []byte(a))
  449. }
  450. if err := t.writePacket(serialized); err != nil {
  451. return false, nil, err
  452. }
  453. }
  454. }