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.
 
 
 

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