本站源代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

903 lines
28KB

  1. // Copyright 2011 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 openpgp
  5. import (
  6. "crypto/hmac"
  7. "encoding/binary"
  8. "io"
  9. "time"
  10. "github.com/keybase/go-crypto/openpgp/armor"
  11. "github.com/keybase/go-crypto/openpgp/errors"
  12. "github.com/keybase/go-crypto/openpgp/packet"
  13. "github.com/keybase/go-crypto/rsa"
  14. )
  15. // PublicKeyType is the armor type for a PGP public key.
  16. var PublicKeyType = "PGP PUBLIC KEY BLOCK"
  17. // PrivateKeyType is the armor type for a PGP private key.
  18. var PrivateKeyType = "PGP PRIVATE KEY BLOCK"
  19. // An Entity represents the components of an OpenPGP key: a primary public key
  20. // (which must be a signing key), one or more identities claimed by that key,
  21. // and zero or more subkeys, which may be encryption keys.
  22. type Entity struct {
  23. PrimaryKey *packet.PublicKey
  24. PrivateKey *packet.PrivateKey
  25. Identities map[string]*Identity // indexed by Identity.Name
  26. Revocations []*packet.Signature
  27. // Revocations that are signed by designated revokers. Reading keys
  28. // will not verify these revocations, because it won't have access to
  29. // issuers' public keys, API consumers should do this instead (or
  30. // not, and just assume that the key is probably revoked).
  31. UnverifiedRevocations []*packet.Signature
  32. Subkeys []Subkey
  33. BadSubkeys []BadSubkey
  34. }
  35. // An Identity represents an identity claimed by an Entity and zero or more
  36. // assertions by other entities about that claim.
  37. type Identity struct {
  38. Name string // by convention, has the form "Full Name (comment) <email@example.com>"
  39. UserId *packet.UserId
  40. SelfSignature *packet.Signature
  41. Signatures []*packet.Signature
  42. Revocation *packet.Signature
  43. }
  44. // A Subkey is an additional public key in an Entity. Subkeys can be used for
  45. // encryption.
  46. type Subkey struct {
  47. PublicKey *packet.PublicKey
  48. PrivateKey *packet.PrivateKey
  49. Sig *packet.Signature
  50. Revocation *packet.Signature
  51. }
  52. // BadSubkey is one that failed reconstruction, but we'll keep it around for
  53. // informational purposes.
  54. type BadSubkey struct {
  55. Subkey
  56. Err error
  57. }
  58. // A Key identifies a specific public key in an Entity. This is either the
  59. // Entity's primary key or a subkey.
  60. type Key struct {
  61. Entity *Entity
  62. PublicKey *packet.PublicKey
  63. PrivateKey *packet.PrivateKey
  64. SelfSignature *packet.Signature
  65. KeyFlags packet.KeyFlagBits
  66. }
  67. // A KeyRing provides access to public and private keys.
  68. type KeyRing interface {
  69. // KeysById returns the set of keys that have the given key id.
  70. // fp can be optionally supplied, which is the full key fingerprint.
  71. // If it's provided, then it must match. This comes up in the case
  72. // of GPG subpacket 33.
  73. KeysById(id uint64, fp []byte) []Key
  74. // KeysByIdAndUsage returns the set of keys with the given id
  75. // that also meet the key usage given by requiredUsage.
  76. // The requiredUsage is expressed as the bitwise-OR of
  77. // packet.KeyFlag* values.
  78. // fp can be optionally supplied, which is the full key fingerprint.
  79. // If it's provided, then it must match. This comes up in the case
  80. // of GPG subpacket 33.
  81. KeysByIdUsage(id uint64, fp []byte, requiredUsage byte) []Key
  82. // DecryptionKeys returns all private keys that are valid for
  83. // decryption.
  84. DecryptionKeys() []Key
  85. }
  86. // primaryIdentity returns the Identity marked as primary or the first identity
  87. // if none are so marked.
  88. func (e *Entity) primaryIdentity() *Identity {
  89. var firstIdentity *Identity
  90. for _, ident := range e.Identities {
  91. if firstIdentity == nil {
  92. firstIdentity = ident
  93. }
  94. if ident.SelfSignature.IsPrimaryId != nil && *ident.SelfSignature.IsPrimaryId {
  95. return ident
  96. }
  97. }
  98. return firstIdentity
  99. }
  100. // encryptionKey returns the best candidate Key for encrypting a message to the
  101. // given Entity.
  102. func (e *Entity) encryptionKey(now time.Time) (Key, bool) {
  103. candidateSubkey := -1
  104. // Iterate the keys to find the newest key
  105. var maxTime time.Time
  106. for i, subkey := range e.Subkeys {
  107. // NOTE(maxtaco)
  108. // If there is a Flags subpacket, then we have to follow it, and only
  109. // use keys that are marked for Encryption of Communication. If there
  110. // isn't a Flags subpacket, and this is an Encrypt-Only key (right now only ElGamal
  111. // suffices), then we implicitly use it. The check for primary below is a little
  112. // more open-ended, but for now, let's be strict and potentially open up
  113. // if we see bugs in the wild.
  114. //
  115. // One more note: old DSA/ElGamal keys tend not to have the Flags subpacket,
  116. // so this sort of thing is pretty important for encrypting to older keys.
  117. //
  118. if ((subkey.Sig.FlagsValid && subkey.Sig.FlagEncryptCommunications) ||
  119. (!subkey.Sig.FlagsValid && subkey.PublicKey.PubKeyAlgo == packet.PubKeyAlgoElGamal)) &&
  120. subkey.PublicKey.PubKeyAlgo.CanEncrypt() &&
  121. !subkey.Sig.KeyExpired(now) &&
  122. subkey.Revocation == nil &&
  123. (maxTime.IsZero() || subkey.Sig.CreationTime.After(maxTime)) {
  124. candidateSubkey = i
  125. maxTime = subkey.Sig.CreationTime
  126. }
  127. }
  128. if candidateSubkey != -1 {
  129. subkey := e.Subkeys[candidateSubkey]
  130. return Key{e, subkey.PublicKey, subkey.PrivateKey, subkey.Sig, subkey.Sig.GetKeyFlags()}, true
  131. }
  132. // If we don't have any candidate subkeys for encryption and
  133. // the primary key doesn't have any usage metadata then we
  134. // assume that the primary key is ok. Or, if the primary key is
  135. // marked as ok to encrypt to, then we can obviously use it.
  136. //
  137. // NOTE(maxtaco) - see note above, how this policy is a little too open-ended
  138. // for my liking, but leave it for now.
  139. i := e.primaryIdentity()
  140. if (!i.SelfSignature.FlagsValid || i.SelfSignature.FlagEncryptCommunications) &&
  141. e.PrimaryKey.PubKeyAlgo.CanEncrypt() &&
  142. !i.SelfSignature.KeyExpired(now) {
  143. return Key{e, e.PrimaryKey, e.PrivateKey, i.SelfSignature, i.SelfSignature.GetKeyFlags()}, true
  144. }
  145. // This Entity appears to be signing only.
  146. return Key{}, false
  147. }
  148. // signingKey return the best candidate Key for signing a message with this
  149. // Entity.
  150. func (e *Entity) signingKey(now time.Time) (Key, bool) {
  151. candidateSubkey := -1
  152. for i, subkey := range e.Subkeys {
  153. if (!subkey.Sig.FlagsValid || subkey.Sig.FlagSign) &&
  154. subkey.PrivateKey.PrivateKey != nil &&
  155. subkey.PublicKey.PubKeyAlgo.CanSign() &&
  156. subkey.Revocation == nil &&
  157. !subkey.Sig.KeyExpired(now) {
  158. candidateSubkey = i
  159. break
  160. }
  161. }
  162. if candidateSubkey != -1 {
  163. subkey := e.Subkeys[candidateSubkey]
  164. return Key{e, subkey.PublicKey, subkey.PrivateKey, subkey.Sig, subkey.Sig.GetKeyFlags()}, true
  165. }
  166. // If we have no candidate subkey then we assume that it's ok to sign
  167. // with the primary key.
  168. i := e.primaryIdentity()
  169. if (!i.SelfSignature.FlagsValid || i.SelfSignature.FlagSign) &&
  170. e.PrimaryKey.PubKeyAlgo.CanSign() &&
  171. !i.SelfSignature.KeyExpired(now) &&
  172. e.PrivateKey.PrivateKey != nil {
  173. return Key{e, e.PrimaryKey, e.PrivateKey, i.SelfSignature, i.SelfSignature.GetKeyFlags()}, true
  174. }
  175. return Key{}, false
  176. }
  177. // An EntityList contains one or more Entities.
  178. type EntityList []*Entity
  179. func keyMatchesIdAndFingerprint(key *packet.PublicKey, id uint64, fp []byte) bool {
  180. if key.KeyId != id {
  181. return false
  182. }
  183. if fp == nil {
  184. return true
  185. }
  186. return hmac.Equal(fp, key.Fingerprint[:])
  187. }
  188. // KeysById returns the set of keys that have the given key id.
  189. // fp can be optionally supplied, which is the full key fingerprint.
  190. // If it's provided, then it must match. This comes up in the case
  191. // of GPG subpacket 33.
  192. func (el EntityList) KeysById(id uint64, fp []byte) (keys []Key) {
  193. for _, e := range el {
  194. if keyMatchesIdAndFingerprint(e.PrimaryKey, id, fp) {
  195. var selfSig *packet.Signature
  196. for _, ident := range e.Identities {
  197. if selfSig == nil {
  198. selfSig = ident.SelfSignature
  199. } else if ident.SelfSignature.IsPrimaryId != nil && *ident.SelfSignature.IsPrimaryId {
  200. selfSig = ident.SelfSignature
  201. break
  202. }
  203. }
  204. var keyFlags packet.KeyFlagBits
  205. for _, ident := range e.Identities {
  206. keyFlags.Merge(ident.SelfSignature.GetKeyFlags())
  207. }
  208. keys = append(keys, Key{e, e.PrimaryKey, e.PrivateKey, selfSig, keyFlags})
  209. }
  210. for _, subKey := range e.Subkeys {
  211. if keyMatchesIdAndFingerprint(subKey.PublicKey, id, fp) {
  212. // If there's both a a revocation and a sig, then take the
  213. // revocation. Otherwise, we can proceed with the sig.
  214. sig := subKey.Revocation
  215. if sig == nil {
  216. sig = subKey.Sig
  217. }
  218. keys = append(keys, Key{e, subKey.PublicKey, subKey.PrivateKey, sig, sig.GetKeyFlags()})
  219. }
  220. }
  221. }
  222. return
  223. }
  224. // KeysByIdAndUsage returns the set of keys with the given id that also meet
  225. // the key usage given by requiredUsage. The requiredUsage is expressed as
  226. // the bitwise-OR of packet.KeyFlag* values.
  227. // fp can be optionally supplied, which is the full key fingerprint.
  228. // If it's provided, then it must match. This comes up in the case
  229. // of GPG subpacket 33.
  230. func (el EntityList) KeysByIdUsage(id uint64, fp []byte, requiredUsage byte) (keys []Key) {
  231. for _, key := range el.KeysById(id, fp) {
  232. if len(key.Entity.Revocations) > 0 {
  233. continue
  234. }
  235. if key.SelfSignature.RevocationReason != nil {
  236. continue
  237. }
  238. if requiredUsage != 0 {
  239. var usage byte
  240. switch {
  241. case key.KeyFlags.Valid:
  242. usage = key.KeyFlags.BitField
  243. case key.PublicKey.PubKeyAlgo == packet.PubKeyAlgoElGamal:
  244. // We also need to handle the case where, although the sig's
  245. // flags aren't valid, the key can is implicitly usable for
  246. // encryption by virtue of being ElGamal. See also the comment
  247. // in encryptionKey() above.
  248. usage |= packet.KeyFlagEncryptCommunications
  249. usage |= packet.KeyFlagEncryptStorage
  250. case key.PublicKey.PubKeyAlgo == packet.PubKeyAlgoDSA ||
  251. key.PublicKey.PubKeyAlgo == packet.PubKeyAlgoECDSA ||
  252. key.PublicKey.PubKeyAlgo == packet.PubKeyAlgoEdDSA:
  253. usage |= packet.KeyFlagSign
  254. // For a primary RSA key without any key flags, be as permissiable
  255. // as possible.
  256. case key.PublicKey.PubKeyAlgo == packet.PubKeyAlgoRSA &&
  257. keyMatchesIdAndFingerprint(key.Entity.PrimaryKey, id, fp):
  258. usage = (packet.KeyFlagCertify | packet.KeyFlagSign |
  259. packet.KeyFlagEncryptCommunications | packet.KeyFlagEncryptStorage)
  260. }
  261. if usage&requiredUsage != requiredUsage {
  262. continue
  263. }
  264. }
  265. keys = append(keys, key)
  266. }
  267. return
  268. }
  269. // DecryptionKeys returns all private keys that are valid for decryption.
  270. func (el EntityList) DecryptionKeys() (keys []Key) {
  271. for _, e := range el {
  272. for _, subKey := range e.Subkeys {
  273. if subKey.PrivateKey != nil && subKey.PrivateKey.PrivateKey != nil && (!subKey.Sig.FlagsValid || subKey.Sig.FlagEncryptStorage || subKey.Sig.FlagEncryptCommunications) {
  274. keys = append(keys, Key{e, subKey.PublicKey, subKey.PrivateKey, subKey.Sig, subKey.Sig.GetKeyFlags()})
  275. }
  276. }
  277. }
  278. return
  279. }
  280. // ReadArmoredKeyRing reads one or more public/private keys from an armor keyring file.
  281. func ReadArmoredKeyRing(r io.Reader) (EntityList, error) {
  282. block, err := armor.Decode(r)
  283. if err == io.EOF {
  284. return nil, errors.InvalidArgumentError("no armored data found")
  285. }
  286. if err != nil {
  287. return nil, err
  288. }
  289. if block.Type != PublicKeyType && block.Type != PrivateKeyType {
  290. return nil, errors.InvalidArgumentError("expected public or private key block, got: " + block.Type)
  291. }
  292. return ReadKeyRing(block.Body)
  293. }
  294. // ReadKeyRing reads one or more public/private keys. Unsupported keys are
  295. // ignored as long as at least a single valid key is found.
  296. func ReadKeyRing(r io.Reader) (el EntityList, err error) {
  297. packets := packet.NewReader(r)
  298. var lastUnsupportedError error
  299. for {
  300. var e *Entity
  301. e, err = ReadEntity(packets)
  302. if err != nil {
  303. // TODO: warn about skipped unsupported/unreadable keys
  304. if _, ok := err.(errors.UnsupportedError); ok {
  305. lastUnsupportedError = err
  306. err = readToNextPublicKey(packets)
  307. } else if _, ok := err.(errors.StructuralError); ok {
  308. // Skip unreadable, badly-formatted keys
  309. lastUnsupportedError = err
  310. err = readToNextPublicKey(packets)
  311. }
  312. if err == io.EOF {
  313. err = nil
  314. break
  315. }
  316. if err != nil {
  317. el = nil
  318. break
  319. }
  320. } else {
  321. el = append(el, e)
  322. }
  323. }
  324. if len(el) == 0 && err == nil {
  325. err = lastUnsupportedError
  326. }
  327. return
  328. }
  329. // readToNextPublicKey reads packets until the start of the entity and leaves
  330. // the first packet of the new entity in the Reader.
  331. func readToNextPublicKey(packets *packet.Reader) (err error) {
  332. var p packet.Packet
  333. for {
  334. p, err = packets.Next()
  335. if err == io.EOF {
  336. return
  337. } else if err != nil {
  338. if _, ok := err.(errors.UnsupportedError); ok {
  339. err = nil
  340. continue
  341. }
  342. return
  343. }
  344. if pk, ok := p.(*packet.PublicKey); ok && !pk.IsSubkey {
  345. packets.Unread(p)
  346. return
  347. }
  348. }
  349. panic("unreachable")
  350. }
  351. // ReadEntity reads an entity (public key, identities, subkeys etc) from the
  352. // given Reader.
  353. func ReadEntity(packets *packet.Reader) (*Entity, error) {
  354. e := new(Entity)
  355. e.Identities = make(map[string]*Identity)
  356. p, err := packets.Next()
  357. if err != nil {
  358. return nil, err
  359. }
  360. var ok bool
  361. if e.PrimaryKey, ok = p.(*packet.PublicKey); !ok {
  362. if e.PrivateKey, ok = p.(*packet.PrivateKey); !ok {
  363. packets.Unread(p)
  364. return nil, errors.StructuralError("first packet was not a public/private key")
  365. } else {
  366. e.PrimaryKey = &e.PrivateKey.PublicKey
  367. }
  368. }
  369. if !e.PrimaryKey.PubKeyAlgo.CanSign() {
  370. return nil, errors.StructuralError("primary key cannot be used for signatures")
  371. }
  372. var current *Identity
  373. var revocations []*packet.Signature
  374. designatedRevokers := make(map[uint64]bool)
  375. EachPacket:
  376. for {
  377. p, err := packets.Next()
  378. if err == io.EOF {
  379. break
  380. } else if err != nil {
  381. return nil, err
  382. }
  383. switch pkt := p.(type) {
  384. case *packet.UserId:
  385. // Make a new Identity object, that we might wind up throwing away.
  386. // We'll only add it if we get a valid self-signature over this
  387. // userID.
  388. current = new(Identity)
  389. current.Name = pkt.Id
  390. current.UserId = pkt
  391. case *packet.Signature:
  392. if pkt.SigType == packet.SigTypeKeyRevocation {
  393. // These revocations won't revoke UIDs (see
  394. // SigTypeIdentityRevocation). Handle these first,
  395. // because key might have revocation coming from
  396. // another key (designated revoke).
  397. revocations = append(revocations, pkt)
  398. continue
  399. }
  400. // These are signatures by other people on this key. Let's just ignore them
  401. // from the beginning, since they shouldn't affect our key decoding one way
  402. // or the other.
  403. if pkt.IssuerKeyId != nil && *pkt.IssuerKeyId != e.PrimaryKey.KeyId {
  404. continue
  405. }
  406. // If this is a signature made by the keyholder, and the signature has stubbed out
  407. // critical packets, then *now* we need to bail out.
  408. if e := pkt.StubbedOutCriticalError; e != nil {
  409. return nil, e
  410. }
  411. // Next handle the case of a self-signature. According to RFC8440,
  412. // Section 5.2.3.3, if there are several self-signatures,
  413. // we should take the newer one. If they were both created
  414. // at the same time, but one of them has keyflags specified and the
  415. // other doesn't, keep the one with the keyflags. We have actually
  416. // seen this in the wild (see the 'Yield' test in read_test.go).
  417. // If there is a tie, and both have the same value for FlagsValid,
  418. // then "last writer wins."
  419. //
  420. // HOWEVER! We have seen yet more keys in the wild (see the 'Spiros'
  421. // test in read_test.go), in which the later self-signature is a bunch
  422. // of junk, and doesn't even specify key flags. Does it really make
  423. // sense to overwrite reasonable key flags with the empty set? I'm not
  424. // sure what that would be trying to achieve, and plus GPG seems to be
  425. // ok with this situation, and ignores the later (empty) keyflag set.
  426. // So further tighten our overwrite rules, and only allow the later
  427. // signature to overwrite the earlier signature if so doing won't
  428. // trash the key flags.
  429. if current != nil &&
  430. (current.SelfSignature == nil ||
  431. (!pkt.CreationTime.Before(current.SelfSignature.CreationTime) &&
  432. (pkt.FlagsValid || !current.SelfSignature.FlagsValid))) &&
  433. (pkt.SigType == packet.SigTypePositiveCert || pkt.SigType == packet.SigTypeGenericCert) &&
  434. pkt.IssuerKeyId != nil &&
  435. *pkt.IssuerKeyId == e.PrimaryKey.KeyId {
  436. if err = e.PrimaryKey.VerifyUserIdSignature(current.Name, e.PrimaryKey, pkt); err == nil {
  437. current.SelfSignature = pkt
  438. // NOTE(maxtaco) 2016.01.11
  439. // Only register an identity once we've gotten a valid self-signature.
  440. // It's possible therefore for us to throw away `current` in the case
  441. // no valid self-signatures were found. That's OK as long as there are
  442. // other identies that make sense.
  443. //
  444. // NOTE! We might later see a revocation for this very same UID, and it
  445. // won't be undone. We've preserved this feature from the original
  446. // Google OpenPGP we forked from.
  447. e.Identities[current.Name] = current
  448. } else {
  449. // We really should warn that there was a failure here. Not raise an error
  450. // since this really shouldn't be a fail-stop error.
  451. }
  452. } else if current != nil && pkt.SigType == packet.SigTypeIdentityRevocation {
  453. if err = e.PrimaryKey.VerifyUserIdSignature(current.Name, e.PrimaryKey, pkt); err == nil {
  454. // Note: we are not removing the identity from
  455. // e.Identities. Caller can always filter by Revocation
  456. // field to ignore revoked identities.
  457. current.Revocation = pkt
  458. }
  459. } else if pkt.SigType == packet.SigTypeDirectSignature {
  460. if err = e.PrimaryKey.VerifyRevocationSignature(e.PrimaryKey, pkt); err == nil {
  461. if desig := pkt.DesignatedRevoker; desig != nil {
  462. // If it's a designated revoker signature, take last 8 octects
  463. // of fingerprint as Key ID and save it to designatedRevokers
  464. // map. We consult this map later to see if a foreign
  465. // revocation should be added to UnverifiedRevocations.
  466. keyID := binary.BigEndian.Uint64(desig.Fingerprint[len(desig.Fingerprint)-8:])
  467. designatedRevokers[keyID] = true
  468. }
  469. }
  470. } else if current == nil {
  471. // NOTE(maxtaco)
  472. //
  473. // See https://github.com/keybase/client/issues/2666
  474. //
  475. // There might have been a user attribute picture before this signature,
  476. // in which case this is still a valid PGP key. In the future we might
  477. // not ignore user attributes (like picture). But either way, it doesn't
  478. // make sense to bail out here. Keep looking for other valid signatures.
  479. //
  480. // Used to be:
  481. // return nil, errors.StructuralError("signature packet found before user id packet")
  482. } else {
  483. current.Signatures = append(current.Signatures, pkt)
  484. }
  485. case *packet.PrivateKey:
  486. if pkt.IsSubkey == false {
  487. packets.Unread(p)
  488. break EachPacket
  489. }
  490. err = addSubkey(e, packets, &pkt.PublicKey, pkt)
  491. if err != nil {
  492. return nil, err
  493. }
  494. case *packet.PublicKey:
  495. if pkt.IsSubkey == false {
  496. packets.Unread(p)
  497. break EachPacket
  498. }
  499. err = addSubkey(e, packets, pkt, nil)
  500. if err != nil {
  501. return nil, err
  502. }
  503. default:
  504. // we ignore unknown packets
  505. }
  506. }
  507. if len(e.Identities) == 0 {
  508. return nil, errors.StructuralError("entity without any identities")
  509. }
  510. for _, revocation := range revocations {
  511. if revocation.IssuerKeyId == nil || *revocation.IssuerKeyId == e.PrimaryKey.KeyId {
  512. // Key revokes itself, something that we can verify.
  513. err = e.PrimaryKey.VerifyRevocationSignature(e.PrimaryKey, revocation)
  514. if err == nil {
  515. e.Revocations = append(e.Revocations, revocation)
  516. } else {
  517. return nil, errors.StructuralError("revocation signature signed by alternate key")
  518. }
  519. } else if revocation.IssuerKeyId != nil {
  520. if _, ok := designatedRevokers[*revocation.IssuerKeyId]; ok {
  521. // Revocation is done by certified designated revoker,
  522. // but we can't verify the revocation.
  523. e.UnverifiedRevocations = append(e.UnverifiedRevocations, revocation)
  524. }
  525. }
  526. }
  527. return e, nil
  528. }
  529. func addSubkey(e *Entity, packets *packet.Reader, pub *packet.PublicKey, priv *packet.PrivateKey) error {
  530. var subKey Subkey
  531. subKey.PublicKey = pub
  532. subKey.PrivateKey = priv
  533. var lastErr error
  534. for {
  535. p, err := packets.Next()
  536. if err == io.EOF {
  537. break
  538. }
  539. if err != nil {
  540. return errors.StructuralError("subkey signature invalid: " + err.Error())
  541. }
  542. sig, ok := p.(*packet.Signature)
  543. if !ok {
  544. // Hit a non-signature packet, so assume we're up to the next key
  545. packets.Unread(p)
  546. break
  547. }
  548. if st := sig.SigType; st != packet.SigTypeSubkeyBinding && st != packet.SigTypeSubkeyRevocation {
  549. // Note(maxtaco):
  550. // We used to error out here, but instead, let's fast-forward past
  551. // packets that are in the wrong place (like misplaced 0x13 signatures)
  552. // until we get to one that works. For a test case,
  553. // see TestWithBadSubkeySignaturePackets.
  554. continue
  555. }
  556. err = e.PrimaryKey.VerifyKeySignature(subKey.PublicKey, sig)
  557. if err != nil {
  558. // Non valid signature, so again, no need to abandon all hope, just continue;
  559. // make a note of the error we hit.
  560. lastErr = errors.StructuralError("subkey signature invalid: " + err.Error())
  561. continue
  562. }
  563. switch sig.SigType {
  564. case packet.SigTypeSubkeyBinding:
  565. // Does the "new" sig set expiration to later date than
  566. // "previous" sig?
  567. if subKey.Sig == nil || subKey.Sig.ExpiresBeforeOther(sig) {
  568. subKey.Sig = sig
  569. }
  570. case packet.SigTypeSubkeyRevocation:
  571. // First writer wins
  572. if subKey.Revocation == nil {
  573. subKey.Revocation = sig
  574. }
  575. }
  576. }
  577. if subKey.Sig != nil {
  578. e.Subkeys = append(e.Subkeys, subKey)
  579. } else {
  580. if lastErr == nil {
  581. lastErr = errors.StructuralError("Subkey wasn't signed; expected a 'binding' signature")
  582. }
  583. e.BadSubkeys = append(e.BadSubkeys, BadSubkey{Subkey: subKey, Err: lastErr})
  584. }
  585. return nil
  586. }
  587. const defaultRSAKeyBits = 2048
  588. // NewEntity returns an Entity that contains a fresh RSA/RSA keypair with a
  589. // single identity composed of the given full name, comment and email, any of
  590. // which may be empty but must not contain any of "()<>\x00".
  591. // If config is nil, sensible defaults will be used.
  592. func NewEntity(name, comment, email string, config *packet.Config) (*Entity, error) {
  593. currentTime := config.Now()
  594. bits := defaultRSAKeyBits
  595. if config != nil && config.RSABits != 0 {
  596. bits = config.RSABits
  597. }
  598. uid := packet.NewUserId(name, comment, email)
  599. if uid == nil {
  600. return nil, errors.InvalidArgumentError("user id field contained invalid characters")
  601. }
  602. signingPriv, err := rsa.GenerateKey(config.Random(), bits)
  603. if err != nil {
  604. return nil, err
  605. }
  606. encryptingPriv, err := rsa.GenerateKey(config.Random(), bits)
  607. if err != nil {
  608. return nil, err
  609. }
  610. e := &Entity{
  611. PrimaryKey: packet.NewRSAPublicKey(currentTime, &signingPriv.PublicKey),
  612. PrivateKey: packet.NewRSAPrivateKey(currentTime, signingPriv),
  613. Identities: make(map[string]*Identity),
  614. }
  615. isPrimaryId := true
  616. e.Identities[uid.Id] = &Identity{
  617. Name: uid.Name,
  618. UserId: uid,
  619. SelfSignature: &packet.Signature{
  620. CreationTime: currentTime,
  621. SigType: packet.SigTypePositiveCert,
  622. PubKeyAlgo: packet.PubKeyAlgoRSA,
  623. Hash: config.Hash(),
  624. IsPrimaryId: &isPrimaryId,
  625. FlagsValid: true,
  626. FlagSign: true,
  627. FlagCertify: true,
  628. IssuerKeyId: &e.PrimaryKey.KeyId,
  629. },
  630. }
  631. e.Subkeys = make([]Subkey, 1)
  632. e.Subkeys[0] = Subkey{
  633. PublicKey: packet.NewRSAPublicKey(currentTime, &encryptingPriv.PublicKey),
  634. PrivateKey: packet.NewRSAPrivateKey(currentTime, encryptingPriv),
  635. Sig: &packet.Signature{
  636. CreationTime: currentTime,
  637. SigType: packet.SigTypeSubkeyBinding,
  638. PubKeyAlgo: packet.PubKeyAlgoRSA,
  639. Hash: config.Hash(),
  640. FlagsValid: true,
  641. FlagEncryptStorage: true,
  642. FlagEncryptCommunications: true,
  643. IssuerKeyId: &e.PrimaryKey.KeyId,
  644. },
  645. }
  646. e.Subkeys[0].PublicKey.IsSubkey = true
  647. e.Subkeys[0].PrivateKey.IsSubkey = true
  648. return e, nil
  649. }
  650. // SerializePrivate serializes an Entity, including private key material, to
  651. // the given Writer. For now, it must only be used on an Entity returned from
  652. // NewEntity.
  653. // If config is nil, sensible defaults will be used.
  654. func (e *Entity) SerializePrivate(w io.Writer, config *packet.Config) (err error) {
  655. err = e.PrivateKey.Serialize(w)
  656. if err != nil {
  657. return
  658. }
  659. for _, ident := range e.Identities {
  660. err = ident.UserId.Serialize(w)
  661. if err != nil {
  662. return
  663. }
  664. if e.PrivateKey.PrivateKey != nil {
  665. err = ident.SelfSignature.SignUserId(ident.UserId.Id, e.PrimaryKey, e.PrivateKey, config)
  666. if err != nil {
  667. return
  668. }
  669. }
  670. err = ident.SelfSignature.Serialize(w)
  671. if err != nil {
  672. return
  673. }
  674. }
  675. for _, subkey := range e.Subkeys {
  676. err = subkey.PrivateKey.Serialize(w)
  677. if err != nil {
  678. return
  679. }
  680. // Workaround shortcoming of SignKey(), which doesn't work to reverse-sign
  681. // sub-signing keys. So if requested, just reuse the signatures already
  682. // available to us (if we read this key from a keyring).
  683. if e.PrivateKey.PrivateKey != nil && !config.ReuseSignatures() {
  684. err = subkey.Sig.SignKey(subkey.PublicKey, e.PrivateKey, config)
  685. if err != nil {
  686. return
  687. }
  688. }
  689. if subkey.Revocation != nil {
  690. err = subkey.Revocation.Serialize(w)
  691. if err != nil {
  692. return
  693. }
  694. }
  695. err = subkey.Sig.Serialize(w)
  696. if err != nil {
  697. return
  698. }
  699. }
  700. return nil
  701. }
  702. // Serialize writes the public part of the given Entity to w. (No private
  703. // key material will be output).
  704. func (e *Entity) Serialize(w io.Writer) error {
  705. err := e.PrimaryKey.Serialize(w)
  706. if err != nil {
  707. return err
  708. }
  709. for _, ident := range e.Identities {
  710. err = ident.UserId.Serialize(w)
  711. if err != nil {
  712. return err
  713. }
  714. err = ident.SelfSignature.Serialize(w)
  715. if err != nil {
  716. return err
  717. }
  718. for _, sig := range ident.Signatures {
  719. err = sig.Serialize(w)
  720. if err != nil {
  721. return err
  722. }
  723. }
  724. }
  725. for _, subkey := range e.Subkeys {
  726. err = subkey.PublicKey.Serialize(w)
  727. if err != nil {
  728. return err
  729. }
  730. if subkey.Revocation != nil {
  731. err = subkey.Revocation.Serialize(w)
  732. if err != nil {
  733. return err
  734. }
  735. }
  736. err = subkey.Sig.Serialize(w)
  737. if err != nil {
  738. return err
  739. }
  740. }
  741. return nil
  742. }
  743. // SignIdentity adds a signature to e, from signer, attesting that identity is
  744. // associated with e. The provided identity must already be an element of
  745. // e.Identities and the private key of signer must have been decrypted if
  746. // necessary.
  747. // If config is nil, sensible defaults will be used.
  748. func (e *Entity) SignIdentity(identity string, signer *Entity, config *packet.Config) error {
  749. if signer.PrivateKey == nil {
  750. return errors.InvalidArgumentError("signing Entity must have a private key")
  751. }
  752. if signer.PrivateKey.Encrypted {
  753. return errors.InvalidArgumentError("signing Entity's private key must be decrypted")
  754. }
  755. ident, ok := e.Identities[identity]
  756. if !ok {
  757. return errors.InvalidArgumentError("given identity string not found in Entity")
  758. }
  759. sig := &packet.Signature{
  760. SigType: packet.SigTypeGenericCert,
  761. PubKeyAlgo: signer.PrivateKey.PubKeyAlgo,
  762. Hash: config.Hash(),
  763. CreationTime: config.Now(),
  764. IssuerKeyId: &signer.PrivateKey.KeyId,
  765. }
  766. if err := sig.SignUserId(identity, e.PrimaryKey, signer.PrivateKey, config); err != nil {
  767. return err
  768. }
  769. ident.Signatures = append(ident.Signatures, sig)
  770. return nil
  771. }
  772. // CopySubkeyRevocations copies subkey revocations from the src Entity over
  773. // to the receiver entity. We need this because `gpg --export-secret-key` does
  774. // not appear to output subkey revocations. In this case we need to manually
  775. // merge with the output of `gpg --export`.
  776. func (e *Entity) CopySubkeyRevocations(src *Entity) {
  777. m := make(map[[20]byte]*packet.Signature)
  778. for _, subkey := range src.Subkeys {
  779. if subkey.Revocation != nil {
  780. m[subkey.PublicKey.Fingerprint] = subkey.Revocation
  781. }
  782. }
  783. for i, subkey := range e.Subkeys {
  784. if r := m[subkey.PublicKey.Fingerprint]; r != nil {
  785. e.Subkeys[i].Revocation = r
  786. }
  787. }
  788. }
  789. // CheckDesignatedRevokers will try to confirm any of designated
  790. // revocation of entity. For this function to work, revocation
  791. // issuer's key should be found in keyring. First successfully
  792. // verified designated revocation is returned along with the key that
  793. // verified it.
  794. func FindVerifiedDesignatedRevoke(keyring KeyRing, entity *Entity) (*packet.Signature, *Key) {
  795. for _, sig := range entity.UnverifiedRevocations {
  796. if sig.IssuerKeyId == nil {
  797. continue
  798. }
  799. issuerKeyId := *sig.IssuerKeyId
  800. issuerFingerprint := sig.IssuerFingerprint
  801. keys := keyring.KeysByIdUsage(issuerKeyId, issuerFingerprint, packet.KeyFlagSign)
  802. if len(keys) == 0 {
  803. continue
  804. }
  805. for _, key := range keys {
  806. err := key.PublicKey.VerifyRevocationSignature(entity.PrimaryKey, sig)
  807. if err == nil {
  808. return sig, &key
  809. }
  810. }
  811. }
  812. return nil, nil
  813. }
上海开阖软件有限公司 沪ICP备12045867号-1