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.

636 lines
18 KiB

  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. }
  290. e.PrimaryKey = &e.PrivateKey.PublicKey
  291. }
  292. if !e.PrimaryKey.PubKeyAlgo.CanSign() {
  293. return nil, errors.StructuralError("primary key cannot be used for signatures")
  294. }
  295. var current *Identity
  296. var revocations []*packet.Signature
  297. EachPacket:
  298. for {
  299. p, err := packets.Next()
  300. if err == io.EOF {
  301. break
  302. } else if err != nil {
  303. return nil, err
  304. }
  305. switch pkt := p.(type) {
  306. case *packet.UserId:
  307. current = new(Identity)
  308. current.Name = pkt.Id
  309. current.UserId = pkt
  310. e.Identities[pkt.Id] = current
  311. for {
  312. p, err = packets.Next()
  313. if err == io.EOF {
  314. return nil, io.ErrUnexpectedEOF
  315. } else if err != nil {
  316. return nil, err
  317. }
  318. sig, ok := p.(*packet.Signature)
  319. if !ok {
  320. return nil, errors.StructuralError("user ID packet not followed by self-signature")
  321. }
  322. if (sig.SigType == packet.SigTypePositiveCert || sig.SigType == packet.SigTypeGenericCert) && sig.IssuerKeyId != nil && *sig.IssuerKeyId == e.PrimaryKey.KeyId {
  323. if err = e.PrimaryKey.VerifyUserIdSignature(pkt.Id, e.PrimaryKey, sig); err != nil {
  324. return nil, errors.StructuralError("user ID self-signature invalid: " + err.Error())
  325. }
  326. current.SelfSignature = sig
  327. break
  328. }
  329. current.Signatures = append(current.Signatures, sig)
  330. }
  331. case *packet.Signature:
  332. if pkt.SigType == packet.SigTypeKeyRevocation {
  333. revocations = append(revocations, pkt)
  334. } else if pkt.SigType == packet.SigTypeDirectSignature {
  335. // TODO: RFC4880 5.2.1 permits signatures
  336. // directly on keys (eg. to bind additional
  337. // revocation keys).
  338. } else if current == nil {
  339. return nil, errors.StructuralError("signature packet found before user id packet")
  340. } else {
  341. current.Signatures = append(current.Signatures, pkt)
  342. }
  343. case *packet.PrivateKey:
  344. if pkt.IsSubkey == false {
  345. packets.Unread(p)
  346. break EachPacket
  347. }
  348. err = addSubkey(e, packets, &pkt.PublicKey, pkt)
  349. if err != nil {
  350. return nil, err
  351. }
  352. case *packet.PublicKey:
  353. if pkt.IsSubkey == false {
  354. packets.Unread(p)
  355. break EachPacket
  356. }
  357. err = addSubkey(e, packets, pkt, nil)
  358. if err != nil {
  359. return nil, err
  360. }
  361. default:
  362. // we ignore unknown packets
  363. }
  364. }
  365. if len(e.Identities) == 0 {
  366. return nil, errors.StructuralError("entity without any identities")
  367. }
  368. for _, revocation := range revocations {
  369. err = e.PrimaryKey.VerifyRevocationSignature(revocation)
  370. if err == nil {
  371. e.Revocations = append(e.Revocations, revocation)
  372. } else {
  373. // TODO: RFC 4880 5.2.3.15 defines revocation keys.
  374. return nil, errors.StructuralError("revocation signature signed by alternate key")
  375. }
  376. }
  377. return e, nil
  378. }
  379. func addSubkey(e *Entity, packets *packet.Reader, pub *packet.PublicKey, priv *packet.PrivateKey) error {
  380. var subKey Subkey
  381. subKey.PublicKey = pub
  382. subKey.PrivateKey = priv
  383. p, err := packets.Next()
  384. if err == io.EOF {
  385. return io.ErrUnexpectedEOF
  386. }
  387. if err != nil {
  388. return errors.StructuralError("subkey signature invalid: " + err.Error())
  389. }
  390. var ok bool
  391. subKey.Sig, ok = p.(*packet.Signature)
  392. if !ok {
  393. return errors.StructuralError("subkey packet not followed by signature")
  394. }
  395. if subKey.Sig.SigType != packet.SigTypeSubkeyBinding && subKey.Sig.SigType != packet.SigTypeSubkeyRevocation {
  396. return errors.StructuralError("subkey signature with wrong type")
  397. }
  398. err = e.PrimaryKey.VerifyKeySignature(subKey.PublicKey, subKey.Sig)
  399. if err != nil {
  400. return errors.StructuralError("subkey signature invalid: " + err.Error())
  401. }
  402. e.Subkeys = append(e.Subkeys, subKey)
  403. return nil
  404. }
  405. const defaultRSAKeyBits = 2048
  406. // NewEntity returns an Entity that contains a fresh RSA/RSA keypair with a
  407. // single identity composed of the given full name, comment and email, any of
  408. // which may be empty but must not contain any of "()<>\x00".
  409. // If config is nil, sensible defaults will be used.
  410. func NewEntity(name, comment, email string, config *packet.Config) (*Entity, error) {
  411. currentTime := config.Now()
  412. bits := defaultRSAKeyBits
  413. if config != nil && config.RSABits != 0 {
  414. bits = config.RSABits
  415. }
  416. uid := packet.NewUserId(name, comment, email)
  417. if uid == nil {
  418. return nil, errors.InvalidArgumentError("user id field contained invalid characters")
  419. }
  420. signingPriv, err := rsa.GenerateKey(config.Random(), bits)
  421. if err != nil {
  422. return nil, err
  423. }
  424. encryptingPriv, err := rsa.GenerateKey(config.Random(), bits)
  425. if err != nil {
  426. return nil, err
  427. }
  428. e := &Entity{
  429. PrimaryKey: packet.NewRSAPublicKey(currentTime, &signingPriv.PublicKey),
  430. PrivateKey: packet.NewRSAPrivateKey(currentTime, signingPriv),
  431. Identities: make(map[string]*Identity),
  432. }
  433. isPrimaryId := true
  434. e.Identities[uid.Id] = &Identity{
  435. Name: uid.Name,
  436. UserId: uid,
  437. SelfSignature: &packet.Signature{
  438. CreationTime: currentTime,
  439. SigType: packet.SigTypePositiveCert,
  440. PubKeyAlgo: packet.PubKeyAlgoRSA,
  441. Hash: config.Hash(),
  442. IsPrimaryId: &isPrimaryId,
  443. FlagsValid: true,
  444. FlagSign: true,
  445. FlagCertify: true,
  446. IssuerKeyId: &e.PrimaryKey.KeyId,
  447. },
  448. }
  449. // If the user passes in a DefaultHash via packet.Config,
  450. // set the PreferredHash for the SelfSignature.
  451. if config != nil && config.DefaultHash != 0 {
  452. e.Identities[uid.Id].SelfSignature.PreferredHash = []uint8{hashToHashId(config.DefaultHash)}
  453. }
  454. e.Subkeys = make([]Subkey, 1)
  455. e.Subkeys[0] = Subkey{
  456. PublicKey: packet.NewRSAPublicKey(currentTime, &encryptingPriv.PublicKey),
  457. PrivateKey: packet.NewRSAPrivateKey(currentTime, encryptingPriv),
  458. Sig: &packet.Signature{
  459. CreationTime: currentTime,
  460. SigType: packet.SigTypeSubkeyBinding,
  461. PubKeyAlgo: packet.PubKeyAlgoRSA,
  462. Hash: config.Hash(),
  463. FlagsValid: true,
  464. FlagEncryptStorage: true,
  465. FlagEncryptCommunications: true,
  466. IssuerKeyId: &e.PrimaryKey.KeyId,
  467. },
  468. }
  469. e.Subkeys[0].PublicKey.IsSubkey = true
  470. e.Subkeys[0].PrivateKey.IsSubkey = true
  471. return e, nil
  472. }
  473. // SerializePrivate serializes an Entity, including private key material, to
  474. // the given Writer. For now, it must only be used on an Entity returned from
  475. // NewEntity.
  476. // If config is nil, sensible defaults will be used.
  477. func (e *Entity) SerializePrivate(w io.Writer, config *packet.Config) (err error) {
  478. err = e.PrivateKey.Serialize(w)
  479. if err != nil {
  480. return
  481. }
  482. for _, ident := range e.Identities {
  483. err = ident.UserId.Serialize(w)
  484. if err != nil {
  485. return
  486. }
  487. err = ident.SelfSignature.SignUserId(ident.UserId.Id, e.PrimaryKey, e.PrivateKey, config)
  488. if err != nil {
  489. return
  490. }
  491. err = ident.SelfSignature.Serialize(w)
  492. if err != nil {
  493. return
  494. }
  495. }
  496. for _, subkey := range e.Subkeys {
  497. err = subkey.PrivateKey.Serialize(w)
  498. if err != nil {
  499. return
  500. }
  501. err = subkey.Sig.SignKey(subkey.PublicKey, e.PrivateKey, config)
  502. if err != nil {
  503. return
  504. }
  505. err = subkey.Sig.Serialize(w)
  506. if err != nil {
  507. return
  508. }
  509. }
  510. return nil
  511. }
  512. // Serialize writes the public part of the given Entity to w. (No private
  513. // key material will be output).
  514. func (e *Entity) Serialize(w io.Writer) error {
  515. err := e.PrimaryKey.Serialize(w)
  516. if err != nil {
  517. return err
  518. }
  519. for _, ident := range e.Identities {
  520. err = ident.UserId.Serialize(w)
  521. if err != nil {
  522. return err
  523. }
  524. err = ident.SelfSignature.Serialize(w)
  525. if err != nil {
  526. return err
  527. }
  528. for _, sig := range ident.Signatures {
  529. err = sig.Serialize(w)
  530. if err != nil {
  531. return err
  532. }
  533. }
  534. }
  535. for _, subkey := range e.Subkeys {
  536. err = subkey.PublicKey.Serialize(w)
  537. if err != nil {
  538. return err
  539. }
  540. err = subkey.Sig.Serialize(w)
  541. if err != nil {
  542. return err
  543. }
  544. }
  545. return nil
  546. }
  547. // SignIdentity adds a signature to e, from signer, attesting that identity is
  548. // associated with e. The provided identity must already be an element of
  549. // e.Identities and the private key of signer must have been decrypted if
  550. // necessary.
  551. // If config is nil, sensible defaults will be used.
  552. func (e *Entity) SignIdentity(identity string, signer *Entity, config *packet.Config) error {
  553. if signer.PrivateKey == nil {
  554. return errors.InvalidArgumentError("signing Entity must have a private key")
  555. }
  556. if signer.PrivateKey.Encrypted {
  557. return errors.InvalidArgumentError("signing Entity's private key must be decrypted")
  558. }
  559. ident, ok := e.Identities[identity]
  560. if !ok {
  561. return errors.InvalidArgumentError("given identity string not found in Entity")
  562. }
  563. sig := &packet.Signature{
  564. SigType: packet.SigTypeGenericCert,
  565. PubKeyAlgo: signer.PrivateKey.PubKeyAlgo,
  566. Hash: config.Hash(),
  567. CreationTime: config.Now(),
  568. IssuerKeyId: &signer.PrivateKey.KeyId,
  569. }
  570. if err := sig.SignUserId(identity, e.PrimaryKey, signer.PrivateKey, config); err != nil {
  571. return err
  572. }
  573. ident.Signatures = append(ident.Signatures, sig)
  574. return nil
  575. }