client_auth.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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. "io"
  8. )
  9. // authenticate authenticates with the remote server. See RFC 4252.
  10. func (c *ClientConn) authenticate(session []byte) error {
  11. // initiate user auth session
  12. if err := c.writePacket(marshal(msgServiceRequest, serviceRequestMsg{serviceUserAuth})); err != nil {
  13. return err
  14. }
  15. packet, err := c.readPacket()
  16. if err != nil {
  17. return err
  18. }
  19. var serviceAccept serviceAcceptMsg
  20. if err := unmarshal(&serviceAccept, packet, msgServiceAccept); err != nil {
  21. return err
  22. }
  23. // during the authentication phase the client first attempts the "none" method
  24. // then any untried methods suggested by the server.
  25. tried, remain := make(map[string]bool), make(map[string]bool)
  26. for auth := ClientAuth(new(noneAuth)); auth != nil; {
  27. ok, methods, err := auth.auth(session, c.config.User, c.transport, c.config.rand())
  28. if err != nil {
  29. return err
  30. }
  31. if ok {
  32. // success
  33. return nil
  34. }
  35. tried[auth.method()] = true
  36. delete(remain, auth.method())
  37. for _, meth := range methods {
  38. if tried[meth] {
  39. // if we've tried meth already, skip it.
  40. continue
  41. }
  42. remain[meth] = true
  43. }
  44. auth = nil
  45. for _, a := range c.config.Auth {
  46. if remain[a.method()] {
  47. auth = a
  48. break
  49. }
  50. }
  51. }
  52. return errors.New("ssh: unable to authenticate, no supported methods remain")
  53. }
  54. // A ClientAuth represents an instance of an RFC 4252 authentication method.
  55. type ClientAuth interface {
  56. // auth authenticates user over transport t.
  57. // Returns true if authentication is successful.
  58. // If authentication is not successful, a []string of alternative
  59. // method names is returned.
  60. auth(session []byte, user string, t *transport, rand io.Reader) (bool, []string, error)
  61. // method returns the RFC 4252 method name.
  62. method() string
  63. }
  64. // "none" authentication, RFC 4252 section 5.2.
  65. type noneAuth int
  66. func (n *noneAuth) auth(session []byte, user string, t *transport, rand io.Reader) (bool, []string, error) {
  67. if err := t.writePacket(marshal(msgUserAuthRequest, userAuthRequestMsg{
  68. User: user,
  69. Service: serviceSSH,
  70. Method: "none",
  71. })); err != nil {
  72. return false, nil, err
  73. }
  74. return handleAuthResponse(t)
  75. }
  76. func (n *noneAuth) method() string {
  77. return "none"
  78. }
  79. // "password" authentication, RFC 4252 Section 8.
  80. type passwordAuth struct {
  81. ClientPassword
  82. }
  83. func (p *passwordAuth) auth(session []byte, user string, t *transport, rand io.Reader) (bool, []string, error) {
  84. type passwordAuthMsg struct {
  85. User string
  86. Service string
  87. Method string
  88. Reply bool
  89. Password string
  90. }
  91. pw, err := p.Password(user)
  92. if err != nil {
  93. return false, nil, err
  94. }
  95. if err := t.writePacket(marshal(msgUserAuthRequest, passwordAuthMsg{
  96. User: user,
  97. Service: serviceSSH,
  98. Method: "password",
  99. Reply: false,
  100. Password: pw,
  101. })); err != nil {
  102. return false, nil, err
  103. }
  104. return handleAuthResponse(t)
  105. }
  106. func (p *passwordAuth) method() string {
  107. return "password"
  108. }
  109. // A ClientPassword implements access to a client's passwords.
  110. type ClientPassword interface {
  111. // Password returns the password to use for user.
  112. Password(user string) (password string, err error)
  113. }
  114. // ClientAuthPassword returns a ClientAuth using password authentication.
  115. func ClientAuthPassword(impl ClientPassword) ClientAuth {
  116. return &passwordAuth{impl}
  117. }
  118. // ClientKeyring implements access to a client key ring.
  119. type ClientKeyring interface {
  120. // Key returns the i'th rsa.Publickey or dsa.Publickey, or nil if
  121. // no key exists at i.
  122. Key(i int) (key interface{}, err error)
  123. // Sign returns a signature of the given data using the i'th key
  124. // and the supplied random source.
  125. Sign(i int, rand io.Reader, data []byte) (sig []byte, err error)
  126. }
  127. // "publickey" authentication, RFC 4252 Section 7.
  128. type publickeyAuth struct {
  129. ClientKeyring
  130. }
  131. type publickeyAuthMsg struct {
  132. User string
  133. Service string
  134. Method string
  135. // HasSig indicates to the reciver packet that the auth request is signed and
  136. // should be used for authentication of the request.
  137. HasSig bool
  138. Algoname string
  139. Pubkey string
  140. // Sig is defined as []byte so marshal will exclude it during validateKey
  141. Sig []byte `ssh:"rest"`
  142. }
  143. func (p *publickeyAuth) auth(session []byte, user string, t *transport, rand io.Reader) (bool, []string, error) {
  144. // Authentication is performed in two stages. The first stage sends an
  145. // enquiry to test if each key is acceptable to the remote. The second
  146. // stage attempts to authenticate with the valid keys obtained in the
  147. // first stage.
  148. var index int
  149. // a map of public keys to their index in the keyring
  150. validKeys := make(map[int]interface{})
  151. for {
  152. key, err := p.Key(index)
  153. if err != nil {
  154. return false, nil, err
  155. }
  156. if key == nil {
  157. // no more keys in the keyring
  158. break
  159. }
  160. if ok, err := p.validateKey(key, user, t); ok {
  161. validKeys[index] = key
  162. } else {
  163. if err != nil {
  164. return false, nil, err
  165. }
  166. }
  167. index++
  168. }
  169. // methods that may continue if this auth is not successful.
  170. var methods []string
  171. for i, key := range validKeys {
  172. pubkey := serializePublickey(key)
  173. algoname := algoName(key)
  174. sign, err := p.Sign(i, rand, buildDataSignedForAuth(session, userAuthRequestMsg{
  175. User: user,
  176. Service: serviceSSH,
  177. Method: p.method(),
  178. }, []byte(algoname), pubkey))
  179. if err != nil {
  180. return false, nil, err
  181. }
  182. // manually wrap the serialized signature in a string
  183. s := serializeSignature(algoname, sign)
  184. sig := make([]byte, stringLength(s))
  185. marshalString(sig, s)
  186. msg := publickeyAuthMsg{
  187. User: user,
  188. Service: serviceSSH,
  189. Method: p.method(),
  190. HasSig: true,
  191. Algoname: algoname,
  192. Pubkey: string(pubkey),
  193. Sig: sig,
  194. }
  195. p := marshal(msgUserAuthRequest, msg)
  196. if err := t.writePacket(p); err != nil {
  197. return false, nil, err
  198. }
  199. success, methods, err := handleAuthResponse(t)
  200. if err != nil {
  201. return false, nil, err
  202. }
  203. if success {
  204. return success, methods, err
  205. }
  206. }
  207. return false, methods, nil
  208. }
  209. // validateKey validates the key provided it is acceptable to the server.
  210. func (p *publickeyAuth) validateKey(key interface{}, user string, t *transport) (bool, error) {
  211. pubkey := serializePublickey(key)
  212. algoname := algoName(key)
  213. msg := publickeyAuthMsg{
  214. User: user,
  215. Service: serviceSSH,
  216. Method: p.method(),
  217. HasSig: false,
  218. Algoname: algoname,
  219. Pubkey: string(pubkey),
  220. }
  221. if err := t.writePacket(marshal(msgUserAuthRequest, msg)); err != nil {
  222. return false, err
  223. }
  224. return p.confirmKeyAck(key, t)
  225. }
  226. func (p *publickeyAuth) confirmKeyAck(key interface{}, t *transport) (bool, error) {
  227. pubkey := serializePublickey(key)
  228. algoname := algoName(key)
  229. for {
  230. packet, err := t.readPacket()
  231. if err != nil {
  232. return false, err
  233. }
  234. switch packet[0] {
  235. case msgUserAuthBanner:
  236. // TODO(gpaul): add callback to present the banner to the user
  237. case msgUserAuthPubKeyOk:
  238. msg := decode(packet).(*userAuthPubKeyOkMsg)
  239. if msg.Algo != algoname || msg.PubKey != string(pubkey) {
  240. return false, nil
  241. }
  242. return true, nil
  243. case msgUserAuthFailure:
  244. return false, nil
  245. default:
  246. return false, UnexpectedMessageError{msgUserAuthSuccess, packet[0]}
  247. }
  248. }
  249. panic("unreachable")
  250. }
  251. func (p *publickeyAuth) method() string {
  252. return "publickey"
  253. }
  254. // ClientAuthKeyring returns a ClientAuth using public key authentication.
  255. func ClientAuthKeyring(impl ClientKeyring) ClientAuth {
  256. return &publickeyAuth{impl}
  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(t *transport) (bool, []string, error) {
  262. for {
  263. packet, err := t.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. msg := decode(packet).(*userAuthFailureMsg)
  272. return false, msg.Methods, nil
  273. case msgUserAuthSuccess:
  274. return true, nil, nil
  275. case msgDisconnect:
  276. return false, nil, io.EOF
  277. default:
  278. return false, nil, UnexpectedMessageError{msgUserAuthSuccess, packet[0]}
  279. }
  280. }
  281. panic("unreachable")
  282. }