certs_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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/ecdsa"
  8. "crypto/elliptic"
  9. "crypto/rand"
  10. "net"
  11. "reflect"
  12. "testing"
  13. "time"
  14. "golang.org/x/crypto/ssh/testdata"
  15. )
  16. // Cert generated by ssh-keygen 6.0p1 Debian-4.
  17. // % ssh-keygen -s ca-key -I test user-key
  18. 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=`
  19. func TestParseCert(t *testing.T) {
  20. authKeyBytes := []byte(exampleSSHCert)
  21. key, _, _, rest, err := ParseAuthorizedKey(authKeyBytes)
  22. if err != nil {
  23. t.Fatalf("ParseAuthorizedKey: %v", err)
  24. }
  25. if len(rest) > 0 {
  26. t.Errorf("rest: got %q, want empty", rest)
  27. }
  28. if _, ok := key.(*Certificate); !ok {
  29. t.Fatalf("got %v (%T), want *Certificate", key, key)
  30. }
  31. marshaled := MarshalAuthorizedKey(key)
  32. // Before comparison, remove the trailing newline that
  33. // MarshalAuthorizedKey adds.
  34. marshaled = marshaled[:len(marshaled)-1]
  35. if !bytes.Equal(authKeyBytes, marshaled) {
  36. t.Errorf("marshaled certificate does not match original: got %q, want %q", marshaled, authKeyBytes)
  37. }
  38. }
  39. // Cert generated by ssh-keygen OpenSSH_6.8p1 OS X 10.10.3
  40. // % ssh-keygen -s ca -I testcert -O source-address=192.168.1.0/24 -O force-command=/bin/sleep user.pub
  41. // user.pub key: ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDACh1rt2DXfV3hk6fszSQcQ/rueMId0kVD9U7nl8cfEnFxqOCrNT92g4laQIGl2mn8lsGZfTLg8ksHq3gkvgO3oo/0wHy4v32JeBOHTsN5AL4gfHNEhWeWb50ev47hnTsRIt9P4dxogeUo/hTu7j9+s9lLpEQXCvq6xocXQt0j8MV9qZBBXFLXVT3cWIkSqOdwt/5ZBg+1GSrc7WfCXVWgTk4a20uPMuJPxU4RQwZW6X3+O8Pqo8C3cW0OzZRFP6gUYUKUsTI5WntlS+LAxgw1mZNsozFGdbiOPRnEryE3SRldh9vjDR3tin1fGpA5P7+CEB/bqaXtG3V+F2OkqaMN
  42. // Critical Options:
  43. // force-command /bin/sleep
  44. // source-address 192.168.1.0/24
  45. // Extensions:
  46. // permit-X11-forwarding
  47. // permit-agent-forwarding
  48. // permit-port-forwarding
  49. // permit-pty
  50. // permit-user-rc
  51. 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`
  52. func TestParseCertWithOptions(t *testing.T) {
  53. opts := map[string]string{
  54. "source-address": "192.168.1.0/24",
  55. "force-command": "/bin/sleep",
  56. }
  57. exts := map[string]string{
  58. "permit-X11-forwarding": "",
  59. "permit-agent-forwarding": "",
  60. "permit-port-forwarding": "",
  61. "permit-pty": "",
  62. "permit-user-rc": "",
  63. }
  64. authKeyBytes := []byte(exampleSSHCertWithOptions)
  65. key, _, _, rest, err := ParseAuthorizedKey(authKeyBytes)
  66. if err != nil {
  67. t.Fatalf("ParseAuthorizedKey: %v", err)
  68. }
  69. if len(rest) > 0 {
  70. t.Errorf("rest: got %q, want empty", rest)
  71. }
  72. cert, ok := key.(*Certificate)
  73. if !ok {
  74. t.Fatalf("got %v (%T), want *Certificate", key, key)
  75. }
  76. if !reflect.DeepEqual(cert.CriticalOptions, opts) {
  77. t.Errorf("unexpected critical options - got %v, want %v", cert.CriticalOptions, opts)
  78. }
  79. if !reflect.DeepEqual(cert.Extensions, exts) {
  80. t.Errorf("unexpected Extensions - got %v, want %v", cert.Extensions, exts)
  81. }
  82. marshaled := MarshalAuthorizedKey(key)
  83. // Before comparison, remove the trailing newline that
  84. // MarshalAuthorizedKey adds.
  85. marshaled = marshaled[:len(marshaled)-1]
  86. if !bytes.Equal(authKeyBytes, marshaled) {
  87. t.Errorf("marshaled certificate does not match original: got %q, want %q", marshaled, authKeyBytes)
  88. }
  89. }
  90. func TestValidateCert(t *testing.T) {
  91. key, _, _, _, err := ParseAuthorizedKey([]byte(exampleSSHCert))
  92. if err != nil {
  93. t.Fatalf("ParseAuthorizedKey: %v", err)
  94. }
  95. validCert, ok := key.(*Certificate)
  96. if !ok {
  97. t.Fatalf("got %v (%T), want *Certificate", key, key)
  98. }
  99. checker := CertChecker{}
  100. checker.IsUserAuthority = func(k PublicKey) bool {
  101. return bytes.Equal(k.Marshal(), validCert.SignatureKey.Marshal())
  102. }
  103. if err := checker.CheckCert("user", validCert); err != nil {
  104. t.Errorf("Unable to validate certificate: %v", err)
  105. }
  106. invalidCert := &Certificate{
  107. Key: testPublicKeys["rsa"],
  108. SignatureKey: testPublicKeys["ecdsa"],
  109. ValidBefore: CertTimeInfinity,
  110. Signature: &Signature{},
  111. }
  112. if err := checker.CheckCert("user", invalidCert); err == nil {
  113. t.Error("Invalid cert signature passed validation")
  114. }
  115. }
  116. func TestValidateCertTime(t *testing.T) {
  117. cert := Certificate{
  118. ValidPrincipals: []string{"user"},
  119. Key: testPublicKeys["rsa"],
  120. ValidAfter: 50,
  121. ValidBefore: 100,
  122. }
  123. cert.SignCert(rand.Reader, testSigners["ecdsa"])
  124. for ts, ok := range map[int64]bool{
  125. 25: false,
  126. 50: true,
  127. 99: true,
  128. 100: false,
  129. 125: false,
  130. } {
  131. checker := CertChecker{
  132. Clock: func() time.Time { return time.Unix(ts, 0) },
  133. }
  134. checker.IsUserAuthority = func(k PublicKey) bool {
  135. return bytes.Equal(k.Marshal(),
  136. testPublicKeys["ecdsa"].Marshal())
  137. }
  138. if v := checker.CheckCert("user", &cert); (v == nil) != ok {
  139. t.Errorf("Authenticate(%d): %v", ts, v)
  140. }
  141. }
  142. }
  143. // TODO(hanwen): tests for
  144. //
  145. // host keys:
  146. // * fallbacks
  147. func TestHostKeyCert(t *testing.T) {
  148. cert := &Certificate{
  149. ValidPrincipals: []string{"hostname", "hostname.domain", "otherhost"},
  150. Key: testPublicKeys["rsa"],
  151. ValidBefore: CertTimeInfinity,
  152. CertType: HostCert,
  153. }
  154. cert.SignCert(rand.Reader, testSigners["ecdsa"])
  155. checker := &CertChecker{
  156. IsHostAuthority: func(p PublicKey, addr string) bool {
  157. return addr == "hostname:22" && bytes.Equal(testPublicKeys["ecdsa"].Marshal(), p.Marshal())
  158. },
  159. }
  160. certSigner, err := NewCertSigner(cert, testSigners["rsa"])
  161. if err != nil {
  162. t.Errorf("NewCertSigner: %v", err)
  163. }
  164. for _, test := range []struct {
  165. addr string
  166. succeed bool
  167. }{
  168. {addr: "hostname:22", succeed: true},
  169. {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'
  170. {addr: "lasthost:22", succeed: false},
  171. } {
  172. c1, c2, err := netPipe()
  173. if err != nil {
  174. t.Fatalf("netPipe: %v", err)
  175. }
  176. defer c1.Close()
  177. defer c2.Close()
  178. errc := make(chan error)
  179. go func() {
  180. conf := ServerConfig{
  181. NoClientAuth: true,
  182. }
  183. conf.AddHostKey(certSigner)
  184. _, _, _, err := NewServerConn(c1, &conf)
  185. errc <- err
  186. }()
  187. config := &ClientConfig{
  188. User: "user",
  189. HostKeyCallback: checker.CheckHostKey,
  190. }
  191. _, _, _, err = NewClientConn(c2, test.addr, config)
  192. if (err == nil) != test.succeed {
  193. t.Fatalf("NewClientConn(%q): %v", test.addr, err)
  194. }
  195. err = <-errc
  196. if (err == nil) != test.succeed {
  197. t.Fatalf("NewServerConn(%q): %v", test.addr, err)
  198. }
  199. }
  200. }
  201. func TestCertTypes(t *testing.T) {
  202. var testVars = []struct {
  203. name string
  204. keys func() Signer
  205. }{
  206. {
  207. name: CertAlgoECDSA256v01,
  208. keys: func() Signer {
  209. s, _ := ParsePrivateKey(testdata.PEMBytes["ecdsap256"])
  210. return s
  211. },
  212. },
  213. {
  214. name: CertAlgoECDSA384v01,
  215. keys: func() Signer {
  216. s, _ := ParsePrivateKey(testdata.PEMBytes["ecdsap384"])
  217. return s
  218. },
  219. },
  220. {
  221. name: CertAlgoECDSA521v01,
  222. keys: func() Signer {
  223. s, _ := ParsePrivateKey(testdata.PEMBytes["ecdsap521"])
  224. return s
  225. },
  226. },
  227. {
  228. name: CertAlgoED25519v01,
  229. keys: func() Signer {
  230. s, _ := ParsePrivateKey(testdata.PEMBytes["ed25519"])
  231. return s
  232. },
  233. },
  234. {
  235. name: CertAlgoRSAv01,
  236. keys: func() Signer {
  237. s, _ := ParsePrivateKey(testdata.PEMBytes["rsa"])
  238. return s
  239. },
  240. },
  241. {
  242. name: CertAlgoDSAv01,
  243. keys: func() Signer {
  244. s, _ := ParsePrivateKey(testdata.PEMBytes["dsa"])
  245. return s
  246. },
  247. },
  248. }
  249. k, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  250. if err != nil {
  251. t.Fatalf("error generating host key: %v", err)
  252. }
  253. signer, err := NewSignerFromKey(k)
  254. if err != nil {
  255. t.Fatalf("error generating signer for ssh listener: %v", err)
  256. }
  257. conf := &ServerConfig{
  258. PublicKeyCallback: func(c ConnMetadata, k PublicKey) (*Permissions, error) {
  259. return new(Permissions), nil
  260. },
  261. }
  262. conf.AddHostKey(signer)
  263. for _, m := range testVars {
  264. t.Run(m.name, func(t *testing.T) {
  265. c1, c2, err := netPipe()
  266. if err != nil {
  267. t.Fatalf("netPipe: %v", err)
  268. }
  269. defer c1.Close()
  270. defer c2.Close()
  271. go NewServerConn(c1, conf)
  272. priv := m.keys()
  273. if err != nil {
  274. t.Fatalf("error generating ssh pubkey: %v", err)
  275. }
  276. cert := &Certificate{
  277. CertType: UserCert,
  278. Key: priv.PublicKey(),
  279. }
  280. cert.SignCert(rand.Reader, priv)
  281. certSigner, err := NewCertSigner(cert, priv)
  282. if err != nil {
  283. t.Fatalf("error generating cert signer: %v", err)
  284. }
  285. config := &ClientConfig{
  286. User: "user",
  287. HostKeyCallback: func(h string, r net.Addr, k PublicKey) error { return nil },
  288. Auth: []AuthMethod{PublicKeys(certSigner)},
  289. }
  290. _, _, _, err = NewClientConn(c2, "", config)
  291. if err != nil {
  292. t.Fatalf("error connecting: %v", err)
  293. }
  294. })
  295. }
  296. }