keys.go 18 KB

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