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.

keys.go 29KB

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