cert_test.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Copyright 2014 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. // +build darwin dragonfly freebsd linux netbsd openbsd
  5. package test
  6. import (
  7. "bytes"
  8. "crypto/rand"
  9. "testing"
  10. "golang.org/x/crypto/ssh"
  11. )
  12. // Test both logging in with a cert, and also that the certificate presented by an OpenSSH host can be validated correctly
  13. func TestCertLogin(t *testing.T) {
  14. s := newServer(t)
  15. defer s.Shutdown()
  16. // Use a key different from the default.
  17. clientKey := testSigners["dsa"]
  18. caAuthKey := testSigners["ecdsa"]
  19. cert := &ssh.Certificate{
  20. Key: clientKey.PublicKey(),
  21. ValidPrincipals: []string{username()},
  22. CertType: ssh.UserCert,
  23. ValidBefore: ssh.CertTimeInfinity,
  24. }
  25. if err := cert.SignCert(rand.Reader, caAuthKey); err != nil {
  26. t.Fatalf("SetSignature: %v", err)
  27. }
  28. certSigner, err := ssh.NewCertSigner(cert, clientKey)
  29. if err != nil {
  30. t.Fatalf("NewCertSigner: %v", err)
  31. }
  32. conf := &ssh.ClientConfig{
  33. User: username(),
  34. HostKeyCallback: (&ssh.CertChecker{
  35. IsHostAuthority: func(pk ssh.PublicKey, addr string) bool {
  36. return bytes.Equal(pk.Marshal(), testPublicKeys["ca"].Marshal())
  37. },
  38. }).CheckHostKey,
  39. }
  40. conf.Auth = append(conf.Auth, ssh.PublicKeys(certSigner))
  41. for _, test := range []struct {
  42. addr string
  43. succeed bool
  44. }{
  45. {addr: "host.example.com:22", succeed: true},
  46. {addr: "host.example.com:10000", succeed: true}, // non-standard port must be OK
  47. {addr: "host.example.com", succeed: false}, // port must be specified
  48. {addr: "host.ex4mple.com:22", succeed: false}, // wrong host
  49. } {
  50. client, err := s.TryDialWithAddr(conf, test.addr)
  51. // Always close client if opened successfully
  52. if err == nil {
  53. client.Close()
  54. }
  55. // Now evaluate whether the test failed or passed
  56. if test.succeed {
  57. if err != nil {
  58. t.Fatalf("TryDialWithAddr: %v", err)
  59. }
  60. } else {
  61. if err == nil {
  62. t.Fatalf("TryDialWithAddr, unexpected success")
  63. }
  64. }
  65. }
  66. }