Debian Codegraph @

openpgp/v2/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 v2
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.VerifiableSignature
32 DirectSignatures []*packet.VerifiableSignature // Direct-key self signature of the PrimaryKey (contains primary key properties in v6)}
33 Subkeys []Subkey
34 }
35
36 // A Key identifies a specific public key in an Entity. This is either the
37 // Entity's primary key or a subkey.
38 type Key struct {
39 Entity *Entity
40 PrimarySelfSignature *packet.Signature // might be nil, if not verified
41 PublicKey *packet.PublicKey
42 PrivateKey *packet.PrivateKey
43 SelfSignature *packet.Signature // might be nil, if not verified
44 }
45
46 // A KeyRing provides access to public and private keys.
47 type KeyRing interface {
48 // KeysById returns the set of keys that have the given key id.
49 // KeysById does not perform any signature validations and verification of the returned keys.
50 KeysById(id uint64) []Key
51 // EntitiesById returns the set of entities that contain a key with the given key id.
52 // EntitiesById does not perform any signature validations and verification of the returned keys.
53 EntitiesById(id uint64) []*Entity
54 }
55
56 // PrimaryIdentity returns a valid non-revoked Identity while preferring
57 // identities marked as primary, or the latest-created identity, in that order.
58 // Returns an nil for both return values if there is no valid primary identity.
59 func (e *Entity) PrimaryIdentity(date time.Time, config *packet.Config) (*packet.Signature, *Identity) {
60 var primaryIdentityCandidates []*Identity
61 var primaryIdentityCandidatesSelfSigs []*packet.Signature
62 for _, identity := range e.Identities {
63 selfSig, err := identity.Verify(date, config) // identity must be valid at date
64 if err == nil {
65 // verification is successful
66 primaryIdentityCandidates = append(primaryIdentityCandidates, identity)
67 primaryIdentityCandidatesSelfSigs = append(primaryIdentityCandidatesSelfSigs, selfSig)
68 }
69 }
70 if len(primaryIdentityCandidates) == 0 {
71 return nil, nil
72 }
73 primaryIdentity := -1
74 for idx := range primaryIdentityCandidates {
75 if primaryIdentity == -1 ||
76 shouldPreferIdentity(primaryIdentityCandidatesSelfSigs[primaryIdentity],
77 primaryIdentityCandidatesSelfSigs[idx]) {
78 primaryIdentity = idx
79 }
80 }
81 return primaryIdentityCandidatesSelfSigs[primaryIdentity], primaryIdentityCandidates[primaryIdentity]
82 }
83
84 func shouldPreferIdentity(existingId, potentialNewId *packet.Signature) bool {
85 // Prefer identities that are marked as primary
86 if existingId.IsPrimaryId != nil && *existingId.IsPrimaryId &&
87 !(potentialNewId.IsPrimaryId != nil && *potentialNewId.IsPrimaryId) {
88 return false
89 }
90 if !(existingId.IsPrimaryId != nil && *existingId.IsPrimaryId) &&
91 potentialNewId.IsPrimaryId != nil && *potentialNewId.IsPrimaryId {
92 return true
93 }
94 // after that newer creation time
95 return potentialNewId.CreationTime.Unix() >= existingId.CreationTime.Unix()
96 }
97
98 // EncryptionKey returns the best candidate Key for encrypting a message to the
99 // given Entity.
100 func (e *Entity) EncryptionKey(now time.Time, config *packet.Config) (Key, bool) {
101 encryptionKey, err := e.EncryptionKeyWithError(now, config)
102 return encryptionKey, err == nil
103 }
104
105 // EncryptionKeyWithError returns the best candidate Key for encrypting a message to the
106 // given Entity.
107 // Provides an error if the function fails to find an encryption key.
108 func (e *Entity) EncryptionKeyWithError(now time.Time, config *packet.Config) (Key, error) {
109 // The primary key has to be valid at time now
110 primarySelfSignature, err := e.VerifyPrimaryKey(now, config)
111 if err != nil { // primary key is not valid
112 return Key{}, errors.ErrEncryptionKeySelection{
113 PrimaryKeyId: e.PrimaryKey.KeyIdString(),
114 PrimaryKeyErr: err,
115 }
116 }
117
118 if err := checkKeyRequirements(e.PrimaryKey, config); err != nil {
119 // The primary key produces weak signatures
120 return Key{}, errors.ErrEncryptionKeySelection{
121 PrimaryKeyId: e.PrimaryKey.KeyIdString(),
122 PrimaryKeyErr: err,
123 }
124 }
125
126 // Iterate the keys to find the newest, unexpired one
127 var latestSelectionError *errors.ErrEncryptionKeySelection
128 candidateSubkey := -1
129 var maxTime time.Time
130 var selectedSubkeySelfSig *packet.Signature
131 for i, subkey := range e.Subkeys {
132 subkeyErr := func(encSelectionErr error) *errors.ErrEncryptionKeySelection {
133 subkeyKeyId := subkey.PublicKey.KeyIdString()
134 return &errors.ErrEncryptionKeySelection{
135 PrimaryKeyId: e.PrimaryKey.KeyIdString(),
136 EncSelectionKeyId: &subkeyKeyId,
137 EncSelectionErr: encSelectionErr,
138 }
139
140 }
141 // Verify the subkey signature.
142 subkeySelfSig, err := subkey.Verify(now, config) // subkey has to be valid at time now
143 if err != nil {
144 latestSelectionError = subkeyErr(err)
145 continue
146 }
147 // Check the algorithm and key flags.
148 if !isValidEncryptionKey(subkeySelfSig, subkey.PublicKey.PubKeyAlgo, config) {
149 continue
150 }
151 // Check if the key fulfils the requirements
152 if err := checkKeyRequirements(subkey.PublicKey, config); err != nil {
153 latestSelectionError = subkeyErr(err)
154 continue
155 }
156 preferNewSubkey := maxTime.IsZero() ||
157 subkeySelfSig.CreationTime.After(maxTime) ||
158 (subkeySelfSig.CreationTime.Equal(maxTime) && subkey.IsPQ())
159 if preferNewSubkey {
160 candidateSubkey = i
161 selectedSubkeySelfSig = subkeySelfSig
162 maxTime = subkeySelfSig.CreationTime
163 }
164 }
165
166 if candidateSubkey != -1 {
167 subkey := &e.Subkeys[candidateSubkey]
168 return Key{
169 Entity: subkey.Primary,
170 PrimarySelfSignature: primarySelfSignature,
171 PublicKey: subkey.PublicKey,
172 PrivateKey: subkey.PrivateKey,
173 SelfSignature: selectedSubkeySelfSig,
174 }, nil
175 }
176
177 // If we don't have any subkeys for encryption and the primary key
178 // is marked as OK to encrypt with, then we can use it.
179 if isValidEncryptionKey(primarySelfSignature, e.PrimaryKey.PubKeyAlgo, config) {
180 return Key{
181 Entity: e,
182 PrimarySelfSignature: primarySelfSignature,
183 PublicKey: e.PrimaryKey,
184 PrivateKey: e.PrivateKey,
185 SelfSignature: primarySelfSignature,
186 }, nil
187 }
188
189 if latestSelectionError == nil {
190 latestSelectionError = &errors.ErrEncryptionKeySelection{
191 PrimaryKeyId: e.PrimaryKey.KeyIdString(),
192 EncSelectionErr: goerrors.New("no encryption-capable key found (no key flags or invalid algorithm)"),
193 }
194 }
195
196 return Key{}, latestSelectionError
197 }
198
199 // DecryptionKeys returns all keys that are available for decryption, matching the keyID when given
200 // If date is zero (i.e., date.IsZero() == true) the time checks are not performed,
201 // which should be proffered to decrypt older messages.
202 // If id is 0 all decryption keys are returned.
203 // This is useful to retrieve keys for session key decryption.
204 func (e *Entity) DecryptionKeys(id uint64, date time.Time, config *packet.Config) (keys []Key) {
205 primarySelfSignature, err := e.PrimarySelfSignature(date, config)
206 if err != nil { // primary key is not valid
207 return
208 }
209 for _, subkey := range e.Subkeys {
210 subkeySelfSig, err := subkey.LatestValidBindingSignature(date, config)
211 if err == nil &&
212 (config.AllowDecryptionWithSigningKeys() || isValidEncryptionKey(subkeySelfSig, subkey.PublicKey.PubKeyAlgo, config)) &&
213 (id == 0 || subkey.PublicKey.KeyId == id) {
214 keys = append(keys, Key{subkey.Primary, primarySelfSignature, subkey.PublicKey, subkey.PrivateKey, subkeySelfSig})
215 }
216 }
217 if config.AllowDecryptionWithSigningKeys() || isValidEncryptionKey(primarySelfSignature, e.PrimaryKey.PubKeyAlgo, config) {
218 keys = append(keys, Key{e, primarySelfSignature, e.PrimaryKey, e.PrivateKey, primarySelfSignature})
219 }
220 return
221 }
222
223 // CertificationKey return the best candidate Key for certifying a key with this
224 // Entity.
225 func (e *Entity) CertificationKey(now time.Time, config *packet.Config) (Key, bool) {
226 return e.CertificationKeyById(now, 0, config)
227 }
228
229 // CertificationKeyById return the Key for key certification with this
230 // Entity and keyID.
231 func (e *Entity) CertificationKeyById(now time.Time, id uint64, config *packet.Config) (Key, bool) {
232 key, err := e.signingKeyByIdUsage(now, id, packet.KeyFlagSign, config)
233 return key, err == nil
234 }
235
236 // SigningKey return the best candidate Key for signing a message with this
237 // Entity.
238 func (e *Entity) SigningKey(now time.Time, config *packet.Config) (Key, bool) {
239 return e.SigningKeyById(now, 0, config)
240 }
241
242 // SigningKeyById return the Key for signing a message with this
243 // Entity and keyID.
244 func (e *Entity) SigningKeyById(now time.Time, id uint64, config *packet.Config) (Key, bool) {
245 key, err := e.signingKeyByIdUsage(now, id, packet.KeyFlagSign, config)
246 return key, err == nil
247 }
248
249 func (e *Entity) signingKeyByIdUsage(now time.Time, id uint64, flags int, config *packet.Config) (Key, error) {
250 primarySelfSignature, err := e.VerifyPrimaryKey(now, config)
251 if err != nil {
252 return Key{}, err
253 }
254
255 if err = checkKeyRequirements(e.PrimaryKey, config); err != nil {
256 // The primary key produces weak signatures
257 return Key{}, err
258 }
259
260 // Iterate the keys to find the newest, unexpired one.
261 candidateSubkey := -1
262 var maxTime time.Time
263 var selectedSubkeySelfSig *packet.Signature
264 for idx, subkey := range e.Subkeys {
265 subkeySelfSig, err := subkey.Verify(now, config)
266 if err == nil &&
267 (flags&packet.KeyFlagCertify == 0 || isValidCertificationKey(subkeySelfSig, subkey.PublicKey.PubKeyAlgo, config)) &&
268 (flags&packet.KeyFlagSign == 0 || isValidSigningKey(subkeySelfSig, subkey.PublicKey.PubKeyAlgo, config)) &&
269 checkKeyRequirements(subkey.PublicKey, config) == nil &&
270 (maxTime.IsZero() ||
271 subkeySelfSig.CreationTime.After(maxTime) ||
272 (subkeySelfSig.CreationTime.Equal(maxTime) && subkey.IsPQ())) &&
273 (id == 0 || subkey.PublicKey.KeyId == id) {
274 candidateSubkey = idx
275 maxTime = subkeySelfSig.CreationTime
276 selectedSubkeySelfSig = subkeySelfSig
277 }
278 }
279
280 if candidateSubkey != -1 {
281 subkey := &e.Subkeys[candidateSubkey]
282 return Key{
283 Entity: subkey.Primary,
284 PrimarySelfSignature: primarySelfSignature,
285 PublicKey: subkey.PublicKey,
286 PrivateKey: subkey.PrivateKey,
287 SelfSignature: selectedSubkeySelfSig,
288 }, nil
289 }
290
291 // If we don't have any subkeys for signing and the primary key
292 // is marked as OK to sign with, then we can use it.
293 if (flags&packet.KeyFlagCertify == 0 || isValidCertificationKey(primarySelfSignature, e.PrimaryKey.PubKeyAlgo, config)) &&
294 (flags&packet.KeyFlagSign == 0 || isValidSigningKey(primarySelfSignature, e.PrimaryKey.PubKeyAlgo, config)) &&
295 (id == 0 || e.PrimaryKey.KeyId == id) {
296 return Key{
297 Entity: e,
298 PrimarySelfSignature: primarySelfSignature,
299 PublicKey: e.PrimaryKey,
300 PrivateKey: e.PrivateKey,
301 SelfSignature: primarySelfSignature,
302 }, nil
303 }
304
305 // No keys with a valid Signing Flag or no keys matched the id passed in
306 return Key{}, errors.StructuralError("no valid signing or verifying key found")
307 }
308
309 // Revoked returns whether the entity has any direct key revocation signatures.
310 // Note that third-party revocation signatures are not supported.
311 // Note also that Identity and Subkey revocation should be checked separately.
312 func (e *Entity) Revoked(now time.Time) bool {
313 // Verify revocations first
314 for _, revocation := range e.Revocations {
315 if revocation.Valid == nil {
316 err := e.PrimaryKey.VerifyRevocationSignature(revocation.Packet)
317 valid := err == nil
318 revocation.Valid = &valid
319 }
320 if *revocation.Valid &&
321 (revocation.Packet.RevocationReason == nil ||
322 *revocation.Packet.RevocationReason == packet.Unknown ||
323 *revocation.Packet.RevocationReason == packet.NoReason ||
324 *revocation.Packet.RevocationReason == packet.KeyCompromised) {
325 // If the key is compromised, the key is considered revoked even before the revocation date.
326 return true
327 }
328 if *revocation.Valid &&
329 !revocation.Packet.SigExpired(now) {
330 return true
331 }
332 }
333 return false
334 }
335
336 // EncryptPrivateKeys encrypts all non-encrypted keys in the entity with the same key
337 // derived from the provided passphrase. Public keys and dummy keys are ignored,
338 // and don't cause an error to be returned.
339 func (e *Entity) EncryptPrivateKeys(passphrase []byte, config *packet.Config) error {
340 var keysToEncrypt []*packet.PrivateKey
341 // Add entity private key to encrypt.
342 if e.PrivateKey != nil && !e.PrivateKey.Dummy() && !e.PrivateKey.Encrypted {
343 keysToEncrypt = append(keysToEncrypt, e.PrivateKey)
344 }
345
346 // Add subkeys to encrypt.
347 for _, sub := range e.Subkeys {
348 if sub.PrivateKey != nil && !sub.PrivateKey.Dummy() && !sub.PrivateKey.Encrypted {
349 keysToEncrypt = append(keysToEncrypt, sub.PrivateKey)
350 }
351 }
352 return packet.EncryptPrivateKeys(keysToEncrypt, passphrase, config)
353 }
354
355 // DecryptPrivateKeys decrypts all encrypted keys in the entity with the given passphrase.
356 // Avoids recomputation of similar s2k key derivations. Public keys and dummy keys are ignored,
357 // and don't cause an error to be returned.
358 func (e *Entity) DecryptPrivateKeys(passphrase []byte) error {
359 var keysToDecrypt []*packet.PrivateKey
360 // Add entity private key to decrypt.
361 if e.PrivateKey != nil && !e.PrivateKey.Dummy() && e.PrivateKey.Encrypted {
362 keysToDecrypt = append(keysToDecrypt, e.PrivateKey)
363 }
364
365 // Add subkeys to decrypt.
366 for _, sub := range e.Subkeys {
367 if sub.PrivateKey != nil && !sub.PrivateKey.Dummy() && sub.PrivateKey.Encrypted {
368 keysToDecrypt = append(keysToDecrypt, sub.PrivateKey)
369 }
370 }
371 return packet.DecryptPrivateKeys(keysToDecrypt, passphrase)
372 }
373
374 // EntityList contains one or more Entities.
375 type EntityList []*Entity
376
377 // KeysById returns the set of keys that have the given key id.
378 // KeysById does not perform any key validation, and the self-signature
379 // fields in the returned key structs are nil.
380 func (el EntityList) KeysById(id uint64) (keys []Key) {
381 for _, e := range el {
382 if id == 0 || e.PrimaryKey.KeyId == id {
383 keys = append(keys, Key{e, nil, e.PrimaryKey, e.PrivateKey, nil})
384 }
385
386 for _, subKey := range e.Subkeys {
387 if id == 0 || subKey.PublicKey.KeyId == id {
388 keys = append(keys, Key{subKey.Primary, nil, subKey.PublicKey, subKey.PrivateKey, nil})
389 }
390 }
391 }
392 return
393 }
394
395 // EntitiesById returns the entities that contain a key with the given key id.
396 func (el EntityList) EntitiesById(id uint64) (entities []*Entity) {
397 for _, e := range el {
398 if id == 0 || e.PrimaryKey.KeyId == id {
399 entities = append(entities, e)
400 continue
401 }
402
403 for _, subKey := range e.Subkeys {
404 if id == 0 || subKey.PublicKey.KeyId == id {
405 entities = append(entities, e)
406 continue
407 }
408 }
409 }
410 return
411 }
412
413 // ReadArmoredKeyRing reads one or more public/private keys from an armor keyring file.
414 func ReadArmoredKeyRing(r io.Reader) (EntityList, error) {
415 block, err := armor.Decode(r)
416 if err == io.EOF {
417 return nil, errors.InvalidArgumentError("no armored data found")
418 }
419 if err != nil {
420 return nil, err
421 }
422 if block.Type != PublicKeyType && block.Type != PrivateKeyType {
423 return nil, errors.InvalidArgumentError("expected public or private key block, got: " + block.Type)
424 }
425
426 return ReadKeyRing(block.Body)
427 }
428
429 // ReadKeyRing reads one or more public/private keys. Unsupported keys are
430 // ignored as long as at least a single valid key is found.
431 func ReadKeyRing(r io.Reader) (el EntityList, err error) {
432 packets := packet.NewReader(r)
433 var lastUnsupportedError error
434
435 for {
436 var e *Entity
437 e, err = ReadEntity(packets)
438 if err != nil {
439 // TODO: warn about skipped unsupported/unreadable keys
440 if _, ok := err.(errors.UnsupportedError); ok {
441 lastUnsupportedError = err
442 err = readToNextPublicKey(packets)
443 } else if _, ok := err.(errors.StructuralError); ok {
444 // Skip unreadable, badly-formatted keys
445 lastUnsupportedError = err
446 err = readToNextPublicKey(packets)
447 }
448 if err == io.EOF {
449 err = nil
450 break
451 }
452 if err != nil {
453 el = nil
454 break
455 }
456 } else {
457 el = append(el, e)
458 }
459 }
460
461 if len(el) == 0 && err == nil {
462 err = lastUnsupportedError
463 }
464 return
465 }
466
467 // readToNextPublicKey reads packets until the start of the entity and leaves
468 // the first packet of the new entity in the Reader.
469 func readToNextPublicKey(packets *packet.Reader) (err error) {
470 var p packet.Packet
471 for {
472 p, err = packets.Next()
473 if err == io.EOF {
474 return
475 } else if err != nil {
476 if _, ok := err.(errors.UnsupportedError); ok {
477 continue
478 }
479 return
480 }
481
482 if pk, ok := p.(*packet.PublicKey); ok && !pk.IsSubkey {
483 packets.Unread(p)
484 return
485 }
486 }
487 }
488
489 // ReadEntity reads an entity (public key, identities, subkeys etc) from the
490 // given Reader.
491 func ReadEntity(packets *packet.Reader) (*Entity, error) {
492 e := new(Entity)
493 e.Identities = make(map[string]*Identity)
494
495 p, err := packets.Next()
496 if err != nil {
497 return nil, err
498 }
499
500 var ok bool
501 if e.PrimaryKey, ok = p.(*packet.PublicKey); !ok {
502 if e.PrivateKey, ok = p.(*packet.PrivateKey); !ok {
503 packets.Unread(p)
504 return nil, errors.StructuralError("first packet was not a public/private key")
505 }
506 e.PrimaryKey = &e.PrivateKey.PublicKey
507 }
508
509 if !e.PrimaryKey.PubKeyAlgo.CanSign() {
510 return nil, errors.StructuralError("primary key cannot be used for signatures")
511 }
512 var ignoreSigs bool
513 EachPacket:
514 for {
515 p, err := packets.NextWithUnsupported()
516 if err == io.EOF {
517 break
518 } else if err != nil {
519 return nil, err
520 }
521
522 var unsupported bool
523 if unsupportedPacket, ok := p.(*packet.UnsupportedPacket); ok {
524 unsupported = true
525 p = unsupportedPacket.IncompletePacket
526 }
527
528 // Handle unsupported keys
529 switch p.(type) {
530 case *packet.PublicKey, *packet.PrivateKey:
531 if unsupported {
532 // Skip following signature packets
533 ignoreSigs = true
534 }
535 case *packet.Signature:
536 if ignoreSigs {
537 continue
538 }
539 default:
540 ignoreSigs = false
541 }
542 // Unsupported packages are handled continue
543 // if the packet is unsupported
544 if unsupported {
545 continue
546 }
547
548 switch pkt := p.(type) {
549 case *packet.UserId:
550 err := readUser(e, packets, pkt)
551 if err != nil {
552 return nil, err
553 }
554 case *packet.Signature:
555 if pkt.SigType == packet.SigTypeKeyRevocation {
556 e.Revocations = append(e.Revocations, packet.NewVerifiableSig(pkt))
557 } else if pkt.SigType == packet.SigTypeDirectSignature {
558 e.DirectSignatures = append(e.DirectSignatures, packet.NewVerifiableSig(pkt))
559 }
560 // Else, ignoring the signature as it does not follow anything
561 // we would know to attach it to.
562 case *packet.PrivateKey:
563 if !pkt.IsSubkey {
564 packets.Unread(p)
565 break EachPacket
566 }
567 err = readSubkey(e, packets, &pkt.PublicKey, pkt)
568 if err != nil {
569 return nil, err
570 }
571 case *packet.PublicKey:
572 if !pkt.IsSubkey {
573 packets.Unread(p)
574 break EachPacket
575 }
576 err = readSubkey(e, packets, pkt, nil)
577 if err != nil {
578 return nil, err
579 }
580 default:
581 // we ignore unknown packets
582 }
583 }
584
585 if len(e.Identities) == 0 && e.PrimaryKey.Version < 6 {
586 return nil, errors.StructuralError("v4 entity without any identities")
587 }
588
589 if e.PrimaryKey.Version == 6 && len(e.DirectSignatures) == 0 {
590 return nil, errors.StructuralError("v6 entity without a direct-key signature")
591 }
592 return e, nil
593 }
594
595 // SerializePrivate serializes an Entity, including private key material, but
596 // excluding signatures from other entities, to the given Writer.
597 // Identities and subkeys are re-signed in case they changed since NewEntry.
598 // If config is nil, sensible defaults will be used.
599 func (e *Entity) SerializePrivate(w io.Writer, config *packet.Config) (err error) {
600 if e.PrivateKey.Dummy() {
601 return errors.ErrDummyPrivateKey("dummy private key cannot re-sign identities")
602 }
603 return e.serializePrivate(w, config, true)
604 }
605
606 // SerializePrivateWithoutSigning serializes an Entity, including private key
607 // material, but excluding signatures from other entities, to the given Writer.
608 // Self-signatures of identities and subkeys are not re-signed. This is useful
609 // when serializing GNU dummy keys, among other things.
610 // If config is nil, sensible defaults will be used.
611 func (e *Entity) SerializePrivateWithoutSigning(w io.Writer, config *packet.Config) (err error) {
612 return e.serializePrivate(w, config, false)
613 }
614
615 func (e *Entity) serializePrivate(w io.Writer, config *packet.Config, reSign bool) (err error) {
616 if e.PrivateKey == nil {
617 return goerrors.New("openpgp: private key is missing")
618 }
619 err = e.PrivateKey.Serialize(w)
620 if err != nil {
621 return
622 }
623 for _, revocation := range e.Revocations {
624 if err = revocation.Packet.Serialize(w); err != nil {
625 return err
626 }
627 }
628 for _, directSignature := range e.DirectSignatures {
629 if err = directSignature.Packet.Serialize(w); err != nil {
630 return err
631 }
632 }
633 for _, ident := range e.Identities {
634 if reSign {
635 if err = ident.ReSign(config); err != nil {
636 return err
637 }
638 }
639 if err = ident.Serialize(w); err != nil {
640 return err
641 }
642 }
643 for _, subkey := range e.Subkeys {
644 if reSign {
645 if err := subkey.ReSign(config); err != nil {
646 return err
647 }
648 }
649 if err = subkey.Serialize(w, true); err != nil {
650 return err
651 }
652 }
653 return nil
654 }
655
656 // Serialize writes the public part of the given Entity to w, including
657 // signatures from other entities. No private key material will be output.
658 func (e *Entity) Serialize(w io.Writer) error {
659 if err := e.PrimaryKey.Serialize(w); err != nil {
660 return err
661 }
662 for _, revocation := range e.Revocations {
663 if err := revocation.Packet.Serialize(w); err != nil {
664 return err
665 }
666 }
667 for _, directSignature := range e.DirectSignatures {
668 err := directSignature.Packet.Serialize(w)
669 if err != nil {
670 return err
671 }
672 }
673 for _, ident := range e.Identities {
674 if err := ident.Serialize(w); err != nil {
675 return err
676 }
677 }
678 for _, subkey := range e.Subkeys {
679 if err := subkey.Serialize(w, false); err != nil {
680 return err
681 }
682 }
683 return nil
684 }
685
686 // Revoke generates a key revocation signature (packet.SigTypeKeyRevocation) with the
687 // specified reason code and text (RFC4880 section-5.2.3.23).
688 // If config is nil, sensible defaults will be used.
689 func (e *Entity) Revoke(reason packet.ReasonForRevocation, reasonText string, config *packet.Config) error {
690 revSig := createSignaturePacket(e.PrimaryKey, packet.SigTypeKeyRevocation, config)
691 revSig.RevocationReason = &reason
692 revSig.RevocationReasonText = reasonText
693
694 if err := revSig.RevokeKey(e.PrimaryKey, e.PrivateKey, config); err != nil {
695 return err
696 }
697 sig := packet.NewVerifiableSig(revSig)
698 valid := true
699 sig.Valid = &valid
700 e.Revocations = append(e.Revocations, sig)
701 return nil
702 }
703
704 // SignIdentity adds a signature to e, from signer, attesting that identity is
705 // associated with e. The provided identity must already be an element of
706 // e.Identities and the private key of signer must have been decrypted if
707 // necessary.
708 // If config is nil, sensible defaults will be used.
709 func (e *Entity) SignIdentity(identity string, signer *Entity, config *packet.Config) error {
710 ident, ok := e.Identities[identity]
711 if !ok {
712 return errors.InvalidArgumentError("given identity string not found in Entity")
713 }
714 return ident.SignIdentity(signer, config)
715 }
716
717 // LatestValidDirectSignature returns the latest valid direct key-signature of the entity.
718 func (e *Entity) LatestValidDirectSignature(date time.Time, config *packet.Config) (selectedSig *packet.Signature, err error) {
719 for sigIdx := len(e.DirectSignatures) - 1; sigIdx >= 0; sigIdx-- {
720 sig := e.DirectSignatures[sigIdx]
721 if (date.IsZero() || date.Unix() >= sig.Packet.CreationTime.Unix()) &&
722 (selectedSig == nil || selectedSig.CreationTime.Unix() < sig.Packet.CreationTime.Unix()) {
723 if sig.Valid == nil {
724 err := e.PrimaryKey.VerifyDirectKeySignature(sig.Packet)
725 if err == nil {
726 err = checkSignatureDetails(sig.Packet, date, config)
727 }
728 valid := err == nil
729 sig.Valid = &valid
730 }
731 if *sig.Valid && (date.IsZero() || !sig.Packet.SigExpired(date)) {
732 selectedSig = sig.Packet
733 }
734 }
735 }
736 if selectedSig == nil {
737 return nil, errors.StructuralError("no valid direct key signature found")
738 }
739 return selectedSig, nil
740 }
741
742 // PrimarySelfSignature searches the entity for the self-signature that stores key preferences.
743 // For V4 keys, returns the self-signature of the primary identity, and the identity.
744 // For V6 keys, returns the latest valid direct-key self-signature, and no identity (nil).
745 // This self-signature is to be used to check the key expiration,
746 // algorithm preferences, and so on.
747 func (e *Entity) PrimarySelfSignature(date time.Time, config *packet.Config) (primarySig *packet.Signature, err error) {
748 if e.PrimaryKey.Version == 6 {
749 return e.LatestValidDirectSignature(date, config)
750 }
751 primarySig, _ = e.PrimaryIdentity(date, config)
752 if primarySig == nil {
753 return nil, errors.StructuralError("no primary identity found")
754 }
755 return
756 }
757
758 // VerifyPrimaryKey checks if the primary key is valid by checking:
759 // - that the primary key is has not been revoked at the given date,
760 // - that there is valid non-expired self-signature,
761 // - that the primary key is not expired given its self-signature.
762 // If date is zero (i.e., date.IsZero() == true) the time checks are not performed.
763 func (e *Entity) VerifyPrimaryKey(date time.Time, config *packet.Config) (*packet.Signature, error) {
764 primarySelfSignature, err := e.PrimarySelfSignature(date, config)
765 if err != nil {
766 return nil, goerrors.New("no valid self signature found")
767 }
768 // check for key revocation signatures
769 if e.Revoked(date) {
770 return nil, errors.ErrKeyRevoked
771 }
772
773 if !date.IsZero() && (e.PrimaryKey.KeyExpired(primarySelfSignature, date) || // primary key has expired
774 primarySelfSignature.SigExpired(date)) { // self-signature has expired
775 return primarySelfSignature, errors.ErrKeyExpired
776 }
777
778 if e.PrimaryKey.Version != 6 && len(e.DirectSignatures) > 0 {
779 // check for expiration time in direct signatures (for V6 keys, the above already did so)
780 primaryDirectKeySignature, _ := e.LatestValidDirectSignature(date, config)
781 if primaryDirectKeySignature != nil &&
782 (!date.IsZero() && e.PrimaryKey.KeyExpired(primaryDirectKeySignature, date)) {
783 return primarySelfSignature, errors.ErrKeyExpired
784 }
785 }
786 return primarySelfSignature, nil
787 }
788
789 func (k *Key) IsPrimary() bool {
790 if k.PrimarySelfSignature == nil || k.SelfSignature == nil {
791 return k.PublicKey == k.Entity.PrimaryKey
792 }
793 return k.PrimarySelfSignature == k.SelfSignature
794 }
795
796 func checkKeyRequirements(usedKey *packet.PublicKey, config *packet.Config) error {
797 algo := usedKey.PubKeyAlgo
798 if config.RejectPublicKeyAlgorithm(algo) {
799 return errors.WeakAlgorithmError("public key algorithm " + string(algo))
800 }
801 switch algo {
802 case packet.PubKeyAlgoRSA, packet.PubKeyAlgoRSASignOnly:
803 length, err := usedKey.BitLength()
804 if err != nil || length < config.MinimumRSABits() {
805 return errors.WeakAlgorithmError(fmt.Sprintf("minimum rsa length is %d got %d", config.MinimumRSABits(), length))
806 }
807 case packet.PubKeyAlgoECDH, packet.PubKeyAlgoEdDSA, packet.PubKeyAlgoECDSA:
808 curve, err := usedKey.Curve()
809 if err != nil || config.RejectCurve(curve) {
810 return errors.WeakAlgorithmError("elliptic curve " + curve)
811 }
812 if usedKey.Version == 6 && (curve == packet.Curve25519 || curve == packet.Curve448) {
813 // Implementations MUST NOT accept or generate v6 key material using the deprecated OIDs.
814 return errors.StructuralError("v6 key uses legacy elliptic curve " + curve)
815 }
816 }
817 return nil
818 }
819
820 func isValidSigningKey(signature *packet.Signature, algo packet.PublicKeyAlgorithm, config *packet.Config) bool {
821 if !algo.CanSign() {
822 return false
823 }
824
825 if signature.FlagsValid {
826 return signature.FlagSign
827 }
828
829 return config.AllowAllKeyFlagsWhenMissing()
830 }
831
832 func isValidCertificationKey(signature *packet.Signature, algo packet.PublicKeyAlgorithm, config *packet.Config) bool {
833 if !algo.CanSign() {
834 return false
835 }
836
837 if signature.FlagsValid {
838 return signature.FlagCertify
839 }
840
841 return config.AllowAllKeyFlagsWhenMissing()
842 }
843
844 func isValidEncryptionKey(signature *packet.Signature, algo packet.PublicKeyAlgorithm, config *packet.Config) bool {
845 if !algo.CanEncrypt() {
846 return false
847 }
848
849 if signature.FlagsValid {
850 return signature.FlagEncryptCommunications || signature.FlagEncryptStorage
851 }
852
853 return config.AllowAllKeyFlagsWhenMissing()
854 }