Debian Codegraph @

openpgp/keys.go

raw
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
5 package openpgp
6
7 import (
8 goerrors "errors"
9 "fmt"
10 "io"
11 "time"
12
13 "github.com/ProtonMail/go-crypto/openpgp/armor"
14 "github.com/ProtonMail/go-crypto/openpgp/errors"
15 "github.com/ProtonMail/go-crypto/openpgp/packet"
16 )
17
18 // PublicKeyType is the armor type for a PGP public key.
19 var PublicKeyType = "PGP PUBLIC KEY BLOCK"
20
21 // PrivateKeyType is the armor type for a PGP private key.
22 var PrivateKeyType = "PGP PRIVATE KEY BLOCK"
23
24 // An Entity represents the components of an OpenPGP key: a primary public key
25 // (which must be a signing key), one or more identities claimed by that key,
26 // and zero or more subkeys, which may be encryption keys.
27 type Entity struct {
28 PrimaryKey *packet.PublicKey
29 PrivateKey *packet.PrivateKey
30 Identities map[string]*Identity // indexed by Identity.Name
31 Revocations []*packet.Signature
32 Subkeys []Subkey
33 SelfSignature *packet.Signature // Direct-key self signature of the PrimaryKey (contains primary key properties in v6)
34 Signatures []*packet.Signature // all (potentially unverified) self-signatures, revocations, and third-party signatures
35 }
36
37 // An Identity represents an identity claimed by an Entity and zero or more
38 // assertions by other entities about that claim.
39 type Identity struct {
40 Name string // by convention, has the form "Full Name (comment) <[email protected]>"
41 UserId *packet.UserId
42 SelfSignature *packet.Signature
43 Revocations []*packet.Signature
44 Signatures []*packet.Signature // all (potentially unverified) self-signatures, revocations, and third-party signatures
45 }
46
47 // A Subkey is an additional public key in an Entity. Subkeys can be used for
48 // encryption.
49 type Subkey struct {
50 PublicKey *packet.PublicKey
51 PrivateKey *packet.PrivateKey
52 Sig *packet.Signature
53 Revocations []*packet.Signature
54 }
55
56 // A Key identifies a specific public key in an Entity. This is either the
57 // Entity's primary key or a subkey.
58 type Key struct {
59 Entity *Entity
60 PublicKey *packet.PublicKey
61 PrivateKey *packet.PrivateKey
62 SelfSignature *packet.Signature
63 Revocations []*packet.Signature
64 }
65
66 // A KeyRing provides access to public and private keys.
67 type KeyRing interface {
68 // KeysById returns the set of keys that have the given key id.
69 KeysById(id uint64) []Key
70 // KeysByIdAndUsage returns the set of keys with the given id
71 // that also meet the key usage given by requiredUsage.
72 // The requiredUsage is expressed as the bitwise-OR of
73 // packet.KeyFlag* values.
74 KeysByIdUsage(id uint64, requiredUsage byte) []Key
75 // DecryptionKeys returns all private keys that are valid for
76 // decryption.
77 DecryptionKeys() []Key
78 }
79
80 // PrimaryIdentity returns an Identity, preferring non-revoked identities,
81 // identities marked as primary, or the latest-created identity, in that order.
82 func (e *Entity) PrimaryIdentity() *Identity {
83 var primaryIdentity *Identity
84 for _, ident := range e.Identities {
85 if shouldPreferIdentity(primaryIdentity, ident) {
86 primaryIdentity = ident
87 }
88 }
89 return primaryIdentity
90 }
91
92 func shouldPreferIdentity(existingId, potentialNewId *Identity) bool {
93 if existingId == nil {
94 return true
95 }
96
97 if len(existingId.Revocations) > len(potentialNewId.Revocations) {
98 return true
99 }
100
101 if len(existingId.Revocations) < len(potentialNewId.Revocations) {
102 return false
103 }
104
105 if existingId.SelfSignature == nil {
106 return true
107 }
108
109 if potentialNewId.SelfSignature == nil {
110 return false
111 }
112
113 if existingId.SelfSignature.IsPrimaryId != nil && *existingId.SelfSignature.IsPrimaryId &&
114 !(potentialNewId.SelfSignature.IsPrimaryId != nil && *potentialNewId.SelfSignature.IsPrimaryId) {
115 return false
116 }
117
118 if !(existingId.SelfSignature.IsPrimaryId != nil && *existingId.SelfSignature.IsPrimaryId) &&
119 potentialNewId.SelfSignature.IsPrimaryId != nil && *potentialNewId.SelfSignature.IsPrimaryId {
120 return true
121 }
122
123 return potentialNewId.SelfSignature.CreationTime.After(existingId.SelfSignature.CreationTime)
124 }
125
126 // EncryptionKey returns the best candidate Key for encrypting a message to the
127 // given Entity.
128 func (e *Entity) EncryptionKey(now time.Time) (Key, bool) {
129 // Fail to find any encryption key if the...
130 primarySelfSignature, primaryIdentity := e.PrimarySelfSignature()
131 if primarySelfSignature == nil || // no self-signature found
132 e.PrimaryKey.KeyExpired(primarySelfSignature, now) || // primary key has expired
133 e.Revoked(now) || // primary key has been revoked
134 primarySelfSignature.SigExpired(now) || // user ID or or direct self-signature has expired
135 (primaryIdentity != nil && primaryIdentity.Revoked(now)) { // user ID has been revoked (for v4 keys)
136 return Key{}, false
137 }
138
139 // Iterate the keys to find the newest, unexpired one
140 candidateSubkey := -1
141 var maxTime time.Time
142 for i, subkey := range e.Subkeys {
143 if subkey.Sig.FlagsValid &&
144 subkey.Sig.FlagEncryptCommunications &&
145 subkey.PublicKey.PubKeyAlgo.CanEncrypt() &&
146 !subkey.PublicKey.KeyExpired(subkey.Sig, now) &&
147 !subkey.Sig.SigExpired(now) &&
148 !subkey.Revoked(now) &&
149 (maxTime.IsZero() ||
150 subkey.Sig.CreationTime.After(maxTime) ||
151 (subkey.Sig.CreationTime.Equal(maxTime) && subkey.IsPQ())) {
152 candidateSubkey = i
153 maxTime = subkey.Sig.CreationTime
154 }
155 }
156
157 if candidateSubkey != -1 {
158 subkey := e.Subkeys[candidateSubkey]
159 return Key{e, subkey.PublicKey, subkey.PrivateKey, subkey.Sig, subkey.Revocations}, true
160 }
161
162 // If we don't have any subkeys for encryption and the primary key
163 // is marked as OK to encrypt with, then we can use it.
164 if primarySelfSignature.FlagsValid && primarySelfSignature.FlagEncryptCommunications &&
165 e.PrimaryKey.PubKeyAlgo.CanEncrypt() {
166 return Key{e, e.PrimaryKey, e.PrivateKey, primarySelfSignature, e.Revocations}, true
167 }
168
169 return Key{}, false
170 }
171
172 // CertificationKey return the best candidate Key for certifying a key with this
173 // Entity.
174 func (e *Entity) CertificationKey(now time.Time) (Key, bool) {
175 return e.CertificationKeyById(now, 0)
176 }
177
178 // CertificationKeyById return the Key for key certification with this
179 // Entity and keyID.
180 func (e *Entity) CertificationKeyById(now time.Time, id uint64) (Key, bool) {
181 return e.signingKeyByIdUsage(now, id, packet.KeyFlagCertify)
182 }
183
184 // SigningKey return the best candidate Key for signing a message with this
185 // Entity.
186 func (e *Entity) SigningKey(now time.Time) (Key, bool) {
187 return e.SigningKeyById(now, 0)
188 }
189
190 // SigningKeyById return the Key for signing a message with this
191 // Entity and keyID.
192 func (e *Entity) SigningKeyById(now time.Time, id uint64) (Key, bool) {
193 return e.signingKeyByIdUsage(now, id, packet.KeyFlagSign)
194 }
195
196 func (e *Entity) signingKeyByIdUsage(now time.Time, id uint64, flags int) (Key, bool) {
197 // Fail to find any signing key if the...
198 primarySelfSignature, primaryIdentity := e.PrimarySelfSignature()
199 if primarySelfSignature == nil || // no self-signature found
200 e.PrimaryKey.KeyExpired(primarySelfSignature, now) || // primary key has expired
201 e.Revoked(now) || // primary key has been revoked
202 primarySelfSignature.SigExpired(now) || // user ID or direct self-signature has expired
203 (primaryIdentity != nil && primaryIdentity.Revoked(now)) { // user ID has been revoked (for v4 keys)
204 return Key{}, false
205 }
206
207 // Iterate the keys to find the newest, unexpired one
208 candidateSubkey := -1
209 var maxTime time.Time
210 for idx, subkey := range e.Subkeys {
211 if subkey.Sig.FlagsValid &&
212 (flags&packet.KeyFlagCertify == 0 || subkey.Sig.FlagCertify) &&
213 (flags&packet.KeyFlagSign == 0 || subkey.Sig.FlagSign) &&
214 subkey.PublicKey.PubKeyAlgo.CanSign() &&
215 !subkey.PublicKey.KeyExpired(subkey.Sig, now) &&
216 !subkey.Sig.SigExpired(now) &&
217 !subkey.Revoked(now) &&
218 (maxTime.IsZero() ||
219 subkey.Sig.CreationTime.After(maxTime) ||
220 (subkey.Sig.CreationTime.Equal(maxTime) && subkey.IsPQ())) &&
221 (id == 0 || subkey.PublicKey.KeyId == id) {
222 candidateSubkey = idx
223 maxTime = subkey.Sig.CreationTime
224 }
225 }
226
227 if candidateSubkey != -1 {
228 subkey := e.Subkeys[candidateSubkey]
229 return Key{e, subkey.PublicKey, subkey.PrivateKey, subkey.Sig, subkey.Revocations}, true
230 }
231
232 // If we don't have any subkeys for signing and the primary key
233 // is marked as OK to sign with, then we can use it.
234 if primarySelfSignature.FlagsValid &&
235 (flags&packet.KeyFlagCertify == 0 || primarySelfSignature.FlagCertify) &&
236 (flags&packet.KeyFlagSign == 0 || primarySelfSignature.FlagSign) &&
237 e.PrimaryKey.PubKeyAlgo.CanSign() &&
238 (id == 0 || e.PrimaryKey.KeyId == id) {
239 return Key{e, e.PrimaryKey, e.PrivateKey, primarySelfSignature, e.Revocations}, true
240 }
241
242 // No keys with a valid Signing Flag or no keys matched the id passed in
243 return Key{}, false
244 }
245
246 func revoked(revocations []*packet.Signature, now time.Time) bool {
247 for _, revocation := range revocations {
248 if revocation.RevocationReason != nil && *revocation.RevocationReason == packet.KeyCompromised {
249 // If the key is compromised, the key is considered revoked even before the revocation date.
250 return true
251 }
252 if !revocation.SigExpired(now) {
253 return true
254 }
255 }
256 return false
257 }
258
259 // Revoked returns whether the entity has any direct key revocation signatures.
260 // Note that third-party revocation signatures are not supported.
261 // Note also that Identity and Subkey revocation should be checked separately.
262 func (e *Entity) Revoked(now time.Time) bool {
263 return revoked(e.Revocations, now)
264 }
265
266 // EncryptPrivateKeys encrypts all non-encrypted keys in the entity with the same key
267 // derived from the provided passphrase. Public keys and dummy keys are ignored,
268 // and don't cause an error to be returned.
269 func (e *Entity) EncryptPrivateKeys(passphrase []byte, config *packet.Config) error {
270 var keysToEncrypt []*packet.PrivateKey
271 // Add entity private key to encrypt.
272 if e.PrivateKey != nil && !e.PrivateKey.Dummy() && !e.PrivateKey.Encrypted {
273 keysToEncrypt = append(keysToEncrypt, e.PrivateKey)
274 }
275
276 // Add subkeys to encrypt.
277 for _, sub := range e.Subkeys {
278 if sub.PrivateKey != nil && !sub.PrivateKey.Dummy() && !sub.PrivateKey.Encrypted {
279 keysToEncrypt = append(keysToEncrypt, sub.PrivateKey)
280 }
281 }
282 return packet.EncryptPrivateKeys(keysToEncrypt, passphrase, config)
283 }
284
285 // DecryptPrivateKeys decrypts all encrypted keys in the entity with the given passphrase.
286 // Avoids recomputation of similar s2k key derivations. Public keys and dummy keys are ignored,
287 // and don't cause an error to be returned.
288 func (e *Entity) DecryptPrivateKeys(passphrase []byte) error {
289 var keysToDecrypt []*packet.PrivateKey
290 // Add entity private key to decrypt.
291 if e.PrivateKey != nil && !e.PrivateKey.Dummy() && e.PrivateKey.Encrypted {
292 keysToDecrypt = append(keysToDecrypt, e.PrivateKey)
293 }
294
295 // Add subkeys to decrypt.
296 for _, sub := range e.Subkeys {
297 if sub.PrivateKey != nil && !sub.PrivateKey.Dummy() && sub.PrivateKey.Encrypted {
298 keysToDecrypt = append(keysToDecrypt, sub.PrivateKey)
299 }
300 }
301 return packet.DecryptPrivateKeys(keysToDecrypt, passphrase)
302 }
303
304 // Revoked returns whether the identity has been revoked by a self-signature.
305 // Note that third-party revocation signatures are not supported.
306 func (i *Identity) Revoked(now time.Time) bool {
307 return revoked(i.Revocations, now)
308 }
309
310 // Revoked returns whether the subkey has been revoked by a self-signature.
311 // Note that third-party revocation signatures are not supported.
312 func (s *Subkey) Revoked(now time.Time) bool {
313 return revoked(s.Revocations, now)
314 }
315
316 // IsPQ returns true if the algorithm is Post-Quantum safe.
317 func (s *Subkey) IsPQ() bool {
318 return s.PublicKey.IsPQ()
319 }
320
321 // Revoked returns whether the key or subkey has been revoked by a self-signature.
322 // Note that third-party revocation signatures are not supported.
323 // Note also that Identity revocation should be checked separately.
324 // Normally, it's not necessary to call this function, except on keys returned by
325 // KeysById or KeysByIdUsage.
326 func (key *Key) Revoked(now time.Time) bool {
327 return revoked(key.Revocations, now)
328 }
329
330 // An EntityList contains one or more Entities.
331 type EntityList []*Entity
332
333 // KeysById returns the set of keys that have the given key id.
334 func (el EntityList) KeysById(id uint64) (keys []Key) {
335 for _, e := range el {
336 if e.PrimaryKey.KeyId == id {
337 selfSig, _ := e.PrimarySelfSignature()
338 keys = append(keys, Key{e, e.PrimaryKey, e.PrivateKey, selfSig, e.Revocations})
339 }
340
341 for _, subKey := range e.Subkeys {
342 if subKey.PublicKey.KeyId == id {
343 keys = append(keys, Key{e, subKey.PublicKey, subKey.PrivateKey, subKey.Sig, subKey.Revocations})
344 }
345 }
346 }
347 return
348 }
349
350 // KeysByIdAndUsage returns the set of keys with the given id that also meet
351 // the key usage given by requiredUsage. The requiredUsage is expressed as
352 // the bitwise-OR of packet.KeyFlag* values.
353 func (el EntityList) KeysByIdUsage(id uint64, requiredUsage byte) (keys []Key) {
354 for _, key := range el.KeysById(id) {
355 if requiredUsage != 0 {
356 if key.SelfSignature == nil || !key.SelfSignature.FlagsValid {
357 continue
358 }
359
360 var usage byte
361 if key.SelfSignature.FlagCertify {
362 usage |= packet.KeyFlagCertify
363 }
364 if key.SelfSignature.FlagSign {
365 usage |= packet.KeyFlagSign
366 }
367 if key.SelfSignature.FlagEncryptCommunications {
368 usage |= packet.KeyFlagEncryptCommunications
369 }
370 if key.SelfSignature.FlagEncryptStorage {
371 usage |= packet.KeyFlagEncryptStorage
372 }
373 if usage&requiredUsage != requiredUsage {
374 continue
375 }
376 }
377
378 keys = append(keys, key)
379 }
380 return
381 }
382
383 // DecryptionKeys returns all private keys that are valid for decryption.
384 func (el EntityList) DecryptionKeys() (keys []Key) {
385 for _, e := range el {
386 for _, subKey := range e.Subkeys {
387 if subKey.PrivateKey != nil && subKey.Sig.FlagsValid && (subKey.Sig.FlagEncryptStorage || subKey.Sig.FlagEncryptCommunications) {
388 keys = append(keys, Key{e, subKey.PublicKey, subKey.PrivateKey, subKey.Sig, subKey.Revocations})
389 }
390 }
391 }
392 return
393 }
394
395 // ReadArmoredKeyRing reads one or more public/private keys from an armor keyring file.
396 func ReadArmoredKeyRing(r io.Reader) (EntityList, error) {
397 block, err := armor.Decode(r)
398 if err == io.EOF {
399 return nil, errors.InvalidArgumentError("no armored data found")
400 }
401 if err != nil {
402 return nil, err
403 }
404 if block.Type != PublicKeyType && block.Type != PrivateKeyType {
405 return nil, errors.InvalidArgumentError("expected public or private key block, got: " + block.Type)
406 }
407
408 return ReadKeyRing(block.Body)
409 }
410
411 // ReadKeyRing reads one or more public/private keys. Unsupported keys are
412 // ignored as long as at least a single valid key is found.
413 func ReadKeyRing(r io.Reader) (el EntityList, err error) {
414 packets := packet.NewReader(r)
415 var lastUnsupportedError error
416
417 for {
418 var e *Entity
419 e, err = ReadEntity(packets)
420 if err != nil {
421 // TODO: warn about skipped unsupported/unreadable keys
422 if _, ok := err.(errors.UnsupportedError); ok {
423 lastUnsupportedError = err
424 err = readToNextPublicKey(packets)
425 } else if _, ok := err.(errors.StructuralError); ok {
426 // Skip unreadable, badly-formatted keys
427 lastUnsupportedError = err
428 err = readToNextPublicKey(packets)
429 }
430 if err == io.EOF {
431 err = nil
432 break
433 }
434 if err != nil {
435 el = nil
436 break
437 }
438 } else {
439 el = append(el, e)
440 }
441 }
442
443 if len(el) == 0 && err == nil {
444 err = lastUnsupportedError
445 }
446 return
447 }
448
449 // readToNextPublicKey reads packets until the start of the entity and leaves
450 // the first packet of the new entity in the Reader.
451 func readToNextPublicKey(packets *packet.Reader) (err error) {
452 var p packet.Packet
453 for {
454 p, err = packets.Next()
455 if err == io.EOF {
456 return
457 } else if err != nil {
458 if _, ok := err.(errors.UnsupportedError); ok {
459 continue
460 }
461 return
462 }
463
464 if pk, ok := p.(*packet.PublicKey); ok && !pk.IsSubkey {
465 packets.Unread(p)
466 return
467 }
468 }
469 }
470
471 // ReadEntity reads an entity (public key, identities, subkeys etc) from the
472 // given Reader.
473 func ReadEntity(packets *packet.Reader) (*Entity, error) {
474 e := new(Entity)
475 e.Identities = make(map[string]*Identity)
476
477 p, err := packets.Next()
478 if err != nil {
479 return nil, err
480 }
481
482 var ok bool
483 if e.PrimaryKey, ok = p.(*packet.PublicKey); !ok {
484 if e.PrivateKey, ok = p.(*packet.PrivateKey); !ok {
485 packets.Unread(p)
486 return nil, errors.StructuralError("first packet was not a public/private key")
487 }
488 e.PrimaryKey = &e.PrivateKey.PublicKey
489 }
490
491 if !e.PrimaryKey.PubKeyAlgo.CanSign() {
492 return nil, errors.StructuralError("primary key cannot be used for signatures")
493 }
494
495 var revocations []*packet.Signature
496 var directSignatures []*packet.Signature
497 EachPacket:
498 for {
499 p, err := packets.Next()
500 if err == io.EOF {
501 break
502 } else if err != nil {
503 return nil, err
504 }
505
506 switch pkt := p.(type) {
507 case *packet.UserId:
508 if err := addUserID(e, packets, pkt); err != nil {
509 return nil, err
510 }
511 case *packet.Signature:
512 if pkt.SigType == packet.SigTypeKeyRevocation {
513 revocations = append(revocations, pkt)
514 } else if pkt.SigType == packet.SigTypeDirectSignature {
515 directSignatures = append(directSignatures, pkt)
516 }
517 // Else, ignoring the signature as it does not follow anything
518 // we would know to attach it to.
519 case *packet.PrivateKey:
520 if !pkt.IsSubkey {
521 packets.Unread(p)
522 break EachPacket
523 }
524 err = addSubkey(e, packets, &pkt.PublicKey, pkt)
525 if err != nil {
526 return nil, err
527 }
528 case *packet.PublicKey:
529 if !pkt.IsSubkey {
530 packets.Unread(p)
531 break EachPacket
532 }
533 err = addSubkey(e, packets, pkt, nil)
534 if err != nil {
535 return nil, err
536 }
537 default:
538 // we ignore unknown packets.
539 }
540 }
541
542 if len(e.Identities) == 0 && e.PrimaryKey.Version < 6 {
543 return nil, errors.StructuralError(fmt.Sprintf("v%d entity without any identities", e.PrimaryKey.Version))
544 }
545
546 // An implementation MUST ensure that a valid direct-key signature is present before using a v6 key.
547 if e.PrimaryKey.Version == 6 {
548 if len(directSignatures) == 0 {
549 return nil, errors.StructuralError("v6 entity without a valid direct-key signature")
550 }
551 // Select main direct key signature.
552 var mainDirectKeySelfSignature *packet.Signature
553 for _, directSignature := range directSignatures {
554 if directSignature.SigType == packet.SigTypeDirectSignature &&
555 directSignature.CheckKeyIdOrFingerprint(e.PrimaryKey) &&
556 (mainDirectKeySelfSignature == nil ||
557 directSignature.CreationTime.After(mainDirectKeySelfSignature.CreationTime)) {
558 mainDirectKeySelfSignature = directSignature
559 }
560 }
561 if mainDirectKeySelfSignature == nil {
562 return nil, errors.StructuralError("no valid direct-key self-signature for v6 primary key found")
563 }
564 // Check that the main self-signature is valid.
565 err = e.PrimaryKey.VerifyDirectKeySignature(mainDirectKeySelfSignature)
566 if err != nil {
567 return nil, errors.StructuralError("invalid direct-key self-signature for v6 primary key")
568 }
569 e.SelfSignature = mainDirectKeySelfSignature
570 e.Signatures = directSignatures
571 }
572
573 for _, revocation := range revocations {
574 err = e.PrimaryKey.VerifyRevocationSignature(revocation)
575 if err == nil {
576 e.Revocations = append(e.Revocations, revocation)
577 } else {
578 // TODO: RFC 4880 5.2.3.15 defines revocation keys.
579 return nil, errors.StructuralError("revocation signature signed by alternate key")
580 }
581 }
582
583 return e, nil
584 }
585
586 func addUserID(e *Entity, packets *packet.Reader, pkt *packet.UserId) error {
587 // Make a new Identity object, that we might wind up throwing away.
588 // We'll only add it if we get a valid self-signature over this
589 // userID.
590 identity := new(Identity)
591 identity.Name = pkt.Id
592 identity.UserId = pkt
593
594 for {
595 p, err := packets.Next()
596 if err == io.EOF {
597 break
598 } else if err != nil {
599 return err
600 }
601
602 sig, ok := p.(*packet.Signature)
603 if !ok {
604 packets.Unread(p)
605 break
606 }
607
608 if sig.SigType != packet.SigTypeGenericCert &&
609 sig.SigType != packet.SigTypePersonaCert &&
610 sig.SigType != packet.SigTypeCasualCert &&
611 sig.SigType != packet.SigTypePositiveCert &&
612 sig.SigType != packet.SigTypeCertificationRevocation {
613 return errors.StructuralError("user ID signature with wrong type")
614 }
615
616 if sig.CheckKeyIdOrFingerprint(e.PrimaryKey) {
617 if err = e.PrimaryKey.VerifyUserIdSignature(pkt.Id, e.PrimaryKey, sig); err != nil {
618 return errors.StructuralError("user ID self-signature invalid: " + err.Error())
619 }
620 if sig.SigType == packet.SigTypeCertificationRevocation {
621 identity.Revocations = append(identity.Revocations, sig)
622 } else if identity.SelfSignature == nil || sig.CreationTime.After(identity.SelfSignature.CreationTime) {
623 identity.SelfSignature = sig
624 }
625 identity.Signatures = append(identity.Signatures, sig)
626 e.Identities[pkt.Id] = identity
627 } else {
628 identity.Signatures = append(identity.Signatures, sig)
629 }
630 }
631
632 return nil
633 }
634
635 func addSubkey(e *Entity, packets *packet.Reader, pub *packet.PublicKey, priv *packet.PrivateKey) error {
636 var subKey Subkey
637 subKey.PublicKey = pub
638 subKey.PrivateKey = priv
639
640 for {
641 p, err := packets.Next()
642 if err == io.EOF {
643 break
644 } else if err != nil {
645 return errors.StructuralError("subkey signature invalid: " + err.Error())
646 }
647
648 sig, ok := p.(*packet.Signature)
649 if !ok {
650 packets.Unread(p)
651 break
652 }
653
654 if sig.SigType != packet.SigTypeSubkeyBinding && sig.SigType != packet.SigTypeSubkeyRevocation {
655 return errors.StructuralError("subkey signature with wrong type")
656 }
657
658 if err := e.PrimaryKey.VerifyKeySignature(subKey.PublicKey, sig); err != nil {
659 return errors.StructuralError("subkey signature invalid: " + err.Error())
660 }
661
662 switch sig.SigType {
663 case packet.SigTypeSubkeyRevocation:
664 subKey.Revocations = append(subKey.Revocations, sig)
665 case packet.SigTypeSubkeyBinding:
666 if subKey.Sig == nil || sig.CreationTime.After(subKey.Sig.CreationTime) {
667 subKey.Sig = sig
668 }
669 }
670 }
671
672 if subKey.Sig == nil {
673 return errors.StructuralError("subkey packet not followed by signature")
674 }
675
676 e.Subkeys = append(e.Subkeys, subKey)
677
678 return nil
679 }
680
681 // SerializePrivate serializes an Entity, including private key material, but
682 // excluding signatures from other entities, to the given Writer.
683 // Identities and subkeys are re-signed in case they changed since NewEntry.
684 // If config is nil, sensible defaults will be used.
685 func (e *Entity) SerializePrivate(w io.Writer, config *packet.Config) (err error) {
686 if e.PrivateKey.Dummy() {
687 return errors.ErrDummyPrivateKey("dummy private key cannot re-sign identities")
688 }
689 return e.serializePrivate(w, config, true)
690 }
691
692 // SerializePrivateWithoutSigning serializes an Entity, including private key
693 // material, but excluding signatures from other entities, to the given Writer.
694 // Self-signatures of identities and subkeys are not re-signed. This is useful
695 // when serializing GNU dummy keys, among other things.
696 // If config is nil, sensible defaults will be used.
697 func (e *Entity) SerializePrivateWithoutSigning(w io.Writer, config *packet.Config) (err error) {
698 return e.serializePrivate(w, config, false)
699 }
700
701 func (e *Entity) serializePrivate(w io.Writer, config *packet.Config, reSign bool) (err error) {
702 if e.PrivateKey == nil {
703 return goerrors.New("openpgp: private key is missing")
704 }
705 err = e.PrivateKey.Serialize(w)
706 if err != nil {
707 return
708 }
709 for _, revocation := range e.Revocations {
710 err := revocation.Serialize(w)
711 if err != nil {
712 return err
713 }
714 }
715 for _, directSignature := range e.Signatures {
716 err := directSignature.Serialize(w)
717 if err != nil {
718 return err
719 }
720 }
721 for _, ident := range e.Identities {
722 err = ident.UserId.Serialize(w)
723 if err != nil {
724 return
725 }
726 if reSign {
727 if ident.SelfSignature == nil {
728 return goerrors.New("openpgp: can't re-sign identity without valid self-signature")
729 }
730 err = ident.SelfSignature.SignUserId(ident.UserId.Id, e.PrimaryKey, e.PrivateKey, config)
731 if err != nil {
732 return
733 }
734 }
735 for _, sig := range ident.Signatures {
736 err = sig.Serialize(w)
737 if err != nil {
738 return err
739 }
740 }
741 }
742 for _, subkey := range e.Subkeys {
743 err = subkey.PrivateKey.Serialize(w)
744 if err != nil {
745 return
746 }
747 if reSign {
748 err = subkey.Sig.SignKey(subkey.PublicKey, e.PrivateKey, config)
749 if err != nil {
750 return
751 }
752 if subkey.Sig.EmbeddedSignature != nil {
753 err = subkey.Sig.EmbeddedSignature.CrossSignKey(subkey.PublicKey, e.PrimaryKey,
754 subkey.PrivateKey, config)
755 if err != nil {
756 return
757 }
758 }
759 }
760 for _, revocation := range subkey.Revocations {
761 err := revocation.Serialize(w)
762 if err != nil {
763 return err
764 }
765 }
766 err = subkey.Sig.Serialize(w)
767 if err != nil {
768 return
769 }
770 }
771 return nil
772 }
773
774 // Serialize writes the public part of the given Entity to w, including
775 // signatures from other entities. No private key material will be output.
776 func (e *Entity) Serialize(w io.Writer) error {
777 err := e.PrimaryKey.Serialize(w)
778 if err != nil {
779 return err
780 }
781 for _, revocation := range e.Revocations {
782 err := revocation.Serialize(w)
783 if err != nil {
784 return err
785 }
786 }
787 for _, directSignature := range e.Signatures {
788 err := directSignature.Serialize(w)
789 if err != nil {
790 return err
791 }
792 }
793 for _, ident := range e.Identities {
794 err = ident.UserId.Serialize(w)
795 if err != nil {
796 return err
797 }
798 for _, sig := range ident.Signatures {
799 err = sig.Serialize(w)
800 if err != nil {
801 return err
802 }
803 }
804 }
805 for _, subkey := range e.Subkeys {
806 err = subkey.PublicKey.Serialize(w)
807 if err != nil {
808 return err
809 }
810 for _, revocation := range subkey.Revocations {
811 err := revocation.Serialize(w)
812 if err != nil {
813 return err
814 }
815 }
816 err = subkey.Sig.Serialize(w)
817 if err != nil {
818 return err
819 }
820 }
821 return nil
822 }
823
824 // SignIdentity adds a signature to e, from signer, attesting that identity is
825 // associated with e. The provided identity must already be an element of
826 // e.Identities and the private key of signer must have been decrypted if
827 // necessary.
828 // If config is nil, sensible defaults will be used.
829 func (e *Entity) SignIdentity(identity string, signer *Entity, config *packet.Config) error {
830 certificationKey, ok := signer.CertificationKey(config.Now())
831 if !ok {
832 return errors.InvalidArgumentError("no valid certification key found")
833 }
834
835 if certificationKey.PrivateKey.Encrypted {
836 return errors.InvalidArgumentError("signing Entity's private key must be decrypted")
837 }
838
839 ident, ok := e.Identities[identity]
840 if !ok {
841 return errors.InvalidArgumentError("given identity string not found in Entity")
842 }
843
844 sig := createSignaturePacket(certificationKey.PublicKey, packet.SigTypeGenericCert, config)
845
846 signingUserID := config.SigningUserId()
847 if signingUserID != "" {
848 if _, ok := signer.Identities[signingUserID]; !ok {
849 return errors.InvalidArgumentError("signer identity string not found in signer Entity")
850 }
851 sig.SignerUserId = &signingUserID
852 }
853
854 if err := sig.SignUserId(identity, e.PrimaryKey, certificationKey.PrivateKey, config); err != nil {
855 return err
856 }
857 ident.Signatures = append(ident.Signatures, sig)
858 return nil
859 }
860
861 // RevokeKey generates a key revocation signature (packet.SigTypeKeyRevocation) with the
862 // specified reason code and text (RFC4880 section-5.2.3.23).
863 // If config is nil, sensible defaults will be used.
864 func (e *Entity) RevokeKey(reason packet.ReasonForRevocation, reasonText string, config *packet.Config) error {
865 revSig := createSignaturePacket(e.PrimaryKey, packet.SigTypeKeyRevocation, config)
866 revSig.RevocationReason = &reason
867 revSig.RevocationReasonText = reasonText
868
869 if err := revSig.RevokeKey(e.PrimaryKey, e.PrivateKey, config); err != nil {
870 return err
871 }
872 e.Revocations = append(e.Revocations, revSig)
873 return nil
874 }
875
876 // RevokeSubkey generates a subkey revocation signature (packet.SigTypeSubkeyRevocation) for
877 // a subkey with the specified reason code and text (RFC4880 section-5.2.3.23).
878 // If config is nil, sensible defaults will be used.
879 func (e *Entity) RevokeSubkey(sk *Subkey, reason packet.ReasonForRevocation, reasonText string, config *packet.Config) error {
880 if err := e.PrimaryKey.VerifyKeySignature(sk.PublicKey, sk.Sig); err != nil {
881 return errors.InvalidArgumentError("given subkey is not associated with this key")
882 }
883
884 revSig := createSignaturePacket(e.PrimaryKey, packet.SigTypeSubkeyRevocation, config)
885 revSig.RevocationReason = &reason
886 revSig.RevocationReasonText = reasonText
887
888 if err := revSig.RevokeSubkey(sk.PublicKey, e.PrivateKey, config); err != nil {
889 return err
890 }
891
892 sk.Revocations = append(sk.Revocations, revSig)
893 return nil
894 }
895
896 func (e *Entity) primaryDirectSignature() *packet.Signature {
897 return e.SelfSignature
898 }
899
900 // PrimarySelfSignature searches the entity for the self-signature that stores key preferences.
901 // For V4 keys, returns the self-signature of the primary identity, and the identity.
902 // For V6 keys, returns the latest valid direct-key self-signature, and no identity (nil).
903 // This self-signature is to be used to check the key expiration,
904 // algorithm preferences, and so on.
905 func (e *Entity) PrimarySelfSignature() (*packet.Signature, *Identity) {
906 if e.PrimaryKey.Version == 6 {
907 return e.primaryDirectSignature(), nil
908 }
909 primaryIdentity := e.PrimaryIdentity()
910 if primaryIdentity == nil {
911 return nil, nil
912 }
913 return primaryIdentity.SelfSignature, primaryIdentity
914 }