client_auth_test.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  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. "os"
  11. "strings"
  12. "testing"
  13. )
  14. type keyboardInteractive map[string]string
  15. func (cr keyboardInteractive) Challenge(user string, instruction string, questions []string, echos []bool) ([]string, error) {
  16. var answers []string
  17. for _, q := range questions {
  18. answers = append(answers, cr[q])
  19. }
  20. return answers, nil
  21. }
  22. // reused internally by tests
  23. var clientPassword = "tiger"
  24. // tryAuth runs a handshake with a given config against an SSH server
  25. // with config serverConfig
  26. func tryAuth(t *testing.T, config *ClientConfig) error {
  27. c1, c2, err := netPipe()
  28. if err != nil {
  29. t.Fatalf("netPipe: %v", err)
  30. }
  31. defer c1.Close()
  32. defer c2.Close()
  33. certChecker := CertChecker{
  34. IsUserAuthority: func(k PublicKey) bool {
  35. return bytes.Equal(k.Marshal(), testPublicKeys["ecdsa"].Marshal())
  36. },
  37. UserKeyFallback: func(conn ConnMetadata, key PublicKey) (*Permissions, error) {
  38. if conn.User() == "testuser" && bytes.Equal(key.Marshal(), testPublicKeys["rsa"].Marshal()) {
  39. return nil, nil
  40. }
  41. return nil, fmt.Errorf("pubkey for %q not acceptable", conn.User())
  42. },
  43. IsRevoked: func(c *Certificate) bool {
  44. return c.Serial == 666
  45. },
  46. }
  47. serverConfig := &ServerConfig{
  48. PasswordCallback: func(conn ConnMetadata, pass []byte) (*Permissions, error) {
  49. if conn.User() == "testuser" && string(pass) == clientPassword {
  50. return nil, nil
  51. }
  52. return nil, errors.New("password auth failed")
  53. },
  54. PublicKeyCallback: certChecker.Authenticate,
  55. KeyboardInteractiveCallback: func(conn ConnMetadata, challenge KeyboardInteractiveChallenge) (*Permissions, error) {
  56. ans, err := challenge("user",
  57. "instruction",
  58. []string{"question1", "question2"},
  59. []bool{true, true})
  60. if err != nil {
  61. return nil, err
  62. }
  63. ok := conn.User() == "testuser" && ans[0] == "answer1" && ans[1] == "answer2"
  64. if ok {
  65. challenge("user", "motd", nil, nil)
  66. return nil, nil
  67. }
  68. return nil, errors.New("keyboard-interactive failed")
  69. },
  70. }
  71. serverConfig.AddHostKey(testSigners["rsa"])
  72. go newServer(c1, serverConfig)
  73. _, _, _, err = NewClientConn(c2, "", config)
  74. return err
  75. }
  76. func TestClientAuthPublicKey(t *testing.T) {
  77. config := &ClientConfig{
  78. User: "testuser",
  79. Auth: []AuthMethod{
  80. PublicKeys(testSigners["rsa"]),
  81. },
  82. HostKeyCallback: InsecureIgnoreHostKey(),
  83. }
  84. if err := tryAuth(t, config); err != nil {
  85. t.Fatalf("unable to dial remote side: %s", err)
  86. }
  87. }
  88. func TestAuthMethodPassword(t *testing.T) {
  89. config := &ClientConfig{
  90. User: "testuser",
  91. Auth: []AuthMethod{
  92. Password(clientPassword),
  93. },
  94. HostKeyCallback: InsecureIgnoreHostKey(),
  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. HostKeyCallback: InsecureIgnoreHostKey(),
  113. }
  114. if err := tryAuth(t, config); err != nil {
  115. t.Fatalf("unable to dial remote side: %s", err)
  116. }
  117. if passwordCalled {
  118. t.Errorf("password auth tried before public-key auth.")
  119. }
  120. }
  121. func TestAuthMethodWrongPassword(t *testing.T) {
  122. config := &ClientConfig{
  123. User: "testuser",
  124. Auth: []AuthMethod{
  125. Password("wrong"),
  126. PublicKeys(testSigners["rsa"]),
  127. },
  128. HostKeyCallback: InsecureIgnoreHostKey(),
  129. }
  130. if err := tryAuth(t, config); err != nil {
  131. t.Fatalf("unable to dial remote side: %s", err)
  132. }
  133. }
  134. func TestAuthMethodKeyboardInteractive(t *testing.T) {
  135. answers := keyboardInteractive(map[string]string{
  136. "question1": "answer1",
  137. "question2": "answer2",
  138. })
  139. config := &ClientConfig{
  140. User: "testuser",
  141. Auth: []AuthMethod{
  142. KeyboardInteractive(answers.Challenge),
  143. },
  144. HostKeyCallback: InsecureIgnoreHostKey(),
  145. }
  146. if err := tryAuth(t, config); err != nil {
  147. t.Fatalf("unable to dial remote side: %s", err)
  148. }
  149. }
  150. func TestAuthMethodWrongKeyboardInteractive(t *testing.T) {
  151. answers := keyboardInteractive(map[string]string{
  152. "question1": "answer1",
  153. "question2": "WRONG",
  154. })
  155. config := &ClientConfig{
  156. User: "testuser",
  157. Auth: []AuthMethod{
  158. KeyboardInteractive(answers.Challenge),
  159. },
  160. }
  161. if err := tryAuth(t, config); err == nil {
  162. t.Fatalf("wrong answers should not have authenticated with KeyboardInteractive")
  163. }
  164. }
  165. // the mock server will only authenticate ssh-rsa keys
  166. func TestAuthMethodInvalidPublicKey(t *testing.T) {
  167. config := &ClientConfig{
  168. User: "testuser",
  169. Auth: []AuthMethod{
  170. PublicKeys(testSigners["dsa"]),
  171. },
  172. }
  173. if err := tryAuth(t, config); err == nil {
  174. t.Fatalf("dsa private key should not have authenticated with rsa public key")
  175. }
  176. }
  177. // the client should authenticate with the second key
  178. func TestAuthMethodRSAandDSA(t *testing.T) {
  179. config := &ClientConfig{
  180. User: "testuser",
  181. Auth: []AuthMethod{
  182. PublicKeys(testSigners["dsa"], testSigners["rsa"]),
  183. },
  184. HostKeyCallback: InsecureIgnoreHostKey(),
  185. }
  186. if err := tryAuth(t, config); err != nil {
  187. t.Fatalf("client could not authenticate with rsa key: %v", err)
  188. }
  189. }
  190. func TestClientHMAC(t *testing.T) {
  191. for _, mac := range supportedMACs {
  192. config := &ClientConfig{
  193. User: "testuser",
  194. Auth: []AuthMethod{
  195. PublicKeys(testSigners["rsa"]),
  196. },
  197. Config: Config{
  198. MACs: []string{mac},
  199. },
  200. HostKeyCallback: InsecureIgnoreHostKey(),
  201. }
  202. if err := tryAuth(t, config); err != nil {
  203. t.Fatalf("client could not authenticate with mac algo %s: %v", mac, err)
  204. }
  205. }
  206. }
  207. // issue 4285.
  208. func TestClientUnsupportedCipher(t *testing.T) {
  209. config := &ClientConfig{
  210. User: "testuser",
  211. Auth: []AuthMethod{
  212. PublicKeys(),
  213. },
  214. Config: Config{
  215. Ciphers: []string{"aes128-cbc"}, // not currently supported
  216. },
  217. }
  218. if err := tryAuth(t, config); err == nil {
  219. t.Errorf("expected no ciphers in common")
  220. }
  221. }
  222. func TestClientUnsupportedKex(t *testing.T) {
  223. if os.Getenv("GO_BUILDER_NAME") != "" {
  224. t.Skip("skipping known-flaky test on the Go build dashboard; see golang.org/issue/15198")
  225. }
  226. config := &ClientConfig{
  227. User: "testuser",
  228. Auth: []AuthMethod{
  229. PublicKeys(),
  230. },
  231. Config: Config{
  232. KeyExchanges: []string{"diffie-hellman-group-exchange-sha256"}, // not currently supported
  233. },
  234. HostKeyCallback: InsecureIgnoreHostKey(),
  235. }
  236. if err := tryAuth(t, config); err == nil || !strings.Contains(err.Error(), "common algorithm") {
  237. t.Errorf("got %v, expected 'common algorithm'", err)
  238. }
  239. }
  240. func TestClientLoginCert(t *testing.T) {
  241. cert := &Certificate{
  242. Key: testPublicKeys["rsa"],
  243. ValidBefore: CertTimeInfinity,
  244. CertType: UserCert,
  245. }
  246. cert.SignCert(rand.Reader, testSigners["ecdsa"])
  247. certSigner, err := NewCertSigner(cert, testSigners["rsa"])
  248. if err != nil {
  249. t.Fatalf("NewCertSigner: %v", err)
  250. }
  251. clientConfig := &ClientConfig{
  252. User: "user",
  253. HostKeyCallback: InsecureIgnoreHostKey(),
  254. }
  255. clientConfig.Auth = append(clientConfig.Auth, PublicKeys(certSigner))
  256. // should succeed
  257. if err := tryAuth(t, clientConfig); err != nil {
  258. t.Errorf("cert login failed: %v", err)
  259. }
  260. // corrupted signature
  261. cert.Signature.Blob[0]++
  262. if err := tryAuth(t, clientConfig); err == nil {
  263. t.Errorf("cert login passed with corrupted sig")
  264. }
  265. // revoked
  266. cert.Serial = 666
  267. cert.SignCert(rand.Reader, testSigners["ecdsa"])
  268. if err := tryAuth(t, clientConfig); err == nil {
  269. t.Errorf("revoked cert login succeeded")
  270. }
  271. cert.Serial = 1
  272. // sign with wrong key
  273. cert.SignCert(rand.Reader, testSigners["dsa"])
  274. if err := tryAuth(t, clientConfig); err == nil {
  275. t.Errorf("cert login passed with non-authoritative key")
  276. }
  277. // host cert
  278. cert.CertType = HostCert
  279. cert.SignCert(rand.Reader, testSigners["ecdsa"])
  280. if err := tryAuth(t, clientConfig); err == nil {
  281. t.Errorf("cert login passed with wrong type")
  282. }
  283. cert.CertType = UserCert
  284. // principal specified
  285. cert.ValidPrincipals = []string{"user"}
  286. cert.SignCert(rand.Reader, testSigners["ecdsa"])
  287. if err := tryAuth(t, clientConfig); err != nil {
  288. t.Errorf("cert login failed: %v", err)
  289. }
  290. // wrong principal specified
  291. cert.ValidPrincipals = []string{"fred"}
  292. cert.SignCert(rand.Reader, testSigners["ecdsa"])
  293. if err := tryAuth(t, clientConfig); err == nil {
  294. t.Errorf("cert login passed with wrong principal")
  295. }
  296. cert.ValidPrincipals = nil
  297. // added critical option
  298. cert.CriticalOptions = map[string]string{"root-access": "yes"}
  299. cert.SignCert(rand.Reader, testSigners["ecdsa"])
  300. if err := tryAuth(t, clientConfig); err == nil {
  301. t.Errorf("cert login passed with unrecognized critical option")
  302. }
  303. // allowed source address
  304. cert.CriticalOptions = map[string]string{"source-address": "127.0.0.42/24,::42/120"}
  305. cert.SignCert(rand.Reader, testSigners["ecdsa"])
  306. if err := tryAuth(t, clientConfig); err != nil {
  307. t.Errorf("cert login with source-address failed: %v", err)
  308. }
  309. // disallowed source address
  310. cert.CriticalOptions = map[string]string{"source-address": "127.0.0.42,::42"}
  311. cert.SignCert(rand.Reader, testSigners["ecdsa"])
  312. if err := tryAuth(t, clientConfig); err == nil {
  313. t.Errorf("cert login with source-address succeeded")
  314. }
  315. }
  316. func testPermissionsPassing(withPermissions bool, t *testing.T) {
  317. serverConfig := &ServerConfig{
  318. PublicKeyCallback: func(conn ConnMetadata, key PublicKey) (*Permissions, error) {
  319. if conn.User() == "nopermissions" {
  320. return nil, nil
  321. } else {
  322. return &Permissions{}, nil
  323. }
  324. },
  325. }
  326. serverConfig.AddHostKey(testSigners["rsa"])
  327. clientConfig := &ClientConfig{
  328. Auth: []AuthMethod{
  329. PublicKeys(testSigners["rsa"]),
  330. },
  331. HostKeyCallback: InsecureIgnoreHostKey(),
  332. }
  333. if withPermissions {
  334. clientConfig.User = "permissions"
  335. } else {
  336. clientConfig.User = "nopermissions"
  337. }
  338. c1, c2, err := netPipe()
  339. if err != nil {
  340. t.Fatalf("netPipe: %v", err)
  341. }
  342. defer c1.Close()
  343. defer c2.Close()
  344. go NewClientConn(c2, "", clientConfig)
  345. serverConn, err := newServer(c1, serverConfig)
  346. if err != nil {
  347. t.Fatal(err)
  348. }
  349. if p := serverConn.Permissions; (p != nil) != withPermissions {
  350. t.Fatalf("withPermissions is %t, but Permissions object is %#v", withPermissions, p)
  351. }
  352. }
  353. func TestPermissionsPassing(t *testing.T) {
  354. testPermissionsPassing(true, t)
  355. }
  356. func TestNoPermissionsPassing(t *testing.T) {
  357. testPermissionsPassing(false, t)
  358. }
  359. func TestRetryableAuth(t *testing.T) {
  360. n := 0
  361. passwords := []string{"WRONG1", "WRONG2"}
  362. config := &ClientConfig{
  363. User: "testuser",
  364. Auth: []AuthMethod{
  365. RetryableAuthMethod(PasswordCallback(func() (string, error) {
  366. p := passwords[n]
  367. n++
  368. return p, nil
  369. }), 2),
  370. PublicKeys(testSigners["rsa"]),
  371. },
  372. HostKeyCallback: InsecureIgnoreHostKey(),
  373. }
  374. if err := tryAuth(t, config); err != nil {
  375. t.Fatalf("unable to dial remote side: %s", err)
  376. }
  377. if n != 2 {
  378. t.Fatalf("Did not try all passwords")
  379. }
  380. }
  381. func ExampleRetryableAuthMethod(t *testing.T) {
  382. user := "testuser"
  383. NumberOfPrompts := 3
  384. // Normally this would be a callback that prompts the user to answer the
  385. // provided questions
  386. Cb := func(user, instruction string, questions []string, echos []bool) (answers []string, err error) {
  387. return []string{"answer1", "answer2"}, nil
  388. }
  389. config := &ClientConfig{
  390. HostKeyCallback: InsecureIgnoreHostKey(),
  391. User: user,
  392. Auth: []AuthMethod{
  393. RetryableAuthMethod(KeyboardInteractiveChallenge(Cb), NumberOfPrompts),
  394. },
  395. }
  396. if err := tryAuth(t, config); err != nil {
  397. t.Fatalf("unable to dial remote side: %s", err)
  398. }
  399. }
  400. // Test if username is received on server side when NoClientAuth is used
  401. func TestClientAuthNone(t *testing.T) {
  402. user := "testuser"
  403. serverConfig := &ServerConfig{
  404. NoClientAuth: true,
  405. }
  406. serverConfig.AddHostKey(testSigners["rsa"])
  407. clientConfig := &ClientConfig{
  408. User: user,
  409. HostKeyCallback: InsecureIgnoreHostKey(),
  410. }
  411. c1, c2, err := netPipe()
  412. if err != nil {
  413. t.Fatalf("netPipe: %v", err)
  414. }
  415. defer c1.Close()
  416. defer c2.Close()
  417. go NewClientConn(c2, "", clientConfig)
  418. serverConn, err := newServer(c1, serverConfig)
  419. if err != nil {
  420. t.Fatalf("newServer: %v", err)
  421. }
  422. if serverConn.User() != user {
  423. t.Fatalf("server: got %q, want %q", serverConn.User(), user)
  424. }
  425. }
  426. // Test if authentication attempts are limited on server when MaxAuthTries is set
  427. func TestClientAuthMaxAuthTries(t *testing.T) {
  428. user := "testuser"
  429. serverConfig := &ServerConfig{
  430. MaxAuthTries: 2,
  431. PasswordCallback: func(conn ConnMetadata, pass []byte) (*Permissions, error) {
  432. if conn.User() == "testuser" && string(pass) == "right" {
  433. return nil, nil
  434. }
  435. return nil, errors.New("password auth failed")
  436. },
  437. }
  438. serverConfig.AddHostKey(testSigners["rsa"])
  439. expectedErr := fmt.Errorf("ssh: handshake failed: %v", &disconnectMsg{
  440. Reason: 2,
  441. Message: "too many authentication failures",
  442. })
  443. for tries := 2; tries < 4; tries++ {
  444. n := tries
  445. clientConfig := &ClientConfig{
  446. User: user,
  447. Auth: []AuthMethod{
  448. RetryableAuthMethod(PasswordCallback(func() (string, error) {
  449. n--
  450. if n == 0 {
  451. return "right", nil
  452. } else {
  453. return "wrong", nil
  454. }
  455. }), tries),
  456. },
  457. HostKeyCallback: InsecureIgnoreHostKey(),
  458. }
  459. c1, c2, err := netPipe()
  460. if err != nil {
  461. t.Fatalf("netPipe: %v", err)
  462. }
  463. defer c1.Close()
  464. defer c2.Close()
  465. go newServer(c1, serverConfig)
  466. _, _, _, err = NewClientConn(c2, "", clientConfig)
  467. if tries > 2 {
  468. if err == nil {
  469. t.Fatalf("client: got no error, want %s", expectedErr)
  470. } else if err.Error() != expectedErr.Error() {
  471. t.Fatalf("client: got %s, want %s", err, expectedErr)
  472. }
  473. } else {
  474. if err != nil {
  475. t.Fatalf("client: got %s, want no error", err)
  476. }
  477. }
  478. }
  479. }
  480. // Test if authentication attempts are correctly limited on server
  481. // when more public keys are provided then MaxAuthTries
  482. func TestClientAuthMaxAuthTriesPublicKey(t *testing.T) {
  483. signers := []Signer{}
  484. for i := 0; i < 6; i++ {
  485. signers = append(signers, testSigners["dsa"])
  486. }
  487. validConfig := &ClientConfig{
  488. User: "testuser",
  489. Auth: []AuthMethod{
  490. PublicKeys(append([]Signer{testSigners["rsa"]}, signers...)...),
  491. },
  492. HostKeyCallback: InsecureIgnoreHostKey(),
  493. }
  494. if err := tryAuth(t, validConfig); err != nil {
  495. t.Fatalf("unable to dial remote side: %s", err)
  496. }
  497. expectedErr := fmt.Errorf("ssh: handshake failed: %v", &disconnectMsg{
  498. Reason: 2,
  499. Message: "too many authentication failures",
  500. })
  501. invalidConfig := &ClientConfig{
  502. User: "testuser",
  503. Auth: []AuthMethod{
  504. PublicKeys(append(signers, testSigners["rsa"])...),
  505. },
  506. HostKeyCallback: InsecureIgnoreHostKey(),
  507. }
  508. if err := tryAuth(t, invalidConfig); err == nil {
  509. t.Fatalf("client: got no error, want %s", expectedErr)
  510. } else if err.Error() != expectedErr.Error() {
  511. t.Fatalf("client: got %s, want %s", err, expectedErr)
  512. }
  513. }