keys.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  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/rsa"
  7. "golang.org/x/crypto/openpgp/armor"
  8. "golang.org/x/crypto/openpgp/errors"
  9. "golang.org/x/crypto/openpgp/packet"
  10. "io"
  11. "time"
  12. )
  13. // PublicKeyType is the armor type for a PGP public key.
  14. var PublicKeyType = "PGP PUBLIC KEY BLOCK"
  15. // PrivateKeyType is the armor type for a PGP private key.
  16. var PrivateKeyType = "PGP PRIVATE KEY BLOCK"
  17. // An Entity represents the components of an OpenPGP key: a primary public key
  18. // (which must be a signing key), one or more identities claimed by that key,
  19. // and zero or more subkeys, which may be encryption keys.
  20. type Entity struct {
  21. PrimaryKey *packet.PublicKey
  22. PrivateKey *packet.PrivateKey
  23. Identities map[string]*Identity // indexed by Identity.Name
  24. Revocations []*packet.Signature
  25. Subkeys []Subkey
  26. }
  27. // An Identity represents an identity claimed by an Entity and zero or more
  28. // assertions by other entities about that claim.
  29. type Identity struct {
  30. Name string // by convention, has the form "Full Name (comment) <email@example.com>"
  31. UserId *packet.UserId
  32. SelfSignature *packet.Signature
  33. Signatures []*packet.Signature
  34. }
  35. // A Subkey is an additional public key in an Entity. Subkeys can be used for
  36. // encryption.
  37. type Subkey struct {
  38. PublicKey *packet.PublicKey
  39. PrivateKey *packet.PrivateKey
  40. Sig *packet.Signature
  41. }
  42. // A Key identifies a specific public key in an Entity. This is either the
  43. // Entity's primary key or a subkey.
  44. type Key struct {
  45. Entity *Entity
  46. PublicKey *packet.PublicKey
  47. PrivateKey *packet.PrivateKey
  48. SelfSignature *packet.Signature
  49. }
  50. // A KeyRing provides access to public and private keys.
  51. type KeyRing interface {
  52. // KeysById returns the set of keys that have the given key id.
  53. KeysById(id uint64) []Key
  54. // KeysByIdAndUsage returns the set of keys with the given id
  55. // that also meet the key usage given by requiredUsage.
  56. // The requiredUsage is expressed as the bitwise-OR of
  57. // packet.KeyFlag* values.
  58. KeysByIdUsage(id uint64, requiredUsage byte) []Key
  59. // DecryptionKeys returns all private keys that are valid for
  60. // decryption.
  61. DecryptionKeys() []Key
  62. }
  63. // primaryIdentity returns the Identity marked as primary or the first identity
  64. // if none are so marked.
  65. func (e *Entity) primaryIdentity() *Identity {
  66. var firstIdentity *Identity
  67. for _, ident := range e.Identities {
  68. if firstIdentity == nil {
  69. firstIdentity = ident
  70. }
  71. if ident.SelfSignature.IsPrimaryId != nil && *ident.SelfSignature.IsPrimaryId {
  72. return ident
  73. }
  74. }
  75. return firstIdentity
  76. }
  77. // encryptionKey returns the best candidate Key for encrypting a message to the
  78. // given Entity.
  79. func (e *Entity) encryptionKey(now time.Time) (Key, bool) {
  80. candidateSubkey := -1
  81. for i, subkey := range e.Subkeys {
  82. if subkey.Sig.FlagsValid &&
  83. subkey.Sig.FlagEncryptCommunications &&
  84. subkey.PublicKey.PubKeyAlgo.CanEncrypt() &&
  85. !subkey.Sig.KeyExpired(now) {
  86. candidateSubkey = i
  87. break
  88. }
  89. }
  90. if candidateSubkey != -1 {
  91. subkey := e.Subkeys[candidateSubkey]
  92. return Key{e, subkey.PublicKey, subkey.PrivateKey, subkey.Sig}, true
  93. }
  94. // If we don't have any candidate subkeys for encryption and
  95. // the primary key doesn't have any usage metadata then we
  96. // assume that the primary key is ok. Or, if the primary key is
  97. // marked as ok to encrypt to, then we can obviously use it.
  98. i := e.primaryIdentity()
  99. if !i.SelfSignature.FlagsValid || i.SelfSignature.FlagEncryptCommunications &&
  100. e.PrimaryKey.PubKeyAlgo.CanEncrypt() &&
  101. !i.SelfSignature.KeyExpired(now) {
  102. return Key{e, e.PrimaryKey, e.PrivateKey, i.SelfSignature}, true
  103. }
  104. // This Entity appears to be signing only.
  105. return Key{}, false
  106. }
  107. // signingKey return the best candidate Key for signing a message with this
  108. // Entity.
  109. func (e *Entity) signingKey(now time.Time) (Key, bool) {
  110. candidateSubkey := -1
  111. for i, subkey := range e.Subkeys {
  112. if subkey.Sig.FlagsValid &&
  113. subkey.Sig.FlagSign &&
  114. subkey.PublicKey.PubKeyAlgo.CanSign() &&
  115. !subkey.Sig.KeyExpired(now) {
  116. candidateSubkey = i
  117. break
  118. }
  119. }
  120. if candidateSubkey != -1 {
  121. subkey := e.Subkeys[candidateSubkey]
  122. return Key{e, subkey.PublicKey, subkey.PrivateKey, subkey.Sig}, true
  123. }
  124. // If we have no candidate subkey then we assume that it's ok to sign
  125. // with the primary key.
  126. i := e.primaryIdentity()
  127. if !i.SelfSignature.FlagsValid || i.SelfSignature.FlagSign &&
  128. !i.SelfSignature.KeyExpired(now) {
  129. return Key{e, e.PrimaryKey, e.PrivateKey, i.SelfSignature}, true
  130. }
  131. return Key{}, false
  132. }
  133. // An EntityList contains one or more Entities.
  134. type EntityList []*Entity
  135. // KeysById returns the set of keys that have the given key id.
  136. func (el EntityList) KeysById(id uint64) (keys []Key) {
  137. for _, e := range el {
  138. if e.PrimaryKey.KeyId == id {
  139. var selfSig *packet.Signature
  140. for _, ident := range e.Identities {
  141. if selfSig == nil {
  142. selfSig = ident.SelfSignature
  143. } else if ident.SelfSignature.IsPrimaryId != nil && *ident.SelfSignature.IsPrimaryId {
  144. selfSig = ident.SelfSignature
  145. break
  146. }
  147. }
  148. keys = append(keys, Key{e, e.PrimaryKey, e.PrivateKey, selfSig})
  149. }
  150. for _, subKey := range e.Subkeys {
  151. if subKey.PublicKey.KeyId == id {
  152. keys = append(keys, Key{e, subKey.PublicKey, subKey.PrivateKey, subKey.Sig})
  153. }
  154. }
  155. }
  156. return
  157. }
  158. // KeysByIdAndUsage returns the set of keys with the given id that also meet
  159. // the key usage given by requiredUsage. The requiredUsage is expressed as
  160. // the bitwise-OR of packet.KeyFlag* values.
  161. func (el EntityList) KeysByIdUsage(id uint64, requiredUsage byte) (keys []Key) {
  162. for _, key := range el.KeysById(id) {
  163. if len(key.Entity.Revocations) > 0 {
  164. continue
  165. }
  166. if key.SelfSignature.RevocationReason != nil {
  167. continue
  168. }
  169. if key.SelfSignature.FlagsValid && requiredUsage != 0 {
  170. var usage byte
  171. if key.SelfSignature.FlagCertify {
  172. usage |= packet.KeyFlagCertify
  173. }
  174. if key.SelfSignature.FlagSign {
  175. usage |= packet.KeyFlagSign
  176. }
  177. if key.SelfSignature.FlagEncryptCommunications {
  178. usage |= packet.KeyFlagEncryptCommunications
  179. }
  180. if key.SelfSignature.FlagEncryptStorage {
  181. usage |= packet.KeyFlagEncryptStorage
  182. }
  183. if usage&requiredUsage != requiredUsage {
  184. continue
  185. }
  186. }
  187. keys = append(keys, key)
  188. }
  189. return
  190. }
  191. // DecryptionKeys returns all private keys that are valid for decryption.
  192. func (el EntityList) DecryptionKeys() (keys []Key) {
  193. for _, e := range el {
  194. for _, subKey := range e.Subkeys {
  195. if subKey.PrivateKey != nil && (!subKey.Sig.FlagsValid || subKey.Sig.FlagEncryptStorage || subKey.Sig.FlagEncryptCommunications) {
  196. keys = append(keys, Key{e, subKey.PublicKey, subKey.PrivateKey, subKey.Sig})
  197. }
  198. }
  199. }
  200. return
  201. }
  202. // ReadArmoredKeyRing reads one or more public/private keys from an armor keyring file.
  203. func ReadArmoredKeyRing(r io.Reader) (EntityList, error) {
  204. block, err := armor.Decode(r)
  205. if err == io.EOF {
  206. return nil, errors.InvalidArgumentError("no armored data found")
  207. }
  208. if err != nil {
  209. return nil, err
  210. }
  211. if block.Type != PublicKeyType && block.Type != PrivateKeyType {
  212. return nil, errors.InvalidArgumentError("expected public or private key block, got: " + block.Type)
  213. }
  214. return ReadKeyRing(block.Body)
  215. }
  216. // ReadKeyRing reads one or more public/private keys. Unsupported keys are
  217. // ignored as long as at least a single valid key is found.
  218. func ReadKeyRing(r io.Reader) (el EntityList, err error) {
  219. packets := packet.NewReader(r)
  220. var lastUnsupportedError error
  221. for {
  222. var e *Entity
  223. e, err = ReadEntity(packets)
  224. if err != nil {
  225. // TODO: warn about skipped unsupported/unreadable keys
  226. if _, ok := err.(errors.UnsupportedError); ok {
  227. lastUnsupportedError = err
  228. err = readToNextPublicKey(packets)
  229. } else if _, ok := err.(errors.StructuralError); ok {
  230. // Skip unreadable, badly-formatted keys
  231. lastUnsupportedError = err
  232. err = readToNextPublicKey(packets)
  233. }
  234. if err == io.EOF {
  235. err = nil
  236. break
  237. }
  238. if err != nil {
  239. el = nil
  240. break
  241. }
  242. } else {
  243. el = append(el, e)
  244. }
  245. }
  246. if len(el) == 0 && err == nil {
  247. err = lastUnsupportedError
  248. }
  249. return
  250. }
  251. // readToNextPublicKey reads packets until the start of the entity and leaves
  252. // the first packet of the new entity in the Reader.
  253. func readToNextPublicKey(packets *packet.Reader) (err error) {
  254. var p packet.Packet
  255. for {
  256. p, err = packets.Next()
  257. if err == io.EOF {
  258. return
  259. } else if err != nil {
  260. if _, ok := err.(errors.UnsupportedError); ok {
  261. err = nil
  262. continue
  263. }
  264. return
  265. }
  266. if pk, ok := p.(*packet.PublicKey); ok && !pk.IsSubkey {
  267. packets.Unread(p)
  268. return
  269. }
  270. }
  271. panic("unreachable")
  272. }
  273. // ReadEntity reads an entity (public key, identities, subkeys etc) from the
  274. // given Reader.
  275. func ReadEntity(packets *packet.Reader) (*Entity, error) {
  276. e := new(Entity)
  277. e.Identities = make(map[string]*Identity)
  278. p, err := packets.Next()
  279. if err != nil {
  280. return nil, err
  281. }
  282. var ok bool
  283. if e.PrimaryKey, ok = p.(*packet.PublicKey); !ok {
  284. if e.PrivateKey, ok = p.(*packet.PrivateKey); !ok {
  285. packets.Unread(p)
  286. return nil, errors.StructuralError("first packet was not a public/private key")
  287. } else {
  288. e.PrimaryKey = &e.PrivateKey.PublicKey
  289. }
  290. }
  291. if !e.PrimaryKey.PubKeyAlgo.CanSign() {
  292. return nil, errors.StructuralError("primary key cannot be used for signatures")
  293. }
  294. var current *Identity
  295. var revocations []*packet.Signature
  296. EachPacket:
  297. for {
  298. p, err := packets.Next()
  299. if err == io.EOF {
  300. break
  301. } else if err != nil {
  302. return nil, err
  303. }
  304. switch pkt := p.(type) {
  305. case *packet.UserId:
  306. current = new(Identity)
  307. current.Name = pkt.Id
  308. current.UserId = pkt
  309. e.Identities[pkt.Id] = current
  310. for {
  311. p, err = packets.Next()
  312. if err == io.EOF {
  313. return nil, io.ErrUnexpectedEOF
  314. } else if err != nil {
  315. return nil, err
  316. }
  317. sig, ok := p.(*packet.Signature)
  318. if !ok {
  319. return nil, errors.StructuralError("user ID packet not followed by self-signature")
  320. }
  321. if (sig.SigType == packet.SigTypePositiveCert || sig.SigType == packet.SigTypeGenericCert) && sig.IssuerKeyId != nil && *sig.IssuerKeyId == e.PrimaryKey.KeyId {
  322. if err = e.PrimaryKey.VerifyUserIdSignature(pkt.Id, e.PrimaryKey, sig); err != nil {
  323. return nil, errors.StructuralError("user ID self-signature invalid: " + err.Error())
  324. }
  325. current.SelfSignature = sig
  326. break
  327. }
  328. current.Signatures = append(current.Signatures, sig)
  329. }
  330. case *packet.Signature:
  331. if pkt.SigType == packet.SigTypeKeyRevocation {
  332. revocations = append(revocations, pkt)
  333. } else if pkt.SigType == packet.SigTypeDirectSignature {
  334. // TODO: RFC4880 5.2.1 permits signatures
  335. // directly on keys (eg. to bind additional
  336. // revocation keys).
  337. } else if current == nil {
  338. return nil, errors.StructuralError("signature packet found before user id packet")
  339. } else {
  340. current.Signatures = append(current.Signatures, pkt)
  341. }
  342. case *packet.PrivateKey:
  343. if pkt.IsSubkey == false {
  344. packets.Unread(p)
  345. break EachPacket
  346. }
  347. err = addSubkey(e, packets, &pkt.PublicKey, pkt)
  348. if err != nil {
  349. return nil, err
  350. }
  351. case *packet.PublicKey:
  352. if pkt.IsSubkey == false {
  353. packets.Unread(p)
  354. break EachPacket
  355. }
  356. err = addSubkey(e, packets, pkt, nil)
  357. if err != nil {
  358. return nil, err
  359. }
  360. default:
  361. // we ignore unknown packets
  362. }
  363. }
  364. if len(e.Identities) == 0 {
  365. return nil, errors.StructuralError("entity without any identities")
  366. }
  367. for _, revocation := range revocations {
  368. err = e.PrimaryKey.VerifyRevocationSignature(revocation)
  369. if err == nil {
  370. e.Revocations = append(e.Revocations, revocation)
  371. } else {
  372. // TODO: RFC 4880 5.2.3.15 defines revocation keys.
  373. return nil, errors.StructuralError("revocation signature signed by alternate key")
  374. }
  375. }
  376. return e, nil
  377. }
  378. func addSubkey(e *Entity, packets *packet.Reader, pub *packet.PublicKey, priv *packet.PrivateKey) error {
  379. var subKey Subkey
  380. subKey.PublicKey = pub
  381. subKey.PrivateKey = priv
  382. p, err := packets.Next()
  383. if err == io.EOF {
  384. return io.ErrUnexpectedEOF
  385. }
  386. if err != nil {
  387. return errors.StructuralError("subkey signature invalid: " + err.Error())
  388. }
  389. var ok bool
  390. subKey.Sig, ok = p.(*packet.Signature)
  391. if !ok {
  392. return errors.StructuralError("subkey packet not followed by signature")
  393. }
  394. if subKey.Sig.SigType != packet.SigTypeSubkeyBinding && subKey.Sig.SigType != packet.SigTypeSubkeyRevocation {
  395. return errors.StructuralError("subkey signature with wrong type")
  396. }
  397. err = e.PrimaryKey.VerifyKeySignature(subKey.PublicKey, subKey.Sig)
  398. if err != nil {
  399. return errors.StructuralError("subkey signature invalid: " + err.Error())
  400. }
  401. e.Subkeys = append(e.Subkeys, subKey)
  402. return nil
  403. }
  404. const defaultRSAKeyBits = 2048
  405. // NewEntity returns an Entity that contains a fresh RSA/RSA keypair with a
  406. // single identity composed of the given full name, comment and email, any of
  407. // which may be empty but must not contain any of "()<>\x00".
  408. // If config is nil, sensible defaults will be used.
  409. func NewEntity(name, comment, email string, config *packet.Config) (*Entity, error) {
  410. currentTime := config.Now()
  411. uid := packet.NewUserId(name, comment, email)
  412. if uid == nil {
  413. return nil, errors.InvalidArgumentError("user id field contained invalid characters")
  414. }
  415. signingPriv, err := rsa.GenerateKey(config.Random(), defaultRSAKeyBits)
  416. if err != nil {
  417. return nil, err
  418. }
  419. encryptingPriv, err := rsa.GenerateKey(config.Random(), defaultRSAKeyBits)
  420. if err != nil {
  421. return nil, err
  422. }
  423. e := &Entity{
  424. PrimaryKey: packet.NewRSAPublicKey(currentTime, &signingPriv.PublicKey),
  425. PrivateKey: packet.NewRSAPrivateKey(currentTime, signingPriv),
  426. Identities: make(map[string]*Identity),
  427. }
  428. isPrimaryId := true
  429. e.Identities[uid.Id] = &Identity{
  430. Name: uid.Name,
  431. UserId: uid,
  432. SelfSignature: &packet.Signature{
  433. CreationTime: currentTime,
  434. SigType: packet.SigTypePositiveCert,
  435. PubKeyAlgo: packet.PubKeyAlgoRSA,
  436. Hash: config.Hash(),
  437. IsPrimaryId: &isPrimaryId,
  438. FlagsValid: true,
  439. FlagSign: true,
  440. FlagCertify: true,
  441. IssuerKeyId: &e.PrimaryKey.KeyId,
  442. },
  443. }
  444. e.Subkeys = make([]Subkey, 1)
  445. e.Subkeys[0] = Subkey{
  446. PublicKey: packet.NewRSAPublicKey(currentTime, &encryptingPriv.PublicKey),
  447. PrivateKey: packet.NewRSAPrivateKey(currentTime, encryptingPriv),
  448. Sig: &packet.Signature{
  449. CreationTime: currentTime,
  450. SigType: packet.SigTypeSubkeyBinding,
  451. PubKeyAlgo: packet.PubKeyAlgoRSA,
  452. Hash: config.Hash(),
  453. FlagsValid: true,
  454. FlagEncryptStorage: true,
  455. FlagEncryptCommunications: true,
  456. IssuerKeyId: &e.PrimaryKey.KeyId,
  457. },
  458. }
  459. e.Subkeys[0].PublicKey.IsSubkey = true
  460. e.Subkeys[0].PrivateKey.IsSubkey = true
  461. return e, nil
  462. }
  463. // SerializePrivate serializes an Entity, including private key material, to
  464. // the given Writer. For now, it must only be used on an Entity returned from
  465. // NewEntity.
  466. // If config is nil, sensible defaults will be used.
  467. func (e *Entity) SerializePrivate(w io.Writer, config *packet.Config) (err error) {
  468. err = e.PrivateKey.Serialize(w)
  469. if err != nil {
  470. return
  471. }
  472. for _, ident := range e.Identities {
  473. err = ident.UserId.Serialize(w)
  474. if err != nil {
  475. return
  476. }
  477. err = ident.SelfSignature.SignUserId(ident.UserId.Id, e.PrimaryKey, e.PrivateKey, config)
  478. if err != nil {
  479. return
  480. }
  481. err = ident.SelfSignature.Serialize(w)
  482. if err != nil {
  483. return
  484. }
  485. }
  486. for _, subkey := range e.Subkeys {
  487. err = subkey.PrivateKey.Serialize(w)
  488. if err != nil {
  489. return
  490. }
  491. err = subkey.Sig.SignKey(subkey.PublicKey, e.PrivateKey, config)
  492. if err != nil {
  493. return
  494. }
  495. err = subkey.Sig.Serialize(w)
  496. if err != nil {
  497. return
  498. }
  499. }
  500. return nil
  501. }
  502. // Serialize writes the public part of the given Entity to w. (No private
  503. // key material will be output).
  504. func (e *Entity) Serialize(w io.Writer) error {
  505. err := e.PrimaryKey.Serialize(w)
  506. if err != nil {
  507. return err
  508. }
  509. for _, ident := range e.Identities {
  510. err = ident.UserId.Serialize(w)
  511. if err != nil {
  512. return err
  513. }
  514. err = ident.SelfSignature.Serialize(w)
  515. if err != nil {
  516. return err
  517. }
  518. for _, sig := range ident.Signatures {
  519. err = sig.Serialize(w)
  520. if err != nil {
  521. return err
  522. }
  523. }
  524. }
  525. for _, subkey := range e.Subkeys {
  526. err = subkey.PublicKey.Serialize(w)
  527. if err != nil {
  528. return err
  529. }
  530. err = subkey.Sig.Serialize(w)
  531. if err != nil {
  532. return err
  533. }
  534. }
  535. return nil
  536. }
  537. // SignIdentity adds a signature to e, from signer, attesting that identity is
  538. // associated with e. The provided identity must already be an element of
  539. // e.Identities and the private key of signer must have been decrypted if
  540. // necessary.
  541. // If config is nil, sensible defaults will be used.
  542. func (e *Entity) SignIdentity(identity string, signer *Entity, config *packet.Config) error {
  543. if signer.PrivateKey == nil {
  544. return errors.InvalidArgumentError("signing Entity must have a private key")
  545. }
  546. if signer.PrivateKey.Encrypted {
  547. return errors.InvalidArgumentError("signing Entity's private key must be decrypted")
  548. }
  549. ident, ok := e.Identities[identity]
  550. if !ok {
  551. return errors.InvalidArgumentError("given identity string not found in Entity")
  552. }
  553. sig := &packet.Signature{
  554. SigType: packet.SigTypeGenericCert,
  555. PubKeyAlgo: signer.PrivateKey.PubKeyAlgo,
  556. Hash: config.Hash(),
  557. CreationTime: config.Now(),
  558. IssuerKeyId: &signer.PrivateKey.KeyId,
  559. }
  560. if err := sig.SignUserId(identity, e.PrimaryKey, signer.PrivateKey, config); err != nil {
  561. return err
  562. }
  563. ident.Signatures = append(ident.Signatures, sig)
  564. return nil
  565. }