certs_test.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. // Copyright 2013 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. "reflect"
  9. "testing"
  10. "time"
  11. )
  12. // Cert generated by ssh-keygen 6.0p1 Debian-4.
  13. // % ssh-keygen -s ca-key -I test user-key
  14. const exampleSSHCert = `ssh-rsa-cert-v01@openssh.com AAAAHHNzaC1yc2EtY2VydC12MDFAb3BlbnNzaC5jb20AAAAgb1srW/W3ZDjYAO45xLYAwzHBDLsJ4Ux6ICFIkTjb1LEAAAADAQABAAAAYQCkoR51poH0wE8w72cqSB8Sszx+vAhzcMdCO0wqHTj7UNENHWEXGrU0E0UQekD7U+yhkhtoyjbPOVIP7hNa6aRk/ezdh/iUnCIt4Jt1v3Z1h1P+hA4QuYFMHNB+rmjPwAcAAAAAAAAAAAAAAAEAAAAEdGVzdAAAAAAAAAAAAAAAAP//////////AAAAAAAAAIIAAAAVcGVybWl0LVgxMS1mb3J3YXJkaW5nAAAAAAAAABdwZXJtaXQtYWdlbnQtZm9yd2FyZGluZwAAAAAAAAAWcGVybWl0LXBvcnQtZm9yd2FyZGluZwAAAAAAAAAKcGVybWl0LXB0eQAAAAAAAAAOcGVybWl0LXVzZXItcmMAAAAAAAAAAAAAAHcAAAAHc3NoLXJzYQAAAAMBAAEAAABhANFS2kaktpSGc+CcmEKPyw9mJC4nZKxHKTgLVZeaGbFZOvJTNzBspQHdy7Q1uKSfktxpgjZnksiu/tFF9ngyY2KFoc+U88ya95IZUycBGCUbBQ8+bhDtw/icdDGQD5WnUwAAAG8AAAAHc3NoLXJzYQAAAGC8Y9Z2LQKhIhxf52773XaWrXdxP0t3GBVo4A10vUWiYoAGepr6rQIoGGXFxT4B9Gp+nEBJjOwKDXPrAevow0T9ca8gZN+0ykbhSrXLE5Ao48rqr3zP4O1/9P7e6gp0gw8=`
  15. func TestParseCert(t *testing.T) {
  16. authKeyBytes := []byte(exampleSSHCert)
  17. key, _, _, rest, err := ParseAuthorizedKey(authKeyBytes)
  18. if err != nil {
  19. t.Fatalf("ParseAuthorizedKey: %v", err)
  20. }
  21. if len(rest) > 0 {
  22. t.Errorf("rest: got %q, want empty", rest)
  23. }
  24. if _, ok := key.(*Certificate); !ok {
  25. t.Fatalf("got %v (%T), want *Certificate", key, key)
  26. }
  27. marshaled := MarshalAuthorizedKey(key)
  28. // Before comparison, remove the trailing newline that
  29. // MarshalAuthorizedKey adds.
  30. marshaled = marshaled[:len(marshaled)-1]
  31. if !bytes.Equal(authKeyBytes, marshaled) {
  32. t.Errorf("marshaled certificate does not match original: got %q, want %q", marshaled, authKeyBytes)
  33. }
  34. }
  35. // Cert generated by ssh-keygen OpenSSH_6.8p1 OS X 10.10.3
  36. // % ssh-keygen -s ca -I testcert -O source-address=192.168.1.0/24 -O force-command=/bin/sleep user.pub
  37. // user.pub key: ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDACh1rt2DXfV3hk6fszSQcQ/rueMId0kVD9U7nl8cfEnFxqOCrNT92g4laQIGl2mn8lsGZfTLg8ksHq3gkvgO3oo/0wHy4v32JeBOHTsN5AL4gfHNEhWeWb50ev47hnTsRIt9P4dxogeUo/hTu7j9+s9lLpEQXCvq6xocXQt0j8MV9qZBBXFLXVT3cWIkSqOdwt/5ZBg+1GSrc7WfCXVWgTk4a20uPMuJPxU4RQwZW6X3+O8Pqo8C3cW0OzZRFP6gUYUKUsTI5WntlS+LAxgw1mZNsozFGdbiOPRnEryE3SRldh9vjDR3tin1fGpA5P7+CEB/bqaXtG3V+F2OkqaMN
  38. // Critical Options:
  39. // force-command /bin/sleep
  40. // source-address 192.168.1.0/24
  41. // Extensions:
  42. // permit-X11-forwarding
  43. // permit-agent-forwarding
  44. // permit-port-forwarding
  45. // permit-pty
  46. // permit-user-rc
  47. const exampleSSHCertWithOptions = `ssh-rsa-cert-v01@openssh.com AAAAHHNzaC1yc2EtY2VydC12MDFAb3BlbnNzaC5jb20AAAAgDyysCJY0XrO1n03EeRRoITnTPdjENFmWDs9X58PP3VUAAAADAQABAAABAQDACh1rt2DXfV3hk6fszSQcQ/rueMId0kVD9U7nl8cfEnFxqOCrNT92g4laQIGl2mn8lsGZfTLg8ksHq3gkvgO3oo/0wHy4v32JeBOHTsN5AL4gfHNEhWeWb50ev47hnTsRIt9P4dxogeUo/hTu7j9+s9lLpEQXCvq6xocXQt0j8MV9qZBBXFLXVT3cWIkSqOdwt/5ZBg+1GSrc7WfCXVWgTk4a20uPMuJPxU4RQwZW6X3+O8Pqo8C3cW0OzZRFP6gUYUKUsTI5WntlS+LAxgw1mZNsozFGdbiOPRnEryE3SRldh9vjDR3tin1fGpA5P7+CEB/bqaXtG3V+F2OkqaMNAAAAAAAAAAAAAAABAAAACHRlc3RjZXJ0AAAAAAAAAAAAAAAA//////////8AAABLAAAADWZvcmNlLWNvbW1hbmQAAAAOAAAACi9iaW4vc2xlZXAAAAAOc291cmNlLWFkZHJlc3MAAAASAAAADjE5Mi4xNjguMS4wLzI0AAAAggAAABVwZXJtaXQtWDExLWZvcndhcmRpbmcAAAAAAAAAF3Blcm1pdC1hZ2VudC1mb3J3YXJkaW5nAAAAAAAAABZwZXJtaXQtcG9ydC1mb3J3YXJkaW5nAAAAAAAAAApwZXJtaXQtcHR5AAAAAAAAAA5wZXJtaXQtdXNlci1yYwAAAAAAAAAAAAABFwAAAAdzc2gtcnNhAAAAAwEAAQAAAQEAwU+c5ui5A8+J/CFpjW8wCa52bEODA808WWQDCSuTG/eMXNf59v9Y8Pk0F1E9dGCosSNyVcB/hacUrc6He+i97+HJCyKavBsE6GDxrjRyxYqAlfcOXi/IVmaUGiO8OQ39d4GHrjToInKvExSUeleQyH4Y4/e27T/pILAqPFL3fyrvMLT5qU9QyIt6zIpa7GBP5+urouNavMprV3zsfIqNBbWypinOQAw823a5wN+zwXnhZrgQiHZ/USG09Y6k98y1dTVz8YHlQVR4D3lpTAsKDKJ5hCH9WU4fdf+lU8OyNGaJ/vz0XNqxcToe1l4numLTnaoSuH89pHryjqurB7lJKwAAAQ8AAAAHc3NoLXJzYQAAAQCaHvUIoPL1zWUHIXLvu96/HU1s/i4CAW2IIEuGgxCUCiFj6vyTyYtgxQxcmbfZf6eaITlS6XJZa7Qq4iaFZh75C1DXTX8labXhRSD4E2t//AIP9MC1rtQC5xo6FmbQ+BoKcDskr+mNACcbRSxs3IL3bwCfWDnIw2WbVox9ZdcthJKk4UoCW4ix4QwdHw7zlddlz++fGEEVhmTbll1SUkycGApPFBsAYRTMupUJcYPIeReBI/m8XfkoMk99bV8ZJQTAd7OekHY2/48Ff53jLmyDjP7kNw1F8OaPtkFs6dGJXta4krmaekPy87j+35In5hFj7yoOqvSbmYUkeX70/GGQ`
  48. func TestParseCertWithOptions(t *testing.T) {
  49. opts := map[string]string{
  50. "source-address": "192.168.1.0/24",
  51. "force-command": "/bin/sleep",
  52. }
  53. exts := map[string]string{
  54. "permit-X11-forwarding": "",
  55. "permit-agent-forwarding": "",
  56. "permit-port-forwarding": "",
  57. "permit-pty": "",
  58. "permit-user-rc": "",
  59. }
  60. authKeyBytes := []byte(exampleSSHCertWithOptions)
  61. key, _, _, rest, err := ParseAuthorizedKey(authKeyBytes)
  62. if err != nil {
  63. t.Fatalf("ParseAuthorizedKey: %v", err)
  64. }
  65. if len(rest) > 0 {
  66. t.Errorf("rest: got %q, want empty", rest)
  67. }
  68. cert, ok := key.(*Certificate)
  69. if !ok {
  70. t.Fatalf("got %v (%T), want *Certificate", key, key)
  71. }
  72. if !reflect.DeepEqual(cert.CriticalOptions, opts) {
  73. t.Errorf("unexpected critical options - got %v, want %v", cert.CriticalOptions, opts)
  74. }
  75. if !reflect.DeepEqual(cert.Extensions, exts) {
  76. t.Errorf("unexpected Extensions - got %v, want %v", cert.Extensions, exts)
  77. }
  78. marshaled := MarshalAuthorizedKey(key)
  79. // Before comparison, remove the trailing newline that
  80. // MarshalAuthorizedKey adds.
  81. marshaled = marshaled[:len(marshaled)-1]
  82. if !bytes.Equal(authKeyBytes, marshaled) {
  83. t.Errorf("marshaled certificate does not match original: got %q, want %q", marshaled, authKeyBytes)
  84. }
  85. }
  86. func TestValidateCert(t *testing.T) {
  87. key, _, _, _, err := ParseAuthorizedKey([]byte(exampleSSHCert))
  88. if err != nil {
  89. t.Fatalf("ParseAuthorizedKey: %v", err)
  90. }
  91. validCert, ok := key.(*Certificate)
  92. if !ok {
  93. t.Fatalf("got %v (%T), want *Certificate", key, key)
  94. }
  95. checker := CertChecker{}
  96. checker.IsUserAuthority = func(k PublicKey) bool {
  97. return bytes.Equal(k.Marshal(), validCert.SignatureKey.Marshal())
  98. }
  99. if err := checker.CheckCert("user", validCert); err != nil {
  100. t.Errorf("Unable to validate certificate: %v", err)
  101. }
  102. invalidCert := &Certificate{
  103. Key: testPublicKeys["rsa"],
  104. SignatureKey: testPublicKeys["ecdsa"],
  105. ValidBefore: CertTimeInfinity,
  106. Signature: &Signature{},
  107. }
  108. if err := checker.CheckCert("user", invalidCert); err == nil {
  109. t.Error("Invalid cert signature passed validation")
  110. }
  111. }
  112. func TestValidateCertTime(t *testing.T) {
  113. cert := Certificate{
  114. ValidPrincipals: []string{"user"},
  115. Key: testPublicKeys["rsa"],
  116. ValidAfter: 50,
  117. ValidBefore: 100,
  118. }
  119. cert.SignCert(rand.Reader, testSigners["ecdsa"])
  120. for ts, ok := range map[int64]bool{
  121. 25: false,
  122. 50: true,
  123. 99: true,
  124. 100: false,
  125. 125: false,
  126. } {
  127. checker := CertChecker{
  128. Clock: func() time.Time { return time.Unix(ts, 0) },
  129. }
  130. checker.IsUserAuthority = func(k PublicKey) bool {
  131. return bytes.Equal(k.Marshal(),
  132. testPublicKeys["ecdsa"].Marshal())
  133. }
  134. if v := checker.CheckCert("user", &cert); (v == nil) != ok {
  135. t.Errorf("Authenticate(%d): %v", ts, v)
  136. }
  137. }
  138. }
  139. // TODO(hanwen): tests for
  140. //
  141. // host keys:
  142. // * fallbacks
  143. func TestHostKeyCert(t *testing.T) {
  144. cert := &Certificate{
  145. ValidPrincipals: []string{"hostname", "hostname.domain", "otherhost"},
  146. Key: testPublicKeys["rsa"],
  147. ValidBefore: CertTimeInfinity,
  148. CertType: HostCert,
  149. }
  150. cert.SignCert(rand.Reader, testSigners["ecdsa"])
  151. checker := &CertChecker{
  152. IsHostAuthority: func(p PublicKey, addr string) bool {
  153. return addr == "hostname:22" && bytes.Equal(testPublicKeys["ecdsa"].Marshal(), p.Marshal())
  154. },
  155. }
  156. certSigner, err := NewCertSigner(cert, testSigners["rsa"])
  157. if err != nil {
  158. t.Errorf("NewCertSigner: %v", err)
  159. }
  160. for _, test := range []struct {
  161. addr string
  162. succeed bool
  163. }{
  164. {addr: "hostname:22", succeed: true},
  165. {addr: "otherhost:22", succeed: false}, // The certificate is valid for 'otherhost' as hostname, but we only recognize the authority of the signer for the address 'hostname:22'
  166. {addr: "lasthost:22", succeed: false},
  167. } {
  168. c1, c2, err := netPipe()
  169. if err != nil {
  170. t.Fatalf("netPipe: %v", err)
  171. }
  172. defer c1.Close()
  173. defer c2.Close()
  174. errc := make(chan error)
  175. go func() {
  176. conf := ServerConfig{
  177. NoClientAuth: true,
  178. }
  179. conf.AddHostKey(certSigner)
  180. _, _, _, err := NewServerConn(c1, &conf)
  181. errc <- err
  182. }()
  183. config := &ClientConfig{
  184. User: "user",
  185. HostKeyCallback: checker.CheckHostKey,
  186. }
  187. _, _, _, err = NewClientConn(c2, test.addr, config)
  188. if (err == nil) != test.succeed {
  189. t.Fatalf("NewClientConn(%q): %v", test.addr, err)
  190. }
  191. err = <-errc
  192. if (err == nil) != test.succeed {
  193. t.Fatalf("NewServerConn(%q): %v", test.addr, err)
  194. }
  195. }
  196. }