keys_test.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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. package ssh
  5. import (
  6. "bytes"
  7. "crypto/dsa"
  8. "crypto/ecdsa"
  9. "crypto/elliptic"
  10. "crypto/rand"
  11. "crypto/rsa"
  12. "encoding/base64"
  13. "fmt"
  14. "reflect"
  15. "strings"
  16. "testing"
  17. "github.com/gogits/gogs/modules/crypto/ssh/testdata"
  18. )
  19. func rawKey(pub PublicKey) interface{} {
  20. switch k := pub.(type) {
  21. case *rsaPublicKey:
  22. return (*rsa.PublicKey)(k)
  23. case *dsaPublicKey:
  24. return (*dsa.PublicKey)(k)
  25. case *ecdsaPublicKey:
  26. return (*ecdsa.PublicKey)(k)
  27. case *Certificate:
  28. return k
  29. }
  30. panic("unknown key type")
  31. }
  32. func TestKeyMarshalParse(t *testing.T) {
  33. for _, priv := range testSigners {
  34. pub := priv.PublicKey()
  35. roundtrip, err := ParsePublicKey(pub.Marshal())
  36. if err != nil {
  37. t.Errorf("ParsePublicKey(%T): %v", pub, err)
  38. }
  39. k1 := rawKey(pub)
  40. k2 := rawKey(roundtrip)
  41. if !reflect.DeepEqual(k1, k2) {
  42. t.Errorf("got %#v in roundtrip, want %#v", k2, k1)
  43. }
  44. }
  45. }
  46. func TestUnsupportedCurves(t *testing.T) {
  47. raw, err := ecdsa.GenerateKey(elliptic.P224(), rand.Reader)
  48. if err != nil {
  49. t.Fatalf("GenerateKey: %v", err)
  50. }
  51. if _, err = NewSignerFromKey(raw); err == nil || !strings.Contains(err.Error(), "only P256") {
  52. t.Fatalf("NewPrivateKey should not succeed with P224, got: %v", err)
  53. }
  54. if _, err = NewPublicKey(&raw.PublicKey); err == nil || !strings.Contains(err.Error(), "only P256") {
  55. t.Fatalf("NewPublicKey should not succeed with P224, got: %v", err)
  56. }
  57. }
  58. func TestNewPublicKey(t *testing.T) {
  59. for _, k := range testSigners {
  60. raw := rawKey(k.PublicKey())
  61. // Skip certificates, as NewPublicKey does not support them.
  62. if _, ok := raw.(*Certificate); ok {
  63. continue
  64. }
  65. pub, err := NewPublicKey(raw)
  66. if err != nil {
  67. t.Errorf("NewPublicKey(%#v): %v", raw, err)
  68. }
  69. if !reflect.DeepEqual(k.PublicKey(), pub) {
  70. t.Errorf("NewPublicKey(%#v) = %#v, want %#v", raw, pub, k.PublicKey())
  71. }
  72. }
  73. }
  74. func TestKeySignVerify(t *testing.T) {
  75. for _, priv := range testSigners {
  76. pub := priv.PublicKey()
  77. data := []byte("sign me")
  78. sig, err := priv.Sign(rand.Reader, data)
  79. if err != nil {
  80. t.Fatalf("Sign(%T): %v", priv, err)
  81. }
  82. if err := pub.Verify(data, sig); err != nil {
  83. t.Errorf("publicKey.Verify(%T): %v", priv, err)
  84. }
  85. sig.Blob[5]++
  86. if err := pub.Verify(data, sig); err == nil {
  87. t.Errorf("publicKey.Verify on broken sig did not fail")
  88. }
  89. }
  90. }
  91. func TestParseRSAPrivateKey(t *testing.T) {
  92. key := testPrivateKeys["rsa"]
  93. rsa, ok := key.(*rsa.PrivateKey)
  94. if !ok {
  95. t.Fatalf("got %T, want *rsa.PrivateKey", rsa)
  96. }
  97. if err := rsa.Validate(); err != nil {
  98. t.Errorf("Validate: %v", err)
  99. }
  100. }
  101. func TestParseECPrivateKey(t *testing.T) {
  102. key := testPrivateKeys["ecdsa"]
  103. ecKey, ok := key.(*ecdsa.PrivateKey)
  104. if !ok {
  105. t.Fatalf("got %T, want *ecdsa.PrivateKey", ecKey)
  106. }
  107. if !validateECPublicKey(ecKey.Curve, ecKey.X, ecKey.Y) {
  108. t.Fatalf("public key does not validate.")
  109. }
  110. }
  111. func TestParseDSA(t *testing.T) {
  112. // We actually exercise the ParsePrivateKey codepath here, as opposed to
  113. // using the ParseRawPrivateKey+NewSignerFromKey path that testdata_test.go
  114. // uses.
  115. s, err := ParsePrivateKey(testdata.PEMBytes["dsa"])
  116. if err != nil {
  117. t.Fatalf("ParsePrivateKey returned error: %s", err)
  118. }
  119. data := []byte("sign me")
  120. sig, err := s.Sign(rand.Reader, data)
  121. if err != nil {
  122. t.Fatalf("dsa.Sign: %v", err)
  123. }
  124. if err := s.PublicKey().Verify(data, sig); err != nil {
  125. t.Errorf("Verify failed: %v", err)
  126. }
  127. }
  128. // Tests for authorized_keys parsing.
  129. // getTestKey returns a public key, and its base64 encoding.
  130. func getTestKey() (PublicKey, string) {
  131. k := testPublicKeys["rsa"]
  132. b := &bytes.Buffer{}
  133. e := base64.NewEncoder(base64.StdEncoding, b)
  134. e.Write(k.Marshal())
  135. e.Close()
  136. return k, b.String()
  137. }
  138. func TestMarshalParsePublicKey(t *testing.T) {
  139. pub, pubSerialized := getTestKey()
  140. line := fmt.Sprintf("%s %s user@host", pub.Type(), pubSerialized)
  141. authKeys := MarshalAuthorizedKey(pub)
  142. actualFields := strings.Fields(string(authKeys))
  143. if len(actualFields) == 0 {
  144. t.Fatalf("failed authKeys: %v", authKeys)
  145. }
  146. // drop the comment
  147. expectedFields := strings.Fields(line)[0:2]
  148. if !reflect.DeepEqual(actualFields, expectedFields) {
  149. t.Errorf("got %v, expected %v", actualFields, expectedFields)
  150. }
  151. actPub, _, _, _, err := ParseAuthorizedKey([]byte(line))
  152. if err != nil {
  153. t.Fatalf("cannot parse %v: %v", line, err)
  154. }
  155. if !reflect.DeepEqual(actPub, pub) {
  156. t.Errorf("got %v, expected %v", actPub, pub)
  157. }
  158. }
  159. type authResult struct {
  160. pubKey PublicKey
  161. options []string
  162. comments string
  163. rest string
  164. ok bool
  165. }
  166. func testAuthorizedKeys(t *testing.T, authKeys []byte, expected []authResult) {
  167. rest := authKeys
  168. var values []authResult
  169. for len(rest) > 0 {
  170. var r authResult
  171. var err error
  172. r.pubKey, r.comments, r.options, rest, err = ParseAuthorizedKey(rest)
  173. r.ok = (err == nil)
  174. t.Log(err)
  175. r.rest = string(rest)
  176. values = append(values, r)
  177. }
  178. if !reflect.DeepEqual(values, expected) {
  179. t.Errorf("got %#v, expected %#v", values, expected)
  180. }
  181. }
  182. func TestAuthorizedKeyBasic(t *testing.T) {
  183. pub, pubSerialized := getTestKey()
  184. line := "ssh-rsa " + pubSerialized + " user@host"
  185. testAuthorizedKeys(t, []byte(line),
  186. []authResult{
  187. {pub, nil, "user@host", "", true},
  188. })
  189. }
  190. func TestAuth(t *testing.T) {
  191. pub, pubSerialized := getTestKey()
  192. authWithOptions := []string{
  193. `# comments to ignore before any keys...`,
  194. ``,
  195. `env="HOME=/home/root",no-port-forwarding ssh-rsa ` + pubSerialized + ` user@host`,
  196. `# comments to ignore, along with a blank line`,
  197. ``,
  198. `env="HOME=/home/root2" ssh-rsa ` + pubSerialized + ` user2@host2`,
  199. ``,
  200. `# more comments, plus a invalid entry`,
  201. `ssh-rsa data-that-will-not-parse user@host3`,
  202. }
  203. for _, eol := range []string{"\n", "\r\n"} {
  204. authOptions := strings.Join(authWithOptions, eol)
  205. rest2 := strings.Join(authWithOptions[3:], eol)
  206. rest3 := strings.Join(authWithOptions[6:], eol)
  207. testAuthorizedKeys(t, []byte(authOptions), []authResult{
  208. {pub, []string{`env="HOME=/home/root"`, "no-port-forwarding"}, "user@host", rest2, true},
  209. {pub, []string{`env="HOME=/home/root2"`}, "user2@host2", rest3, true},
  210. {nil, nil, "", "", false},
  211. })
  212. }
  213. }
  214. func TestAuthWithQuotedSpaceInEnv(t *testing.T) {
  215. pub, pubSerialized := getTestKey()
  216. authWithQuotedSpaceInEnv := []byte(`env="HOME=/home/root dir",no-port-forwarding ssh-rsa ` + pubSerialized + ` user@host`)
  217. testAuthorizedKeys(t, []byte(authWithQuotedSpaceInEnv), []authResult{
  218. {pub, []string{`env="HOME=/home/root dir"`, "no-port-forwarding"}, "user@host", "", true},
  219. })
  220. }
  221. func TestAuthWithQuotedCommaInEnv(t *testing.T) {
  222. pub, pubSerialized := getTestKey()
  223. authWithQuotedCommaInEnv := []byte(`env="HOME=/home/root,dir",no-port-forwarding ssh-rsa ` + pubSerialized + ` user@host`)
  224. testAuthorizedKeys(t, []byte(authWithQuotedCommaInEnv), []authResult{
  225. {pub, []string{`env="HOME=/home/root,dir"`, "no-port-forwarding"}, "user@host", "", true},
  226. })
  227. }
  228. func TestAuthWithQuotedQuoteInEnv(t *testing.T) {
  229. pub, pubSerialized := getTestKey()
  230. authWithQuotedQuoteInEnv := []byte(`env="HOME=/home/\"root dir",no-port-forwarding` + "\t" + `ssh-rsa` + "\t" + pubSerialized + ` user@host`)
  231. authWithDoubleQuotedQuote := []byte(`no-port-forwarding,env="HOME=/home/ \"root dir\"" ssh-rsa ` + pubSerialized + "\t" + `user@host`)
  232. testAuthorizedKeys(t, []byte(authWithQuotedQuoteInEnv), []authResult{
  233. {pub, []string{`env="HOME=/home/\"root dir"`, "no-port-forwarding"}, "user@host", "", true},
  234. })
  235. testAuthorizedKeys(t, []byte(authWithDoubleQuotedQuote), []authResult{
  236. {pub, []string{"no-port-forwarding", `env="HOME=/home/ \"root dir\""`}, "user@host", "", true},
  237. })
  238. }
  239. func TestAuthWithInvalidSpace(t *testing.T) {
  240. _, pubSerialized := getTestKey()
  241. authWithInvalidSpace := []byte(`env="HOME=/home/root dir", no-port-forwarding ssh-rsa ` + pubSerialized + ` user@host
  242. #more to follow but still no valid keys`)
  243. testAuthorizedKeys(t, []byte(authWithInvalidSpace), []authResult{
  244. {nil, nil, "", "", false},
  245. })
  246. }
  247. func TestAuthWithMissingQuote(t *testing.T) {
  248. pub, pubSerialized := getTestKey()
  249. authWithMissingQuote := []byte(`env="HOME=/home/root,no-port-forwarding ssh-rsa ` + pubSerialized + ` user@host
  250. env="HOME=/home/root",shared-control ssh-rsa ` + pubSerialized + ` user@host`)
  251. testAuthorizedKeys(t, []byte(authWithMissingQuote), []authResult{
  252. {pub, []string{`env="HOME=/home/root"`, `shared-control`}, "user@host", "", true},
  253. })
  254. }
  255. func TestInvalidEntry(t *testing.T) {
  256. authInvalid := []byte(`ssh-rsa`)
  257. _, _, _, _, err := ParseAuthorizedKey(authInvalid)
  258. if err == nil {
  259. t.Errorf("got valid entry for %q", authInvalid)
  260. }
  261. }