keys_test.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. package openpgp
  2. import (
  3. "bytes"
  4. "crypto"
  5. "strings"
  6. "testing"
  7. "time"
  8. "golang.org/x/crypto/openpgp/errors"
  9. "golang.org/x/crypto/openpgp/packet"
  10. )
  11. func TestKeyExpiry(t *testing.T) {
  12. kring, err := ReadKeyRing(readerFromHex(expiringKeyHex))
  13. if err != nil {
  14. t.Fatal(err)
  15. }
  16. entity := kring[0]
  17. const timeFormat = "2006-01-02"
  18. time1, _ := time.Parse(timeFormat, "2013-07-01")
  19. // The expiringKeyHex key is structured as:
  20. //
  21. // pub 1024R/5E237D8C created: 2013-07-01 expires: 2013-07-31 usage: SC
  22. // sub 1024R/1ABB25A0 created: 2013-07-01 23:11:07 +0200 CEST expires: 2013-07-08 usage: E
  23. // sub 1024R/96A672F5 created: 2013-07-01 23:11:23 +0200 CEST expires: 2013-07-31 usage: E
  24. //
  25. // So this should select the newest, non-expired encryption key.
  26. key, _ := entity.encryptionKey(time1)
  27. if id, expected := key.PublicKey.KeyIdShortString(), "96A672F5"; id != expected {
  28. t.Errorf("Expected key %s at time %s, but got key %s", expected, time1.Format(timeFormat), id)
  29. }
  30. // Once the first encryption subkey has expired, the second should be
  31. // selected.
  32. time2, _ := time.Parse(timeFormat, "2013-07-09")
  33. key, _ = entity.encryptionKey(time2)
  34. if id, expected := key.PublicKey.KeyIdShortString(), "96A672F5"; id != expected {
  35. t.Errorf("Expected key %s at time %s, but got key %s", expected, time2.Format(timeFormat), id)
  36. }
  37. // Once all the keys have expired, nothing should be returned.
  38. time3, _ := time.Parse(timeFormat, "2013-08-01")
  39. if key, ok := entity.encryptionKey(time3); ok {
  40. t.Errorf("Expected no key at time %s, but got key %s", time3.Format(timeFormat), key.PublicKey.KeyIdShortString())
  41. }
  42. }
  43. func TestMissingCrossSignature(t *testing.T) {
  44. // This public key has a signing subkey, but the subkey does not
  45. // contain a cross-signature.
  46. keys, err := ReadArmoredKeyRing(bytes.NewBufferString(missingCrossSignatureKey))
  47. if len(keys) != 0 {
  48. t.Errorf("Accepted key with missing cross signature")
  49. }
  50. if err == nil {
  51. t.Fatal("Failed to detect error in keyring with missing cross signature")
  52. }
  53. structural, ok := err.(errors.StructuralError)
  54. if !ok {
  55. t.Fatalf("Unexpected class of error: %T. Wanted StructuralError", err)
  56. }
  57. const expectedMsg = "signing subkey is missing cross-signature"
  58. if !strings.Contains(string(structural), expectedMsg) {
  59. t.Fatalf("Unexpected error: %q. Expected it to contain %q", err, expectedMsg)
  60. }
  61. }
  62. func TestInvalidCrossSignature(t *testing.T) {
  63. // This public key has a signing subkey, and the subkey has an
  64. // embedded cross-signature. However, the cross-signature does
  65. // not correctly validate over the primary and subkey.
  66. keys, err := ReadArmoredKeyRing(bytes.NewBufferString(invalidCrossSignatureKey))
  67. if len(keys) != 0 {
  68. t.Errorf("Accepted key with invalid cross signature")
  69. }
  70. if err == nil {
  71. t.Fatal("Failed to detect error in keyring with an invalid cross signature")
  72. }
  73. structural, ok := err.(errors.StructuralError)
  74. if !ok {
  75. t.Fatalf("Unexpected class of error: %T. Wanted StructuralError", err)
  76. }
  77. const expectedMsg = "subkey signature invalid"
  78. if !strings.Contains(string(structural), expectedMsg) {
  79. t.Fatalf("Unexpected error: %q. Expected it to contain %q", err, expectedMsg)
  80. }
  81. }
  82. func TestGoodCrossSignature(t *testing.T) {
  83. // This public key has a signing subkey, and the subkey has an
  84. // embedded cross-signature which correctly validates over the
  85. // primary and subkey.
  86. keys, err := ReadArmoredKeyRing(bytes.NewBufferString(goodCrossSignatureKey))
  87. if err != nil {
  88. t.Fatal(err)
  89. }
  90. if len(keys) != 1 {
  91. t.Errorf("Failed to accept key with good cross signature, %d", len(keys))
  92. }
  93. if len(keys[0].Subkeys) != 1 {
  94. t.Errorf("Failed to accept good subkey, %d", len(keys[0].Subkeys))
  95. }
  96. }
  97. func TestRevokedUserID(t *testing.T) {
  98. // This key contains 2 UIDs, one of which is revoked:
  99. // [ultimate] (1) Golang Gopher <no-reply@golang.com>
  100. // [ revoked] (2) Golang Gopher <revoked@golang.com>
  101. keys, err := ReadArmoredKeyRing(bytes.NewBufferString(revokedUserIDKey))
  102. if err != nil {
  103. t.Fatal(err)
  104. }
  105. if len(keys) != 1 {
  106. t.Fatal("Failed to read key with a revoked user id")
  107. }
  108. var identities []*Identity
  109. for _, identity := range keys[0].Identities {
  110. identities = append(identities, identity)
  111. }
  112. if numIdentities, numExpected := len(identities), 1; numIdentities != numExpected {
  113. t.Errorf("obtained %d identities, expected %d", numIdentities, numExpected)
  114. }
  115. if identityName, expectedName := identities[0].Name, "Golang Gopher <no-reply@golang.com>"; identityName != expectedName {
  116. t.Errorf("obtained identity %s expected %s", identityName, expectedName)
  117. }
  118. }
  119. // TestExternallyRevokableKey attempts to load and parse a key with a third party revocation permission.
  120. func TestExternallyRevocableKey(t *testing.T) {
  121. kring, err := ReadKeyRing(readerFromHex(subkeyUsageHex))
  122. if err != nil {
  123. t.Fatal(err)
  124. }
  125. // The 0xA42704B92866382A key can be revoked by 0xBE3893CB843D0FE70C
  126. // according to this signature that appears within the key:
  127. // :signature packet: algo 1, keyid A42704B92866382A
  128. // version 4, created 1396409682, md5len 0, sigclass 0x1f
  129. // digest algo 2, begin of digest a9 84
  130. // hashed subpkt 2 len 4 (sig created 2014-04-02)
  131. // hashed subpkt 12 len 22 (revocation key: c=80 a=1 f=CE094AA433F7040BB2DDF0BE3893CB843D0FE70C)
  132. // hashed subpkt 7 len 1 (not revocable)
  133. // subpkt 16 len 8 (issuer key ID A42704B92866382A)
  134. // data: [1024 bits]
  135. id := uint64(0xA42704B92866382A)
  136. keys := kring.KeysById(id)
  137. if len(keys) != 1 {
  138. t.Errorf("Expected to find key id %X, but got %d matches", id, len(keys))
  139. }
  140. }
  141. func TestKeyRevocation(t *testing.T) {
  142. kring, err := ReadKeyRing(readerFromHex(revokedKeyHex))
  143. if err != nil {
  144. t.Fatal(err)
  145. }
  146. // revokedKeyHex contains these keys:
  147. // pub 1024R/9A34F7C0 2014-03-25 [revoked: 2014-03-25]
  148. // sub 1024R/1BA3CD60 2014-03-25 [revoked: 2014-03-25]
  149. ids := []uint64{0xA401D9F09A34F7C0, 0x5CD3BE0A1BA3CD60}
  150. for _, id := range ids {
  151. keys := kring.KeysById(id)
  152. if len(keys) != 1 {
  153. t.Errorf("Expected KeysById to find revoked key %X, but got %d matches", id, len(keys))
  154. }
  155. keys = kring.KeysByIdUsage(id, 0)
  156. if len(keys) != 0 {
  157. t.Errorf("Expected KeysByIdUsage to filter out revoked key %X, but got %d matches", id, len(keys))
  158. }
  159. }
  160. }
  161. func TestKeyWithRevokedSubKey(t *testing.T) {
  162. // This key contains a revoked sub key:
  163. // pub rsa1024/0x4CBD826C39074E38 2018-06-14 [SC]
  164. // Key fingerprint = 3F95 169F 3FFA 7D3F 2B47 6F0C 4CBD 826C 3907 4E38
  165. // uid Golang Gopher <no-reply@golang.com>
  166. // sub rsa1024/0x945DB1AF61D85727 2018-06-14 [S] [revoked: 2018-06-14]
  167. keys, err := ReadArmoredKeyRing(bytes.NewBufferString(keyWithSubKey))
  168. if err != nil {
  169. t.Fatal(err)
  170. }
  171. if len(keys) != 1 {
  172. t.Fatal("Failed to read key with a sub key")
  173. }
  174. identity := keys[0].Identities["Golang Gopher <no-reply@golang.com>"]
  175. // Test for an issue where Subkey Binding Signatures (RFC 4880 5.2.1) were added to the identity
  176. // preceding the Subkey Packet if the Subkey Packet was followed by more than one signature.
  177. // For example, the current key has the following layout:
  178. // PUBKEY UID SELFSIG SUBKEY REV SELFSIG
  179. // The last SELFSIG would be added to the UID's signatures. This is wrong.
  180. if numIdentitySigs, numExpected := len(identity.Signatures), 0; numIdentitySigs != numExpected {
  181. t.Fatalf("got %d identity signatures, expected %d", numIdentitySigs, numExpected)
  182. }
  183. if numSubKeys, numExpected := len(keys[0].Subkeys), 1; numSubKeys != numExpected {
  184. t.Fatalf("got %d subkeys, expected %d", numSubKeys, numExpected)
  185. }
  186. subKey := keys[0].Subkeys[0]
  187. if subKey.Sig == nil {
  188. t.Fatalf("subkey signature is nil")
  189. }
  190. }
  191. func TestSubkeyRevocation(t *testing.T) {
  192. kring, err := ReadKeyRing(readerFromHex(revokedSubkeyHex))
  193. if err != nil {
  194. t.Fatal(err)
  195. }
  196. // revokedSubkeyHex contains these keys:
  197. // pub 1024R/4EF7E4BECCDE97F0 2014-03-25
  198. // sub 1024R/D63636E2B96AE423 2014-03-25
  199. // sub 1024D/DBCE4EE19529437F 2014-03-25
  200. // sub 1024R/677815E371C2FD23 2014-03-25 [revoked: 2014-03-25]
  201. validKeys := []uint64{0x4EF7E4BECCDE97F0, 0xD63636E2B96AE423, 0xDBCE4EE19529437F}
  202. revokedKey := uint64(0x677815E371C2FD23)
  203. for _, id := range validKeys {
  204. keys := kring.KeysById(id)
  205. if len(keys) != 1 {
  206. t.Errorf("Expected KeysById to find key %X, but got %d matches", id, len(keys))
  207. }
  208. keys = kring.KeysByIdUsage(id, 0)
  209. if len(keys) != 1 {
  210. t.Errorf("Expected KeysByIdUsage to find key %X, but got %d matches", id, len(keys))
  211. }
  212. }
  213. keys := kring.KeysById(revokedKey)
  214. if len(keys) != 1 {
  215. t.Errorf("Expected KeysById to find key %X, but got %d matches", revokedKey, len(keys))
  216. }
  217. keys = kring.KeysByIdUsage(revokedKey, 0)
  218. if len(keys) != 0 {
  219. t.Errorf("Expected KeysByIdUsage to filter out revoked key %X, but got %d matches", revokedKey, len(keys))
  220. }
  221. }
  222. func TestKeyWithSubKeyAndBadSelfSigOrder(t *testing.T) {
  223. // This key was altered so that the self signatures following the
  224. // subkey are in a sub-optimal order.
  225. //
  226. // Note: Should someone have to create a similar key again, look into
  227. // gpgsplit, gpg --dearmor, and gpg --enarmor.
  228. //
  229. // The packet ordering is the following:
  230. // PUBKEY UID UIDSELFSIG SUBKEY SELFSIG1 SELFSIG2
  231. //
  232. // Where:
  233. // SELFSIG1 expires on 2018-06-14 and was created first
  234. // SELFSIG2 does not expire and was created after SELFSIG1
  235. //
  236. // Test for RFC 4880 5.2.3.3:
  237. // > An implementation that encounters multiple self-signatures on the
  238. // > same object may resolve the ambiguity in any way it sees fit, but it
  239. // > is RECOMMENDED that priority be given to the most recent self-
  240. // > signature.
  241. //
  242. // This means that we should keep SELFSIG2.
  243. keys, err := ReadArmoredKeyRing(bytes.NewBufferString(keyWithSubKeyAndBadSelfSigOrder))
  244. if err != nil {
  245. t.Fatal(err)
  246. }
  247. if len(keys) != 1 {
  248. t.Fatal("Failed to read key with a sub key and a bad selfsig packet order")
  249. }
  250. key := keys[0]
  251. if numKeys, expected := len(key.Subkeys), 1; numKeys != expected {
  252. t.Fatalf("Read %d subkeys, expected %d", numKeys, expected)
  253. }
  254. subKey := key.Subkeys[0]
  255. if lifetime := subKey.Sig.KeyLifetimeSecs; lifetime != nil {
  256. t.Errorf("The signature has a key lifetime (%d), but it should be nil", *lifetime)
  257. }
  258. }
  259. func TestKeyUsage(t *testing.T) {
  260. kring, err := ReadKeyRing(readerFromHex(subkeyUsageHex))
  261. if err != nil {
  262. t.Fatal(err)
  263. }
  264. // subkeyUsageHex contains these keys:
  265. // pub 1024R/2866382A created: 2014-04-01 expires: never usage: SC
  266. // sub 1024R/936C9153 created: 2014-04-01 expires: never usage: E
  267. // sub 1024R/64D5F5BB created: 2014-04-02 expires: never usage: E
  268. // sub 1024D/BC0BA992 created: 2014-04-02 expires: never usage: S
  269. certifiers := []uint64{0xA42704B92866382A}
  270. signers := []uint64{0xA42704B92866382A, 0x42CE2C64BC0BA992}
  271. encrypters := []uint64{0x09C0C7D9936C9153, 0xC104E98664D5F5BB}
  272. for _, id := range certifiers {
  273. keys := kring.KeysByIdUsage(id, packet.KeyFlagCertify)
  274. if len(keys) == 1 {
  275. if keys[0].PublicKey.KeyId != id {
  276. t.Errorf("Expected to find certifier key id %X, but got %X", id, keys[0].PublicKey.KeyId)
  277. }
  278. } else {
  279. t.Errorf("Expected one match for certifier key id %X, but got %d matches", id, len(keys))
  280. }
  281. }
  282. for _, id := range signers {
  283. keys := kring.KeysByIdUsage(id, packet.KeyFlagSign)
  284. if len(keys) == 1 {
  285. if keys[0].PublicKey.KeyId != id {
  286. t.Errorf("Expected to find signing key id %X, but got %X", id, keys[0].PublicKey.KeyId)
  287. }
  288. } else {
  289. t.Errorf("Expected one match for signing key id %X, but got %d matches", id, len(keys))
  290. }
  291. // This keyring contains no encryption keys that are also good for signing.
  292. keys = kring.KeysByIdUsage(id, packet.KeyFlagEncryptStorage|packet.KeyFlagEncryptCommunications)
  293. if len(keys) != 0 {
  294. t.Errorf("Unexpected match for encryption key id %X", id)
  295. }
  296. }
  297. for _, id := range encrypters {
  298. keys := kring.KeysByIdUsage(id, packet.KeyFlagEncryptStorage|packet.KeyFlagEncryptCommunications)
  299. if len(keys) == 1 {
  300. if keys[0].PublicKey.KeyId != id {
  301. t.Errorf("Expected to find encryption key id %X, but got %X", id, keys[0].PublicKey.KeyId)
  302. }
  303. } else {
  304. t.Errorf("Expected one match for encryption key id %X, but got %d matches", id, len(keys))
  305. }
  306. // This keyring contains no encryption keys that are also good for signing.
  307. keys = kring.KeysByIdUsage(id, packet.KeyFlagSign)
  308. if len(keys) != 0 {
  309. t.Errorf("Unexpected match for signing key id %X", id)
  310. }
  311. }
  312. }
  313. func TestIdVerification(t *testing.T) {
  314. kring, err := ReadKeyRing(readerFromHex(testKeys1And2PrivateHex))
  315. if err != nil {
  316. t.Fatal(err)
  317. }
  318. if err := kring[1].PrivateKey.Decrypt([]byte("passphrase")); err != nil {
  319. t.Fatal(err)
  320. }
  321. const identity = "Test Key 1 (RSA)"
  322. if err := kring[0].SignIdentity(identity, kring[1], nil); err != nil {
  323. t.Fatal(err)
  324. }
  325. ident, ok := kring[0].Identities[identity]
  326. if !ok {
  327. t.Fatal("identity missing from key after signing")
  328. }
  329. checked := false
  330. for _, sig := range ident.Signatures {
  331. if sig.IssuerKeyId == nil || *sig.IssuerKeyId != kring[1].PrimaryKey.KeyId {
  332. continue
  333. }
  334. if err := kring[1].PrimaryKey.VerifyUserIdSignature(identity, kring[0].PrimaryKey, sig); err != nil {
  335. t.Fatalf("error verifying new identity signature: %s", err)
  336. }
  337. checked = true
  338. break
  339. }
  340. if !checked {
  341. t.Fatal("didn't find identity signature in Entity")
  342. }
  343. }
  344. func TestNewEntityWithPreferredHash(t *testing.T) {
  345. c := &packet.Config{
  346. DefaultHash: crypto.SHA256,
  347. }
  348. entity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", c)
  349. if err != nil {
  350. t.Fatal(err)
  351. }
  352. for _, identity := range entity.Identities {
  353. if len(identity.SelfSignature.PreferredHash) == 0 {
  354. t.Fatal("didn't find a preferred hash in self signature")
  355. }
  356. ph := hashToHashId(c.DefaultHash)
  357. if identity.SelfSignature.PreferredHash[0] != ph {
  358. t.Fatalf("Expected preferred hash to be %d, got %d", ph, identity.SelfSignature.PreferredHash[0])
  359. }
  360. }
  361. }
  362. func TestNewEntityWithoutPreferredHash(t *testing.T) {
  363. entity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", nil)
  364. if err != nil {
  365. t.Fatal(err)
  366. }
  367. for _, identity := range entity.Identities {
  368. if len(identity.SelfSignature.PreferredHash) != 0 {
  369. t.Fatalf("Expected preferred hash to be empty but got length %d", len(identity.SelfSignature.PreferredHash))
  370. }
  371. }
  372. }
  373. func TestNewEntityCorrectName(t *testing.T) {
  374. entity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", nil)
  375. if err != nil {
  376. t.Fatal(err)
  377. }
  378. if len(entity.Identities) != 1 {
  379. t.Fatalf("len(entity.Identities) = %d, want 1", len(entity.Identities))
  380. }
  381. var got string
  382. for _, i := range entity.Identities {
  383. got = i.Name
  384. }
  385. want := "Golang Gopher (Test Key) <no-reply@golang.com>"
  386. if got != want {
  387. t.Fatalf("Identity.Name = %q, want %q", got, want)
  388. }
  389. }
  390. func TestNewEntityWithPreferredSymmetric(t *testing.T) {
  391. c := &packet.Config{
  392. DefaultCipher: packet.CipherAES256,
  393. }
  394. entity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", c)
  395. if err != nil {
  396. t.Fatal(err)
  397. }
  398. for _, identity := range entity.Identities {
  399. if len(identity.SelfSignature.PreferredSymmetric) == 0 {
  400. t.Fatal("didn't find a preferred cipher in self signature")
  401. }
  402. if identity.SelfSignature.PreferredSymmetric[0] != uint8(c.DefaultCipher) {
  403. t.Fatalf("Expected preferred cipher to be %d, got %d", uint8(c.DefaultCipher), identity.SelfSignature.PreferredSymmetric[0])
  404. }
  405. }
  406. }
  407. func TestNewEntityWithoutPreferredSymmetric(t *testing.T) {
  408. entity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", nil)
  409. if err != nil {
  410. t.Fatal(err)
  411. }
  412. for _, identity := range entity.Identities {
  413. if len(identity.SelfSignature.PreferredSymmetric) != 0 {
  414. t.Fatalf("Expected preferred cipher to be empty but got length %d", len(identity.SelfSignature.PreferredSymmetric))
  415. }
  416. }
  417. }
  418. func TestNewEntityPublicSerialization(t *testing.T) {
  419. entity, err := NewEntity("Golang Gopher", "Test Key", "no-reply@golang.com", nil)
  420. if err != nil {
  421. t.Fatal(err)
  422. }
  423. serializedEntity := bytes.NewBuffer(nil)
  424. entity.Serialize(serializedEntity)
  425. _, err = ReadEntity(packet.NewReader(bytes.NewBuffer(serializedEntity.Bytes())))
  426. if err != nil {
  427. t.Fatal(err)
  428. }
  429. }