keys_test.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812
  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/ed25519"
  10. "crypto/elliptic"
  11. "crypto/rand"
  12. "crypto/rsa"
  13. "crypto/x509"
  14. "encoding/base64"
  15. "encoding/hex"
  16. "encoding/pem"
  17. "errors"
  18. "fmt"
  19. "io"
  20. "reflect"
  21. "strings"
  22. "testing"
  23. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/crypto/ssh/testdata"
  24. )
  25. func rawKey(pub PublicKey) interface{} {
  26. switch k := pub.(type) {
  27. case *rsaPublicKey:
  28. return (*rsa.PublicKey)(k)
  29. case *dsaPublicKey:
  30. return (*dsa.PublicKey)(k)
  31. case *ecdsaPublicKey:
  32. return (*ecdsa.PublicKey)(k)
  33. case ed25519PublicKey:
  34. return (ed25519.PublicKey)(k)
  35. case *Certificate:
  36. return k
  37. }
  38. panic("unknown key type")
  39. }
  40. func TestKeyMarshalParse(t *testing.T) {
  41. for _, priv := range testSigners {
  42. pub := priv.PublicKey()
  43. roundtrip, err := ParsePublicKey(pub.Marshal())
  44. if err != nil {
  45. t.Errorf("ParsePublicKey(%T): %v", pub, err)
  46. }
  47. k1 := rawKey(pub)
  48. k2 := rawKey(roundtrip)
  49. if !reflect.DeepEqual(k1, k2) {
  50. t.Errorf("got %#v in roundtrip, want %#v", k2, k1)
  51. }
  52. }
  53. }
  54. func TestUnsupportedCurves(t *testing.T) {
  55. raw, err := ecdsa.GenerateKey(elliptic.P224(), rand.Reader)
  56. if err != nil {
  57. t.Fatalf("GenerateKey: %v", err)
  58. }
  59. if _, err = NewSignerFromKey(raw); err == nil || !strings.Contains(err.Error(), "only P-256") {
  60. t.Fatalf("NewPrivateKey should not succeed with P-224, got: %v", err)
  61. }
  62. if _, err = NewPublicKey(&raw.PublicKey); err == nil || !strings.Contains(err.Error(), "only P-256") {
  63. t.Fatalf("NewPublicKey should not succeed with P-224, got: %v", err)
  64. }
  65. }
  66. func TestNewPublicKey(t *testing.T) {
  67. for _, k := range testSigners {
  68. raw := rawKey(k.PublicKey())
  69. // Skip certificates, as NewPublicKey does not support them.
  70. if _, ok := raw.(*Certificate); ok {
  71. continue
  72. }
  73. pub, err := NewPublicKey(raw)
  74. if err != nil {
  75. t.Errorf("NewPublicKey(%#v): %v", raw, err)
  76. }
  77. if !reflect.DeepEqual(k.PublicKey(), pub) {
  78. t.Errorf("NewPublicKey(%#v) = %#v, want %#v", raw, pub, k.PublicKey())
  79. }
  80. }
  81. }
  82. func TestKeySignVerify(t *testing.T) {
  83. for _, priv := range testSigners {
  84. pub := priv.PublicKey()
  85. data := []byte("sign me")
  86. sig, err := priv.Sign(rand.Reader, data)
  87. if err != nil {
  88. t.Fatalf("Sign(%T): %v", priv, err)
  89. }
  90. if err := pub.Verify(data, sig); err != nil {
  91. t.Errorf("publicKey.Verify(%T): %v", priv, err)
  92. }
  93. sig.Blob[5]++
  94. if err := pub.Verify(data, sig); err == nil {
  95. t.Errorf("publicKey.Verify on broken sig did not fail")
  96. }
  97. }
  98. }
  99. func TestKeySignWithAlgorithmVerify(t *testing.T) {
  100. for k, priv := range testSigners {
  101. if algorithmSigner, ok := priv.(MultiAlgorithmSigner); !ok {
  102. t.Errorf("Signers %q constructed by ssh package should always implement the MultiAlgorithmSigner interface: %T", k, priv)
  103. } else {
  104. pub := priv.PublicKey()
  105. data := []byte("sign me")
  106. signWithAlgTestCase := func(algorithm string, expectedAlg string) {
  107. sig, err := algorithmSigner.SignWithAlgorithm(rand.Reader, data, algorithm)
  108. if err != nil {
  109. t.Fatalf("Sign(%T): %v", priv, err)
  110. }
  111. if sig.Format != expectedAlg {
  112. t.Errorf("signature format did not match requested signature algorithm: %s != %s", sig.Format, expectedAlg)
  113. }
  114. if err := pub.Verify(data, sig); err != nil {
  115. t.Errorf("publicKey.Verify(%T): %v", priv, err)
  116. }
  117. sig.Blob[5]++
  118. if err := pub.Verify(data, sig); err == nil {
  119. t.Errorf("publicKey.Verify on broken sig did not fail")
  120. }
  121. }
  122. // Using the empty string as the algorithm name should result in the same signature format as the algorithm-free Sign method.
  123. defaultSig, err := priv.Sign(rand.Reader, data)
  124. if err != nil {
  125. t.Fatalf("Sign(%T): %v", priv, err)
  126. }
  127. signWithAlgTestCase("", defaultSig.Format)
  128. // RSA keys are the only ones which currently support more than one signing algorithm
  129. if pub.Type() == KeyAlgoRSA {
  130. for _, algorithm := range []string{KeyAlgoRSA, KeyAlgoRSASHA256, KeyAlgoRSASHA512} {
  131. signWithAlgTestCase(algorithm, algorithm)
  132. }
  133. }
  134. }
  135. }
  136. }
  137. func TestKeySignWithShortSignature(t *testing.T) {
  138. signer := testSigners["rsa"].(AlgorithmSigner)
  139. pub := signer.PublicKey()
  140. // Note: data obtained by empirically trying until a result
  141. // starting with 0 appeared
  142. tests := []struct {
  143. algorithm string
  144. data []byte
  145. }{
  146. {
  147. algorithm: KeyAlgoRSA,
  148. data: []byte("sign me92"),
  149. },
  150. {
  151. algorithm: KeyAlgoRSASHA256,
  152. data: []byte("sign me294"),
  153. },
  154. {
  155. algorithm: KeyAlgoRSASHA512,
  156. data: []byte("sign me60"),
  157. },
  158. }
  159. for _, tt := range tests {
  160. sig, err := signer.SignWithAlgorithm(rand.Reader, tt.data, tt.algorithm)
  161. if err != nil {
  162. t.Fatalf("Sign(%T): %v", signer, err)
  163. }
  164. if sig.Blob[0] != 0 {
  165. t.Errorf("%s: Expected signature with a leading 0", tt.algorithm)
  166. }
  167. sig.Blob = sig.Blob[1:]
  168. if err := pub.Verify(tt.data, sig); err != nil {
  169. t.Errorf("publicKey.Verify(%s): %v", tt.algorithm, err)
  170. }
  171. }
  172. }
  173. func TestParseRSAPrivateKey(t *testing.T) {
  174. key := testPrivateKeys["rsa"]
  175. rsa, ok := key.(*rsa.PrivateKey)
  176. if !ok {
  177. t.Fatalf("got %T, want *rsa.PrivateKey", rsa)
  178. }
  179. if err := rsa.Validate(); err != nil {
  180. t.Errorf("Validate: %v", err)
  181. }
  182. }
  183. func TestParseECPrivateKey(t *testing.T) {
  184. key := testPrivateKeys["ecdsa"]
  185. ecKey, ok := key.(*ecdsa.PrivateKey)
  186. if !ok {
  187. t.Fatalf("got %T, want *ecdsa.PrivateKey", ecKey)
  188. }
  189. if !validateECPublicKey(ecKey.Curve, ecKey.X, ecKey.Y) {
  190. t.Fatalf("public key does not validate.")
  191. }
  192. }
  193. func TestParseEncryptedPrivateKeysWithPassphrase(t *testing.T) {
  194. data := []byte("sign me")
  195. for _, tt := range testdata.PEMEncryptedKeys {
  196. t.Run(tt.Name, func(t *testing.T) {
  197. _, err := ParsePrivateKeyWithPassphrase(tt.PEMBytes, []byte("incorrect"))
  198. if err != x509.IncorrectPasswordError {
  199. t.Errorf("got %v want IncorrectPasswordError", err)
  200. }
  201. s, err := ParsePrivateKeyWithPassphrase(tt.PEMBytes, []byte(tt.EncryptionKey))
  202. if err != nil {
  203. t.Fatalf("ParsePrivateKeyWithPassphrase returned error: %s", err)
  204. }
  205. sig, err := s.Sign(rand.Reader, data)
  206. if err != nil {
  207. t.Fatalf("Signer.Sign: %v", err)
  208. }
  209. if err := s.PublicKey().Verify(data, sig); err != nil {
  210. t.Errorf("Verify failed: %v", err)
  211. }
  212. _, err = ParsePrivateKey(tt.PEMBytes)
  213. if err == nil {
  214. t.Fatalf("ParsePrivateKey succeeded, expected an error")
  215. }
  216. if err, ok := err.(*PassphraseMissingError); !ok {
  217. t.Errorf("got error %q, want PassphraseMissingError", err)
  218. } else if tt.IncludesPublicKey {
  219. if err.PublicKey == nil {
  220. t.Fatalf("expected PassphraseMissingError.PublicKey not to be nil")
  221. }
  222. got, want := err.PublicKey.Marshal(), s.PublicKey().Marshal()
  223. if !bytes.Equal(got, want) {
  224. t.Errorf("error field %q doesn't match signer public key %q", got, want)
  225. }
  226. }
  227. })
  228. }
  229. }
  230. func TestParseEncryptedPrivateKeysWithIncorrectPassphrase(t *testing.T) {
  231. pem := testdata.PEMEncryptedKeys[0].PEMBytes
  232. for i := 0; i < 4096; i++ {
  233. _, err := ParseRawPrivateKeyWithPassphrase(pem, []byte(fmt.Sprintf("%d", i)))
  234. if !errors.Is(err, x509.IncorrectPasswordError) {
  235. t.Fatalf("expected error: %v, got: %v", x509.IncorrectPasswordError, err)
  236. }
  237. }
  238. }
  239. func TestParseDSA(t *testing.T) {
  240. // We actually exercise the ParsePrivateKey codepath here, as opposed to
  241. // using the ParseRawPrivateKey+NewSignerFromKey path that testdata_test.go
  242. // uses.
  243. s, err := ParsePrivateKey(testdata.PEMBytes["dsa"])
  244. if err != nil {
  245. t.Fatalf("ParsePrivateKey returned error: %s", err)
  246. }
  247. data := []byte("sign me")
  248. sig, err := s.Sign(rand.Reader, data)
  249. if err != nil {
  250. t.Fatalf("dsa.Sign: %v", err)
  251. }
  252. if err := s.PublicKey().Verify(data, sig); err != nil {
  253. t.Errorf("Verify failed: %v", err)
  254. }
  255. }
  256. // Tests for authorized_keys parsing.
  257. // getTestKey returns a public key, and its base64 encoding.
  258. func getTestKey() (PublicKey, string) {
  259. k := testPublicKeys["rsa"]
  260. b := &bytes.Buffer{}
  261. e := base64.NewEncoder(base64.StdEncoding, b)
  262. e.Write(k.Marshal())
  263. e.Close()
  264. return k, b.String()
  265. }
  266. func TestMarshalParsePublicKey(t *testing.T) {
  267. pub, pubSerialized := getTestKey()
  268. line := fmt.Sprintf("%s %s user@host", pub.Type(), pubSerialized)
  269. authKeys := MarshalAuthorizedKey(pub)
  270. actualFields := strings.Fields(string(authKeys))
  271. if len(actualFields) == 0 {
  272. t.Fatalf("failed authKeys: %v", authKeys)
  273. }
  274. // drop the comment
  275. expectedFields := strings.Fields(line)[0:2]
  276. if !reflect.DeepEqual(actualFields, expectedFields) {
  277. t.Errorf("got %v, expected %v", actualFields, expectedFields)
  278. }
  279. actPub, _, _, _, err := ParseAuthorizedKey([]byte(line))
  280. if err != nil {
  281. t.Fatalf("cannot parse %v: %v", line, err)
  282. }
  283. if !reflect.DeepEqual(actPub, pub) {
  284. t.Errorf("got %v, expected %v", actPub, pub)
  285. }
  286. }
  287. func TestMarshalPrivateKey(t *testing.T) {
  288. tests := []struct {
  289. name string
  290. }{
  291. {"rsa-openssh-format"},
  292. {"ed25519"},
  293. {"p256-openssh-format"},
  294. {"p384-openssh-format"},
  295. {"p521-openssh-format"},
  296. }
  297. for _, tt := range tests {
  298. t.Run(tt.name, func(t *testing.T) {
  299. expected, ok := testPrivateKeys[tt.name]
  300. if !ok {
  301. t.Fatalf("cannot find key %s", tt.name)
  302. }
  303. block, err := MarshalPrivateKey(expected, "test@golang.org")
  304. if err != nil {
  305. t.Fatalf("cannot marshal %s: %v", tt.name, err)
  306. }
  307. key, err := ParseRawPrivateKey(pem.EncodeToMemory(block))
  308. if err != nil {
  309. t.Fatalf("cannot parse %s: %v", tt.name, err)
  310. }
  311. if !reflect.DeepEqual(expected, key) {
  312. t.Errorf("unexpected marshaled key %s", tt.name)
  313. }
  314. })
  315. }
  316. }
  317. func TestMarshalPrivateKeyWithPassphrase(t *testing.T) {
  318. tests := []struct {
  319. name string
  320. }{
  321. {"rsa-openssh-format"},
  322. {"ed25519"},
  323. {"p256-openssh-format"},
  324. {"p384-openssh-format"},
  325. {"p521-openssh-format"},
  326. }
  327. for _, tt := range tests {
  328. t.Run(tt.name, func(t *testing.T) {
  329. expected, ok := testPrivateKeys[tt.name]
  330. if !ok {
  331. t.Fatalf("cannot find key %s", tt.name)
  332. }
  333. block, err := MarshalPrivateKeyWithPassphrase(expected, "test@golang.org", []byte("test-passphrase"))
  334. if err != nil {
  335. t.Fatalf("cannot marshal %s: %v", tt.name, err)
  336. }
  337. key, err := ParseRawPrivateKeyWithPassphrase(pem.EncodeToMemory(block), []byte("test-passphrase"))
  338. if err != nil {
  339. t.Fatalf("cannot parse %s: %v", tt.name, err)
  340. }
  341. if !reflect.DeepEqual(expected, key) {
  342. t.Errorf("unexpected marshaled key %s", tt.name)
  343. }
  344. })
  345. }
  346. }
  347. type testAuthResult struct {
  348. pubKey PublicKey
  349. options []string
  350. comments string
  351. rest string
  352. ok bool
  353. }
  354. func testAuthorizedKeys(t *testing.T, authKeys []byte, expected []testAuthResult) {
  355. rest := authKeys
  356. var values []testAuthResult
  357. for len(rest) > 0 {
  358. var r testAuthResult
  359. var err error
  360. r.pubKey, r.comments, r.options, rest, err = ParseAuthorizedKey(rest)
  361. r.ok = (err == nil)
  362. t.Log(err)
  363. r.rest = string(rest)
  364. values = append(values, r)
  365. }
  366. if !reflect.DeepEqual(values, expected) {
  367. t.Errorf("got %#v, expected %#v", values, expected)
  368. }
  369. }
  370. func TestAuthorizedKeyBasic(t *testing.T) {
  371. pub, pubSerialized := getTestKey()
  372. line := "ssh-rsa " + pubSerialized + " user@host"
  373. testAuthorizedKeys(t, []byte(line),
  374. []testAuthResult{
  375. {pub, nil, "user@host", "", true},
  376. })
  377. }
  378. func TestAuth(t *testing.T) {
  379. pub, pubSerialized := getTestKey()
  380. authWithOptions := []string{
  381. `# comments to ignore before any keys...`,
  382. ``,
  383. `env="HOME=/home/root",no-port-forwarding ssh-rsa ` + pubSerialized + ` user@host`,
  384. `# comments to ignore, along with a blank line`,
  385. ``,
  386. `env="HOME=/home/root2" ssh-rsa ` + pubSerialized + ` user2@host2`,
  387. ``,
  388. `# more comments, plus a invalid entry`,
  389. `ssh-rsa data-that-will-not-parse user@host3`,
  390. }
  391. for _, eol := range []string{"\n", "\r\n"} {
  392. authOptions := strings.Join(authWithOptions, eol)
  393. rest2 := strings.Join(authWithOptions[3:], eol)
  394. rest3 := strings.Join(authWithOptions[6:], eol)
  395. testAuthorizedKeys(t, []byte(authOptions), []testAuthResult{
  396. {pub, []string{`env="HOME=/home/root"`, "no-port-forwarding"}, "user@host", rest2, true},
  397. {pub, []string{`env="HOME=/home/root2"`}, "user2@host2", rest3, true},
  398. {nil, nil, "", "", false},
  399. })
  400. }
  401. }
  402. func TestAuthWithQuotedSpaceInEnv(t *testing.T) {
  403. pub, pubSerialized := getTestKey()
  404. authWithQuotedSpaceInEnv := []byte(`env="HOME=/home/root dir",no-port-forwarding ssh-rsa ` + pubSerialized + ` user@host`)
  405. testAuthorizedKeys(t, []byte(authWithQuotedSpaceInEnv), []testAuthResult{
  406. {pub, []string{`env="HOME=/home/root dir"`, "no-port-forwarding"}, "user@host", "", true},
  407. })
  408. }
  409. func TestAuthWithQuotedCommaInEnv(t *testing.T) {
  410. pub, pubSerialized := getTestKey()
  411. authWithQuotedCommaInEnv := []byte(`env="HOME=/home/root,dir",no-port-forwarding ssh-rsa ` + pubSerialized + ` user@host`)
  412. testAuthorizedKeys(t, []byte(authWithQuotedCommaInEnv), []testAuthResult{
  413. {pub, []string{`env="HOME=/home/root,dir"`, "no-port-forwarding"}, "user@host", "", true},
  414. })
  415. }
  416. func TestAuthWithQuotedQuoteInEnv(t *testing.T) {
  417. pub, pubSerialized := getTestKey()
  418. authWithQuotedQuoteInEnv := []byte(`env="HOME=/home/\"root dir",no-port-forwarding` + "\t" + `ssh-rsa` + "\t" + pubSerialized + ` user@host`)
  419. authWithDoubleQuotedQuote := []byte(`no-port-forwarding,env="HOME=/home/ \"root dir\"" ssh-rsa ` + pubSerialized + "\t" + `user@host`)
  420. testAuthorizedKeys(t, []byte(authWithQuotedQuoteInEnv), []testAuthResult{
  421. {pub, []string{`env="HOME=/home/\"root dir"`, "no-port-forwarding"}, "user@host", "", true},
  422. })
  423. testAuthorizedKeys(t, []byte(authWithDoubleQuotedQuote), []testAuthResult{
  424. {pub, []string{"no-port-forwarding", `env="HOME=/home/ \"root dir\""`}, "user@host", "", true},
  425. })
  426. }
  427. func TestAuthWithInvalidSpace(t *testing.T) {
  428. _, pubSerialized := getTestKey()
  429. authWithInvalidSpace := []byte(`env="HOME=/home/root dir", no-port-forwarding ssh-rsa ` + pubSerialized + ` user@host
  430. #more to follow but still no valid keys`)
  431. testAuthorizedKeys(t, []byte(authWithInvalidSpace), []testAuthResult{
  432. {nil, nil, "", "", false},
  433. })
  434. }
  435. func TestAuthWithMissingQuote(t *testing.T) {
  436. pub, pubSerialized := getTestKey()
  437. authWithMissingQuote := []byte(`env="HOME=/home/root,no-port-forwarding ssh-rsa ` + pubSerialized + ` user@host
  438. env="HOME=/home/root",shared-control ssh-rsa ` + pubSerialized + ` user@host`)
  439. testAuthorizedKeys(t, []byte(authWithMissingQuote), []testAuthResult{
  440. {pub, []string{`env="HOME=/home/root"`, `shared-control`}, "user@host", "", true},
  441. })
  442. }
  443. func TestInvalidEntry(t *testing.T) {
  444. authInvalid := []byte(`ssh-rsa`)
  445. _, _, _, _, err := ParseAuthorizedKey(authInvalid)
  446. if err == nil {
  447. t.Errorf("got valid entry for %q", authInvalid)
  448. }
  449. }
  450. var knownHostsParseTests = []struct {
  451. input string
  452. err string
  453. marker string
  454. comment string
  455. hosts []string
  456. rest string
  457. }{
  458. {
  459. "",
  460. "EOF",
  461. "", "", nil, "",
  462. },
  463. {
  464. "# Just a comment",
  465. "EOF",
  466. "", "", nil, "",
  467. },
  468. {
  469. " \t ",
  470. "EOF",
  471. "", "", nil, "",
  472. },
  473. {
  474. "localhost ssh-rsa {RSAPUB}",
  475. "",
  476. "", "", []string{"localhost"}, "",
  477. },
  478. {
  479. "localhost\tssh-rsa {RSAPUB}",
  480. "",
  481. "", "", []string{"localhost"}, "",
  482. },
  483. {
  484. "localhost\tssh-rsa {RSAPUB}\tcomment comment",
  485. "",
  486. "", "comment comment", []string{"localhost"}, "",
  487. },
  488. {
  489. "localhost\tssh-rsa {RSAPUB}\tcomment comment\n",
  490. "",
  491. "", "comment comment", []string{"localhost"}, "",
  492. },
  493. {
  494. "localhost\tssh-rsa {RSAPUB}\tcomment comment\r\n",
  495. "",
  496. "", "comment comment", []string{"localhost"}, "",
  497. },
  498. {
  499. "localhost\tssh-rsa {RSAPUB}\tcomment comment\r\nnext line",
  500. "",
  501. "", "comment comment", []string{"localhost"}, "next line",
  502. },
  503. {
  504. "localhost,[host2:123]\tssh-rsa {RSAPUB}\tcomment comment",
  505. "",
  506. "", "comment comment", []string{"localhost", "[host2:123]"}, "",
  507. },
  508. {
  509. "@marker \tlocalhost,[host2:123]\tssh-rsa {RSAPUB}",
  510. "",
  511. "marker", "", []string{"localhost", "[host2:123]"}, "",
  512. },
  513. {
  514. "@marker \tlocalhost,[host2:123]\tssh-rsa aabbccdd",
  515. "short read",
  516. "", "", nil, "",
  517. },
  518. }
  519. func TestKnownHostsParsing(t *testing.T) {
  520. rsaPub, rsaPubSerialized := getTestKey()
  521. for i, test := range knownHostsParseTests {
  522. var expectedKey PublicKey
  523. const rsaKeyToken = "{RSAPUB}"
  524. input := test.input
  525. if strings.Contains(input, rsaKeyToken) {
  526. expectedKey = rsaPub
  527. input = strings.Replace(test.input, rsaKeyToken, rsaPubSerialized, -1)
  528. }
  529. marker, hosts, pubKey, comment, rest, err := ParseKnownHosts([]byte(input))
  530. if err != nil {
  531. if len(test.err) == 0 {
  532. t.Errorf("#%d: unexpectedly failed with %q", i, err)
  533. } else if !strings.Contains(err.Error(), test.err) {
  534. t.Errorf("#%d: expected error containing %q, but got %q", i, test.err, err)
  535. }
  536. continue
  537. } else if len(test.err) != 0 {
  538. t.Errorf("#%d: succeeded but expected error including %q", i, test.err)
  539. continue
  540. }
  541. if !reflect.DeepEqual(expectedKey, pubKey) {
  542. t.Errorf("#%d: expected key %#v, but got %#v", i, expectedKey, pubKey)
  543. }
  544. if marker != test.marker {
  545. t.Errorf("#%d: expected marker %q, but got %q", i, test.marker, marker)
  546. }
  547. if comment != test.comment {
  548. t.Errorf("#%d: expected comment %q, but got %q", i, test.comment, comment)
  549. }
  550. if !reflect.DeepEqual(test.hosts, hosts) {
  551. t.Errorf("#%d: expected hosts %#v, but got %#v", i, test.hosts, hosts)
  552. }
  553. if rest := string(rest); rest != test.rest {
  554. t.Errorf("#%d: expected remaining input to be %q, but got %q", i, test.rest, rest)
  555. }
  556. }
  557. }
  558. func TestFingerprintLegacyMD5(t *testing.T) {
  559. pub, _ := getTestKey()
  560. fingerprint := FingerprintLegacyMD5(pub)
  561. want := "b7:ef:d3:d5:89:29:52:96:9f:df:47:41:4d:15:37:f4" // ssh-keygen -lf -E md5 rsa
  562. if fingerprint != want {
  563. t.Errorf("got fingerprint %q want %q", fingerprint, want)
  564. }
  565. }
  566. func TestFingerprintSHA256(t *testing.T) {
  567. pub, _ := getTestKey()
  568. fingerprint := FingerprintSHA256(pub)
  569. want := "SHA256:fi5+D7UmDZDE9Q2sAVvvlpcQSIakN4DERdINgXd2AnE" // ssh-keygen -lf rsa
  570. if fingerprint != want {
  571. t.Errorf("got fingerprint %q want %q", fingerprint, want)
  572. }
  573. }
  574. func TestInvalidKeys(t *testing.T) {
  575. keyTypes := []string{
  576. "RSA PRIVATE KEY",
  577. "PRIVATE KEY",
  578. "EC PRIVATE KEY",
  579. "DSA PRIVATE KEY",
  580. "OPENSSH PRIVATE KEY",
  581. }
  582. for _, keyType := range keyTypes {
  583. for _, dataLen := range []int{0, 1, 2, 5, 10, 20} {
  584. data := make([]byte, dataLen)
  585. if _, err := io.ReadFull(rand.Reader, data); err != nil {
  586. t.Fatal(err)
  587. }
  588. var buf bytes.Buffer
  589. pem.Encode(&buf, &pem.Block{
  590. Type: keyType,
  591. Bytes: data,
  592. })
  593. // This test is just to ensure that the function
  594. // doesn't panic so the return value is ignored.
  595. ParseRawPrivateKey(buf.Bytes())
  596. }
  597. }
  598. }
  599. func TestSKKeys(t *testing.T) {
  600. for _, d := range testdata.SKData {
  601. pk, _, _, _, err := ParseAuthorizedKey(d.PubKey)
  602. if err != nil {
  603. t.Fatalf("parseAuthorizedKey returned error: %v", err)
  604. }
  605. sigBuf := make([]byte, hex.DecodedLen(len(d.HexSignature)))
  606. if _, err := hex.Decode(sigBuf, d.HexSignature); err != nil {
  607. t.Fatalf("hex.Decode() failed: %v", err)
  608. }
  609. dataBuf := make([]byte, hex.DecodedLen(len(d.HexData)))
  610. if _, err := hex.Decode(dataBuf, d.HexData); err != nil {
  611. t.Fatalf("hex.Decode() failed: %v", err)
  612. }
  613. sig, _, ok := parseSignature(sigBuf)
  614. if !ok {
  615. t.Fatalf("parseSignature(%v) failed", sigBuf)
  616. }
  617. // Test that good data and signature pass verification
  618. if err := pk.Verify(dataBuf, sig); err != nil {
  619. t.Errorf("%s: PublicKey.Verify(%v, %v) failed: %v", d.Name, dataBuf, sig, err)
  620. }
  621. // Invalid data being passed in
  622. invalidData := []byte("INVALID DATA")
  623. if err := pk.Verify(invalidData, sig); err == nil {
  624. t.Errorf("%s with invalid data: PublicKey.Verify(%v, %v) passed unexpectedly", d.Name, invalidData, sig)
  625. }
  626. // Change byte in blob to corrup signature
  627. sig.Blob[5] = byte('A')
  628. // Corrupted data being passed in
  629. if err := pk.Verify(dataBuf, sig); err == nil {
  630. t.Errorf("%s with corrupted signature: PublicKey.Verify(%v, %v) passed unexpectedly", d.Name, dataBuf, sig)
  631. }
  632. }
  633. }
  634. func TestNewSignerWithAlgos(t *testing.T) {
  635. algorithSigner, ok := testSigners["rsa"].(AlgorithmSigner)
  636. if !ok {
  637. t.Fatal("rsa test signer does not implement the AlgorithmSigner interface")
  638. }
  639. _, err := NewSignerWithAlgorithms(algorithSigner, nil)
  640. if err == nil {
  641. t.Error("signer with algos created with no algorithms")
  642. }
  643. _, err = NewSignerWithAlgorithms(algorithSigner, []string{KeyAlgoED25519})
  644. if err == nil {
  645. t.Error("signer with algos created with invalid algorithms")
  646. }
  647. _, err = NewSignerWithAlgorithms(algorithSigner, []string{CertAlgoRSASHA256v01})
  648. if err == nil {
  649. t.Error("signer with algos created with certificate algorithms")
  650. }
  651. mas, err := NewSignerWithAlgorithms(algorithSigner, []string{KeyAlgoRSASHA256, KeyAlgoRSASHA512})
  652. if err != nil {
  653. t.Errorf("unable to create signer with valid algorithms: %v", err)
  654. }
  655. _, err = NewSignerWithAlgorithms(mas, []string{KeyAlgoRSA})
  656. if err == nil {
  657. t.Error("signer with algos created with restricted algorithms")
  658. }
  659. }
  660. func TestCryptoPublicKey(t *testing.T) {
  661. for _, priv := range testSigners {
  662. p1 := priv.PublicKey()
  663. key, ok := p1.(CryptoPublicKey)
  664. if !ok {
  665. continue
  666. }
  667. p2, err := NewPublicKey(key.CryptoPublicKey())
  668. if err != nil {
  669. t.Fatalf("NewPublicKey(CryptoPublicKey) failed for %s, got: %v", p1.Type(), err)
  670. }
  671. if !reflect.DeepEqual(p1, p2) {
  672. t.Errorf("got %#v in NewPublicKey, want %#v", p2, p1)
  673. }
  674. }
  675. for _, d := range testdata.SKData {
  676. p1, _, _, _, err := ParseAuthorizedKey(d.PubKey)
  677. if err != nil {
  678. t.Fatalf("parseAuthorizedKey returned error: %v", err)
  679. }
  680. k1, ok := p1.(CryptoPublicKey)
  681. if !ok {
  682. t.Fatalf("%T does not implement CryptoPublicKey", p1)
  683. }
  684. var p2 PublicKey
  685. switch pub := k1.CryptoPublicKey().(type) {
  686. case *ecdsa.PublicKey:
  687. p2 = &skECDSAPublicKey{
  688. application: "ssh:",
  689. PublicKey: *pub,
  690. }
  691. case ed25519.PublicKey:
  692. p2 = &skEd25519PublicKey{
  693. application: "ssh:",
  694. PublicKey: pub,
  695. }
  696. default:
  697. t.Fatalf("unexpected type %T from CryptoPublicKey()", pub)
  698. }
  699. if !reflect.DeepEqual(p1, p2) {
  700. t.Errorf("got %#v, want %#v", p2, p1)
  701. }
  702. }
  703. }