client_auth_test.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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. "crypto/rand"
  8. "errors"
  9. "fmt"
  10. "strings"
  11. "testing"
  12. )
  13. type keyboardInteractive map[string]string
  14. func (cr keyboardInteractive) Challenge(user string, instruction string, questions []string, echos []bool) ([]string, error) {
  15. var answers []string
  16. for _, q := range questions {
  17. answers = append(answers, cr[q])
  18. }
  19. return answers, nil
  20. }
  21. // reused internally by tests
  22. var clientPassword = "tiger"
  23. // tryAuth runs a handshake with a given config against an SSH server
  24. // with config serverConfig
  25. func tryAuth(t *testing.T, config *ClientConfig) error {
  26. c1, c2, err := netPipe()
  27. if err != nil {
  28. t.Fatalf("netPipe: %v", err)
  29. }
  30. defer c1.Close()
  31. defer c2.Close()
  32. certChecker := CertChecker{
  33. IsAuthority: func(k PublicKey) bool {
  34. return bytes.Equal(k.Marshal(), testPublicKeys["ecdsa"].Marshal())
  35. },
  36. UserKeyFallback: func(conn ConnMetadata, key PublicKey) (*Permissions, error) {
  37. if conn.User() == "testuser" && bytes.Equal(key.Marshal(), testPublicKeys["rsa"].Marshal()) {
  38. return nil, nil
  39. }
  40. return nil, fmt.Errorf("pubkey for %q not acceptable", conn.User())
  41. },
  42. IsRevoked: func(c *Certificate) bool {
  43. return c.Serial == 666
  44. },
  45. }
  46. serverConfig := &ServerConfig{
  47. PasswordCallback: func(conn ConnMetadata, pass []byte) (*Permissions, error) {
  48. if conn.User() == "testuser" && string(pass) == clientPassword {
  49. return nil, nil
  50. }
  51. return nil, errors.New("password auth failed")
  52. },
  53. PublicKeyCallback: certChecker.Authenticate,
  54. KeyboardInteractiveCallback: func(conn ConnMetadata, challenge KeyboardInteractiveChallenge) (*Permissions, error) {
  55. ans, err := challenge("user",
  56. "instruction",
  57. []string{"question1", "question2"},
  58. []bool{true, true})
  59. if err != nil {
  60. return nil, err
  61. }
  62. ok := conn.User() == "testuser" && ans[0] == "answer1" && ans[1] == "answer2"
  63. if ok {
  64. challenge("user", "motd", nil, nil)
  65. return nil, nil
  66. }
  67. return nil, errors.New("keyboard-interactive failed")
  68. },
  69. AuthLogCallback: func(conn ConnMetadata, method string, err error) {
  70. t.Logf("user %q, method %q: %v", conn.User(), method, err)
  71. },
  72. }
  73. serverConfig.AddHostKey(testSigners["rsa"])
  74. go newServer(c1, serverConfig)
  75. _, _, _, err = NewClientConn(c2, "", config)
  76. return err
  77. }
  78. func TestClientAuthPublicKey(t *testing.T) {
  79. config := &ClientConfig{
  80. User: "testuser",
  81. Auth: []AuthMethod{
  82. PublicKeys(testSigners["rsa"]),
  83. },
  84. }
  85. if err := tryAuth(t, config); err != nil {
  86. t.Fatalf("unable to dial remote side: %s", err)
  87. }
  88. }
  89. func TestAuthMethodPassword(t *testing.T) {
  90. config := &ClientConfig{
  91. User: "testuser",
  92. Auth: []AuthMethod{
  93. Password(clientPassword),
  94. },
  95. }
  96. if err := tryAuth(t, config); err != nil {
  97. t.Fatalf("unable to dial remote side: %s", err)
  98. }
  99. }
  100. func TestAuthMethodFallback(t *testing.T) {
  101. var passwordCalled bool
  102. config := &ClientConfig{
  103. User: "testuser",
  104. Auth: []AuthMethod{
  105. PublicKeys(testSigners["rsa"]),
  106. PasswordCallback(
  107. func() (string, error) {
  108. passwordCalled = true
  109. return "WRONG", nil
  110. }),
  111. },
  112. }
  113. if err := tryAuth(t, config); err != nil {
  114. t.Fatalf("unable to dial remote side: %s", err)
  115. }
  116. if passwordCalled {
  117. t.Errorf("password auth tried before public-key auth.")
  118. }
  119. }
  120. func TestAuthMethodWrongPassword(t *testing.T) {
  121. config := &ClientConfig{
  122. User: "testuser",
  123. Auth: []AuthMethod{
  124. Password("wrong"),
  125. PublicKeys(testSigners["rsa"]),
  126. },
  127. }
  128. if err := tryAuth(t, config); err != nil {
  129. t.Fatalf("unable to dial remote side: %s", err)
  130. }
  131. }
  132. func TestAuthMethodKeyboardInteractive(t *testing.T) {
  133. answers := keyboardInteractive(map[string]string{
  134. "question1": "answer1",
  135. "question2": "answer2",
  136. })
  137. config := &ClientConfig{
  138. User: "testuser",
  139. Auth: []AuthMethod{
  140. KeyboardInteractive(answers.Challenge),
  141. },
  142. }
  143. if err := tryAuth(t, config); err != nil {
  144. t.Fatalf("unable to dial remote side: %s", err)
  145. }
  146. }
  147. func TestAuthMethodWrongKeyboardInteractive(t *testing.T) {
  148. answers := keyboardInteractive(map[string]string{
  149. "question1": "answer1",
  150. "question2": "WRONG",
  151. })
  152. config := &ClientConfig{
  153. User: "testuser",
  154. Auth: []AuthMethod{
  155. KeyboardInteractive(answers.Challenge),
  156. },
  157. }
  158. if err := tryAuth(t, config); err == nil {
  159. t.Fatalf("wrong answers should not have authenticated with KeyboardInteractive")
  160. }
  161. }
  162. // the mock server will only authenticate ssh-rsa keys
  163. func TestAuthMethodInvalidPublicKey(t *testing.T) {
  164. config := &ClientConfig{
  165. User: "testuser",
  166. Auth: []AuthMethod{
  167. PublicKeys(testSigners["dsa"]),
  168. },
  169. }
  170. if err := tryAuth(t, config); err == nil {
  171. t.Fatalf("dsa private key should not have authenticated with rsa public key")
  172. }
  173. }
  174. // the client should authenticate with the second key
  175. func TestAuthMethodRSAandDSA(t *testing.T) {
  176. config := &ClientConfig{
  177. User: "testuser",
  178. Auth: []AuthMethod{
  179. PublicKeys(testSigners["dsa"], testSigners["rsa"]),
  180. },
  181. }
  182. if err := tryAuth(t, config); err != nil {
  183. t.Fatalf("client could not authenticate with rsa key: %v", err)
  184. }
  185. }
  186. func TestClientHMAC(t *testing.T) {
  187. for _, mac := range supportedMACs {
  188. config := &ClientConfig{
  189. User: "testuser",
  190. Auth: []AuthMethod{
  191. PublicKeys(testSigners["rsa"]),
  192. },
  193. Config: Config{
  194. MACs: []string{mac},
  195. },
  196. }
  197. if err := tryAuth(t, config); err != nil {
  198. t.Fatalf("client could not authenticate with mac algo %s: %v", mac, err)
  199. }
  200. }
  201. }
  202. // issue 4285.
  203. func TestClientUnsupportedCipher(t *testing.T) {
  204. config := &ClientConfig{
  205. User: "testuser",
  206. Auth: []AuthMethod{
  207. PublicKeys(),
  208. },
  209. Config: Config{
  210. Ciphers: []string{"aes128-cbc"}, // not currently supported
  211. },
  212. }
  213. if err := tryAuth(t, config); err == nil {
  214. t.Errorf("expected no ciphers in common")
  215. }
  216. }
  217. func TestClientUnsupportedKex(t *testing.T) {
  218. config := &ClientConfig{
  219. User: "testuser",
  220. Auth: []AuthMethod{
  221. PublicKeys(),
  222. },
  223. Config: Config{
  224. KeyExchanges: []string{"diffie-hellman-group-exchange-sha256"}, // not currently supported
  225. },
  226. }
  227. if err := tryAuth(t, config); err == nil || !strings.Contains(err.Error(), "common algorithm") {
  228. t.Errorf("got %v, expected 'common algorithm'", err)
  229. }
  230. }
  231. func TestClientLoginCert(t *testing.T) {
  232. cert := &Certificate{
  233. Key: testPublicKeys["rsa"],
  234. ValidBefore: CertTimeInfinity,
  235. CertType: UserCert,
  236. }
  237. cert.SignCert(rand.Reader, testSigners["ecdsa"])
  238. certSigner, err := NewCertSigner(cert, testSigners["rsa"])
  239. if err != nil {
  240. t.Fatalf("NewCertSigner: %v", err)
  241. }
  242. clientConfig := &ClientConfig{
  243. User: "user",
  244. }
  245. clientConfig.Auth = append(clientConfig.Auth, PublicKeys(certSigner))
  246. t.Log("should succeed")
  247. if err := tryAuth(t, clientConfig); err != nil {
  248. t.Errorf("cert login failed: %v", err)
  249. }
  250. t.Log("corrupted signature")
  251. cert.Signature.Blob[0]++
  252. if err := tryAuth(t, clientConfig); err == nil {
  253. t.Errorf("cert login passed with corrupted sig")
  254. }
  255. t.Log("revoked")
  256. cert.Serial = 666
  257. cert.SignCert(rand.Reader, testSigners["ecdsa"])
  258. if err := tryAuth(t, clientConfig); err == nil {
  259. t.Errorf("revoked cert login succeeded")
  260. }
  261. cert.Serial = 1
  262. t.Log("sign with wrong key")
  263. cert.SignCert(rand.Reader, testSigners["dsa"])
  264. if err := tryAuth(t, clientConfig); err == nil {
  265. t.Errorf("cert login passed with non-authoritive key")
  266. }
  267. t.Log("host cert")
  268. cert.CertType = HostCert
  269. cert.SignCert(rand.Reader, testSigners["ecdsa"])
  270. if err := tryAuth(t, clientConfig); err == nil {
  271. t.Errorf("cert login passed with wrong type")
  272. }
  273. cert.CertType = UserCert
  274. t.Log("principal specified")
  275. cert.ValidPrincipals = []string{"user"}
  276. cert.SignCert(rand.Reader, testSigners["ecdsa"])
  277. if err := tryAuth(t, clientConfig); err != nil {
  278. t.Errorf("cert login failed: %v", err)
  279. }
  280. t.Log("wrong principal specified")
  281. cert.ValidPrincipals = []string{"fred"}
  282. cert.SignCert(rand.Reader, testSigners["ecdsa"])
  283. if err := tryAuth(t, clientConfig); err == nil {
  284. t.Errorf("cert login passed with wrong principal")
  285. }
  286. cert.ValidPrincipals = nil
  287. t.Log("added critical option")
  288. cert.CriticalOptions = map[string]string{"root-access": "yes"}
  289. cert.SignCert(rand.Reader, testSigners["ecdsa"])
  290. if err := tryAuth(t, clientConfig); err == nil {
  291. t.Errorf("cert login passed with unrecognized critical option")
  292. }
  293. t.Log("allowed source address")
  294. cert.CriticalOptions = map[string]string{"source-address": "127.0.0.42/24"}
  295. cert.SignCert(rand.Reader, testSigners["ecdsa"])
  296. if err := tryAuth(t, clientConfig); err != nil {
  297. t.Errorf("cert login with source-address failed: %v", err)
  298. }
  299. t.Log("disallowed source address")
  300. cert.CriticalOptions = map[string]string{"source-address": "127.0.0.42"}
  301. cert.SignCert(rand.Reader, testSigners["ecdsa"])
  302. if err := tryAuth(t, clientConfig); err == nil {
  303. t.Errorf("cert login with source-address succeeded")
  304. }
  305. }
  306. func testPermissionsPassing(withPermissions bool, t *testing.T) {
  307. serverConfig := &ServerConfig{
  308. PublicKeyCallback: func(conn ConnMetadata, key PublicKey) (*Permissions, error) {
  309. if conn.User() == "nopermissions" {
  310. return nil, nil
  311. } else {
  312. return &Permissions{}, nil
  313. }
  314. },
  315. }
  316. serverConfig.AddHostKey(testSigners["rsa"])
  317. clientConfig := &ClientConfig{
  318. Auth: []AuthMethod{
  319. PublicKeys(testSigners["rsa"]),
  320. },
  321. }
  322. if withPermissions {
  323. clientConfig.User = "permissions"
  324. } else {
  325. clientConfig.User = "nopermissions"
  326. }
  327. c1, c2, err := netPipe()
  328. if err != nil {
  329. t.Fatalf("netPipe: %v", err)
  330. }
  331. defer c1.Close()
  332. defer c2.Close()
  333. go NewClientConn(c2, "", clientConfig)
  334. serverConn, err := newServer(c1, serverConfig)
  335. if err != nil {
  336. t.Fatal(err)
  337. }
  338. if p := serverConn.Permissions; (p != nil) != withPermissions {
  339. t.Fatalf("withPermissions is %t, but Permissions object is %#v", withPermissions, p)
  340. }
  341. }
  342. func TestPermissionsPassing(t *testing.T) {
  343. testPermissionsPassing(true, t)
  344. }
  345. func TestNoPermissionsPassing(t *testing.T) {
  346. testPermissionsPassing(false, t)
  347. }