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
5package openpgp
6
7import (
8	"crypto/hmac"
9	"encoding/binary"
10	"io"
11	"time"
12
13	"github.com/keybase/go-crypto/openpgp/armor"
14	"github.com/keybase/go-crypto/openpgp/errors"
15	"github.com/keybase/go-crypto/openpgp/packet"
16	"github.com/keybase/go-crypto/rsa"
17)
18
19// PublicKeyType is the armor type for a PGP public key.
20var PublicKeyType = "PGP PUBLIC KEY BLOCK"
21
22// PrivateKeyType is the armor type for a PGP private key.
23var PrivateKeyType = "PGP PRIVATE KEY BLOCK"
24
25// An Entity represents the components of an OpenPGP key: a primary public key
26// (which must be a signing key), one or more identities claimed by that key,
27// and zero or more subkeys, which may be encryption keys.
28type Entity struct {
29	PrimaryKey  *packet.PublicKey
30	PrivateKey  *packet.PrivateKey
31	Identities  map[string]*Identity // indexed by Identity.Name
32	Revocations []*packet.Signature
33	// Revocations that are signed by designated revokers. Reading keys
34	// will not verify these revocations, because it won't have access to
35	// issuers' public keys, API consumers should do this instead (or
36	// not, and just assume that the key is probably revoked).
37	UnverifiedRevocations []*packet.Signature
38	Subkeys               []Subkey
39	BadSubkeys            []BadSubkey
40}
41
42// An Identity represents an identity claimed by an Entity and zero or more
43// assertions by other entities about that claim.
44type Identity struct {
45	Name          string // by convention, has the form "Full Name (comment) <email@example.com>"
46	UserId        *packet.UserId
47	SelfSignature *packet.Signature
48	Signatures    []*packet.Signature
49	Revocation    *packet.Signature
50}
51
52// A Subkey is an additional public key in an Entity. Subkeys can be used for
53// encryption.
54type Subkey struct {
55	PublicKey  *packet.PublicKey
56	PrivateKey *packet.PrivateKey
57	Sig        *packet.Signature
58	Revocation *packet.Signature
59}
60
61// BadSubkey is one that failed reconstruction, but we'll keep it around for
62// informational purposes.
63type BadSubkey struct {
64	Subkey
65	Err error
66}
67
68// A Key identifies a specific public key in an Entity. This is either the
69// Entity's primary key or a subkey.
70type Key struct {
71	Entity        *Entity
72	PublicKey     *packet.PublicKey
73	PrivateKey    *packet.PrivateKey
74	SelfSignature *packet.Signature
75	KeyFlags      packet.KeyFlagBits
76}
77
78// A KeyRing provides access to public and private keys.
79type KeyRing interface {
80
81	// KeysById returns the set of keys that have the given key id.
82	// fp can be optionally supplied, which is the full key fingerprint.
83	// If it's provided, then it must match. This comes up in the case
84	// of GPG subpacket 33.
85	KeysById(id uint64, fp []byte) []Key
86
87	// KeysByIdAndUsage returns the set of keys with the given id
88	// that also meet the key usage given by requiredUsage.
89	// The requiredUsage is expressed as the bitwise-OR of
90	// packet.KeyFlag* values.
91	// fp can be optionally supplied, which is the full key fingerprint.
92	// If it's provided, then it must match. This comes up in the case
93	// of GPG subpacket 33.
94	KeysByIdUsage(id uint64, fp []byte, requiredUsage byte) []Key
95
96	// DecryptionKeys returns all private keys that are valid for
97	// decryption.
98	DecryptionKeys() []Key
99}
100
101// primaryIdentity returns the Identity marked as primary or the first identity
102// if none are so marked.
103func (e *Entity) primaryIdentity() *Identity {
104	var firstIdentity *Identity
105	for _, ident := range e.Identities {
106		if firstIdentity == nil {
107			firstIdentity = ident
108		}
109		if ident.SelfSignature.IsPrimaryId != nil && *ident.SelfSignature.IsPrimaryId {
110			return ident
111		}
112	}
113	return firstIdentity
114}
115
116// encryptionKey returns the best candidate Key for encrypting a message to the
117// given Entity.
118func (e *Entity) encryptionKey(now time.Time) (Key, bool) {
119	candidateSubkey := -1
120
121	// Iterate the keys to find the newest, non-revoked key that can
122	// encrypt.
123	var maxTime time.Time
124	for i, subkey := range e.Subkeys {
125
126		// NOTE(maxtaco)
127		// If there is a Flags subpacket, then we have to follow it, and only
128		// use keys that are marked for Encryption of Communication.  If there
129		// isn't a Flags subpacket, and this is an Encrypt-Only key (right now only ElGamal
130		// suffices), then we implicitly use it. The check for primary below is a little
131		// more open-ended, but for now, let's be strict and potentially open up
132		// if we see bugs in the wild.
133		//
134		// One more note: old DSA/ElGamal keys tend not to have the Flags subpacket,
135		// so this sort of thing is pretty important for encrypting to older keys.
136		//
137		if ((subkey.Sig.FlagsValid && subkey.Sig.FlagEncryptCommunications) ||
138			(!subkey.Sig.FlagsValid && subkey.PublicKey.PubKeyAlgo == packet.PubKeyAlgoElGamal)) &&
139			subkey.PublicKey.PubKeyAlgo.CanEncrypt() &&
140			!subkey.Sig.KeyExpired(now) &&
141			subkey.Revocation == nil &&
142			(maxTime.IsZero() || subkey.Sig.CreationTime.After(maxTime)) {
143			candidateSubkey = i
144			maxTime = subkey.Sig.CreationTime
145		}
146	}
147
148	if candidateSubkey != -1 {
149		subkey := e.Subkeys[candidateSubkey]
150		return Key{e, subkey.PublicKey, subkey.PrivateKey, subkey.Sig, subkey.Sig.GetKeyFlags()}, true
151	}
152
153	// If we don't have any candidate subkeys for encryption and
154	// the primary key doesn't have any usage metadata then we
155	// assume that the primary key is ok. Or, if the primary key is
156	// marked as ok to encrypt to, then we can obviously use it.
157	//
158	// NOTE(maxtaco) - see note above, how this policy is a little too open-ended
159	// for my liking, but leave it for now.
160	i := e.primaryIdentity()
161	if (!i.SelfSignature.FlagsValid || i.SelfSignature.FlagEncryptCommunications) &&
162		e.PrimaryKey.PubKeyAlgo.CanEncrypt() &&
163		!i.SelfSignature.KeyExpired(now) {
164		return Key{e, e.PrimaryKey, e.PrivateKey, i.SelfSignature, i.SelfSignature.GetKeyFlags()}, true
165	}
166
167	// This Entity appears to be signing only.
168	return Key{}, false
169}
170
171// signingKey return the best candidate Key for signing a message with this
172// Entity.
173func (e *Entity) signingKey(now time.Time) (Key, bool) {
174	candidateSubkey := -1
175
176	// Iterate the keys to find the newest, non-revoked key that can
177	// sign.
178	var maxTime time.Time
179	for i, subkey := range e.Subkeys {
180		if (!subkey.Sig.FlagsValid || subkey.Sig.FlagSign) &&
181			subkey.PrivateKey.PrivateKey != nil &&
182			subkey.PublicKey.PubKeyAlgo.CanSign() &&
183			!subkey.Sig.KeyExpired(now) &&
184			subkey.Revocation == nil &&
185			(maxTime.IsZero() || subkey.Sig.CreationTime.After(maxTime)) {
186			candidateSubkey = i
187			maxTime = subkey.Sig.CreationTime
188			break
189		}
190	}
191
192	if candidateSubkey != -1 {
193		subkey := e.Subkeys[candidateSubkey]
194		return Key{e, subkey.PublicKey, subkey.PrivateKey, subkey.Sig, subkey.Sig.GetKeyFlags()}, true
195	}
196
197	// If we have no candidate subkey then we assume that it's ok to sign
198	// with the primary key.
199	i := e.primaryIdentity()
200	if (!i.SelfSignature.FlagsValid || i.SelfSignature.FlagSign) &&
201		e.PrimaryKey.PubKeyAlgo.CanSign() &&
202		!i.SelfSignature.KeyExpired(now) &&
203		e.PrivateKey.PrivateKey != nil {
204		return Key{e, e.PrimaryKey, e.PrivateKey, i.SelfSignature, i.SelfSignature.GetKeyFlags()}, true
205	}
206
207	return Key{}, false
208}
209
210// An EntityList contains one or more Entities.
211type EntityList []*Entity
212
213func keyMatchesIdAndFingerprint(key *packet.PublicKey, id uint64, fp []byte) bool {
214	if key.KeyId != id {
215		return false
216	}
217	if fp == nil {
218		return true
219	}
220	return hmac.Equal(fp, key.Fingerprint[:])
221}
222
223// KeysById returns the set of keys that have the given key id.
224// fp can be optionally supplied, which is the full key fingerprint.
225// If it's provided, then it must match. This comes up in the case
226// of GPG subpacket 33.
227func (el EntityList) KeysById(id uint64, fp []byte) (keys []Key) {
228	for _, e := range el {
229		if keyMatchesIdAndFingerprint(e.PrimaryKey, id, fp) {
230			var selfSig *packet.Signature
231			for _, ident := range e.Identities {
232				if selfSig == nil {
233					selfSig = ident.SelfSignature
234				} else if ident.SelfSignature.IsPrimaryId != nil && *ident.SelfSignature.IsPrimaryId {
235					selfSig = ident.SelfSignature
236					break
237				}
238			}
239
240			var keyFlags packet.KeyFlagBits
241			for _, ident := range e.Identities {
242				keyFlags.Merge(ident.SelfSignature.GetKeyFlags())
243			}
244
245			keys = append(keys, Key{e, e.PrimaryKey, e.PrivateKey, selfSig, keyFlags})
246		}
247
248		for _, subKey := range e.Subkeys {
249			if keyMatchesIdAndFingerprint(subKey.PublicKey, id, fp) {
250
251				// If there's both a a revocation and a sig, then take the
252				// revocation. Otherwise, we can proceed with the sig.
253				sig := subKey.Revocation
254				if sig == nil {
255					sig = subKey.Sig
256				}
257
258				keys = append(keys, Key{e, subKey.PublicKey, subKey.PrivateKey, sig, sig.GetKeyFlags()})
259			}
260		}
261	}
262	return
263}
264
265// KeysByIdAndUsage returns the set of keys with the given id that also meet
266// the key usage given by requiredUsage.  The requiredUsage is expressed as
267// the bitwise-OR of packet.KeyFlag* values.
268// fp can be optionally supplied, which is the full key fingerprint.
269// If it's provided, then it must match. This comes up in the case
270// of GPG subpacket 33.
271func (el EntityList) KeysByIdUsage(id uint64, fp []byte, requiredUsage byte) (keys []Key) {
272	for _, key := range el.KeysById(id, fp) {
273		if len(key.Entity.Revocations) > 0 {
274			continue
275		}
276
277		if key.SelfSignature.RevocationReason != nil {
278			continue
279		}
280
281		if requiredUsage != 0 {
282			var usage byte
283
284			switch {
285			case key.KeyFlags.Valid:
286				usage = key.KeyFlags.BitField
287
288			case key.PublicKey.PubKeyAlgo == packet.PubKeyAlgoElGamal:
289				// We also need to handle the case where, although the sig's
290				// flags aren't valid, the key can is implicitly usable for
291				// encryption by virtue of being ElGamal. See also the comment
292				// in encryptionKey() above.
293				usage |= packet.KeyFlagEncryptCommunications
294				usage |= packet.KeyFlagEncryptStorage
295
296			case key.PublicKey.PubKeyAlgo == packet.PubKeyAlgoDSA ||
297				key.PublicKey.PubKeyAlgo == packet.PubKeyAlgoECDSA ||
298				key.PublicKey.PubKeyAlgo == packet.PubKeyAlgoEdDSA:
299				usage |= packet.KeyFlagSign
300
301			// For a primary RSA key without any key flags, be as permissiable
302			// as possible.
303			case key.PublicKey.PubKeyAlgo == packet.PubKeyAlgoRSA &&
304				keyMatchesIdAndFingerprint(key.Entity.PrimaryKey, id, fp):
305				usage = (packet.KeyFlagCertify | packet.KeyFlagSign |
306					packet.KeyFlagEncryptCommunications | packet.KeyFlagEncryptStorage)
307			}
308
309			if usage&requiredUsage != requiredUsage {
310				continue
311			}
312		}
313
314		keys = append(keys, key)
315	}
316	return
317}
318
319// DecryptionKeys returns all private keys that are valid for decryption.
320func (el EntityList) DecryptionKeys() (keys []Key) {
321	for _, e := range el {
322		for _, subKey := range e.Subkeys {
323			if subKey.PrivateKey != nil && subKey.PrivateKey.PrivateKey != nil && (!subKey.Sig.FlagsValid || subKey.Sig.FlagEncryptStorage || subKey.Sig.FlagEncryptCommunications) {
324				keys = append(keys, Key{e, subKey.PublicKey, subKey.PrivateKey, subKey.Sig, subKey.Sig.GetKeyFlags()})
325			}
326		}
327	}
328	return
329}
330
331// ReadArmoredKeyRing reads one or more public/private keys from an armor keyring file.
332func ReadArmoredKeyRing(r io.Reader) (EntityList, error) {
333	block, err := armor.Decode(r)
334	if err == io.EOF {
335		return nil, errors.InvalidArgumentError("no armored data found")
336	}
337	if err != nil {
338		return nil, err
339	}
340	if block.Type != PublicKeyType && block.Type != PrivateKeyType {
341		return nil, errors.InvalidArgumentError("expected public or private key block, got: " + block.Type)
342	}
343
344	return ReadKeyRing(block.Body)
345}
346
347// ReadKeyRing reads one or more public/private keys. Unsupported keys are
348// ignored as long as at least a single valid key is found.
349func ReadKeyRing(r io.Reader) (el EntityList, err error) {
350	packets := packet.NewReader(r)
351	var lastUnsupportedError error
352
353	for {
354		var e *Entity
355		e, err = ReadEntity(packets)
356		if err != nil {
357			// TODO: warn about skipped unsupported/unreadable keys
358			if _, ok := err.(errors.UnsupportedError); ok {
359				lastUnsupportedError = err
360				err = readToNextPublicKey(packets)
361			} else if _, ok := err.(errors.StructuralError); ok {
362				// Skip unreadable, badly-formatted keys
363				lastUnsupportedError = err
364				err = readToNextPublicKey(packets)
365			}
366			if err == io.EOF {
367				err = nil
368				break
369			}
370			if err != nil {
371				el = nil
372				break
373			}
374		} else {
375			el = append(el, e)
376		}
377	}
378
379	if len(el) == 0 && err == nil {
380		err = lastUnsupportedError
381	}
382	return
383}
384
385// readToNextPublicKey reads packets until the start of the entity and leaves
386// the first packet of the new entity in the Reader.
387func readToNextPublicKey(packets *packet.Reader) (err error) {
388	var p packet.Packet
389	for {
390		p, err = packets.Next()
391		if err == io.EOF {
392			return
393		} else if err != nil {
394			if _, ok := err.(errors.UnsupportedError); ok {
395				err = nil
396				continue
397			}
398			return
399		}
400
401		if pk, ok := p.(*packet.PublicKey); ok && !pk.IsSubkey {
402			packets.Unread(p)
403			return
404		}
405	}
406
407	panic("unreachable")
408}
409
410// ReadEntity reads an entity (public key, identities, subkeys etc) from the
411// given Reader.
412func ReadEntity(packets *packet.Reader) (*Entity, error) {
413	e := new(Entity)
414	e.Identities = make(map[string]*Identity)
415
416	p, err := packets.Next()
417	if err != nil {
418		return nil, err
419	}
420
421	var ok bool
422	if e.PrimaryKey, ok = p.(*packet.PublicKey); !ok {
423		if e.PrivateKey, ok = p.(*packet.PrivateKey); !ok {
424			packets.Unread(p)
425			return nil, errors.StructuralError("first packet was not a public/private key")
426		} else {
427			e.PrimaryKey = &e.PrivateKey.PublicKey
428		}
429	}
430
431	if !e.PrimaryKey.PubKeyAlgo.CanSign() {
432		return nil, errors.StructuralError("primary key cannot be used for signatures")
433	}
434
435	var current *Identity
436	var revocations []*packet.Signature
437
438	designatedRevokers := make(map[uint64]bool)
439EachPacket:
440	for {
441		p, err := packets.Next()
442		if err == io.EOF {
443			break
444		} else if err != nil {
445			return nil, err
446		}
447		switch pkt := p.(type) {
448		case *packet.UserId:
449
450			// Make a new Identity object, that we might wind up throwing away.
451			// We'll only add it if we get a valid self-signature over this
452			// userID.
453			current = new(Identity)
454			current.Name = pkt.Id
455			current.UserId = pkt
456		case *packet.Signature:
457			if pkt.SigType == packet.SigTypeKeyRevocation {
458				// These revocations won't revoke UIDs (see
459				// SigTypeIdentityRevocation). Handle these first,
460				// because key might have revocation coming from
461				// another key (designated revoke).
462				revocations = append(revocations, pkt)
463				continue
464			}
465
466			// These are signatures by other people on this key. Let's just ignore them
467			// from the beginning, since they shouldn't affect our key decoding one way
468			// or the other.
469			if pkt.IssuerKeyId != nil && *pkt.IssuerKeyId != e.PrimaryKey.KeyId {
470				continue
471			}
472
473			// If this is a signature made by the keyholder, and the signature has stubbed out
474			// critical packets, then *now* we need to bail out.
475			if e := pkt.StubbedOutCriticalError; e != nil {
476				return nil, e
477			}
478
479			// Next handle the case of a self-signature. According to RFC8440,
480			// Section 5.2.3.3, if there are several self-signatures,
481			// we should take the newer one.  If they were both created
482			// at the same time, but one of them has keyflags specified and the
483			// other doesn't, keep the one with the keyflags. We have actually
484			// seen this in the wild (see the 'Yield' test in read_test.go).
485			// If there is a tie, and both have the same value for FlagsValid,
486			// then "last writer wins."
487			//
488			// HOWEVER! We have seen yet more keys in the wild (see the 'Spiros'
489			// test in read_test.go), in which the later self-signature is a bunch
490			// of junk, and doesn't even specify key flags. Does it really make
491			// sense to overwrite reasonable key flags with the empty set? I'm not
492			// sure what that would be trying to achieve, and plus GPG seems to be
493			// ok with this situation, and ignores the later (empty) keyflag set.
494			// So further tighten our overwrite rules, and only allow the later
495			// signature to overwrite the earlier signature if so doing won't
496			// trash the key flags.
497			if current != nil &&
498				(current.SelfSignature == nil ||
499					(!pkt.CreationTime.Before(current.SelfSignature.CreationTime) &&
500						(pkt.FlagsValid || !current.SelfSignature.FlagsValid))) &&
501				(pkt.SigType == packet.SigTypePositiveCert || pkt.SigType == packet.SigTypeGenericCert) &&
502				pkt.IssuerKeyId != nil &&
503				*pkt.IssuerKeyId == e.PrimaryKey.KeyId {
504
505				if err = e.PrimaryKey.VerifyUserIdSignature(current.Name, e.PrimaryKey, pkt); err == nil {
506
507					current.SelfSignature = pkt
508
509					// NOTE(maxtaco) 2016.01.11
510					// Only register an identity once we've gotten a valid self-signature.
511					// It's possible therefore for us to throw away `current` in the case
512					// no valid self-signatures were found. That's OK as long as there are
513					// other identities that make sense.
514					//
515					// NOTE! We might later see a revocation for this very same UID, and it
516					// won't be undone. We've preserved this feature from the original
517					// Google OpenPGP we forked from.
518					e.Identities[current.Name] = current
519				} else {
520					// We really should warn that there was a failure here. Not raise an error
521					// since this really shouldn't be a fail-stop error.
522				}
523			} else if current != nil && pkt.SigType == packet.SigTypeIdentityRevocation {
524				if err = e.PrimaryKey.VerifyUserIdSignature(current.Name, e.PrimaryKey, pkt); err == nil {
525					// Note: we are not removing the identity from
526					// e.Identities. Caller can always filter by Revocation
527					// field to ignore revoked identities.
528					current.Revocation = pkt
529				}
530			} else if pkt.SigType == packet.SigTypeDirectSignature {
531				if err = e.PrimaryKey.VerifyRevocationSignature(e.PrimaryKey, pkt); err == nil {
532					if desig := pkt.DesignatedRevoker; desig != nil {
533						// If it's a designated revoker signature, take last 8 octects
534						// of fingerprint as Key ID and save it to designatedRevokers
535						// map. We consult this map later to see if a foreign
536						// revocation should be added to UnverifiedRevocations.
537						keyID := binary.BigEndian.Uint64(desig.Fingerprint[len(desig.Fingerprint)-8:])
538						designatedRevokers[keyID] = true
539					}
540				}
541			} else if current == nil {
542				// NOTE(maxtaco)
543				//
544				// See https://github.com/keybase/client/issues/2666
545				//
546				// There might have been a user attribute picture before this signature,
547				// in which case this is still a valid PGP key. In the future we might
548				// not ignore user attributes (like picture). But either way, it doesn't
549				// make sense to bail out here. Keep looking for other valid signatures.
550				//
551				// Used to be:
552				//    return nil, errors.StructuralError("signature packet found before user id packet")
553			} else {
554				current.Signatures = append(current.Signatures, pkt)
555			}
556		case *packet.PrivateKey:
557			if pkt.IsSubkey == false {
558				packets.Unread(p)
559				break EachPacket
560			}
561			err = addSubkey(e, packets, &pkt.PublicKey, pkt)
562			if err != nil {
563				return nil, err
564			}
565		case *packet.PublicKey:
566			if pkt.IsSubkey == false {
567				packets.Unread(p)
568				break EachPacket
569			}
570			err = addSubkey(e, packets, pkt, nil)
571			if err != nil {
572				return nil, err
573			}
574		default:
575			// we ignore unknown packets
576		}
577	}
578
579	if len(e.Identities) == 0 {
580		return nil, errors.StructuralError("entity without any identities")
581	}
582
583	for _, revocation := range revocations {
584		if revocation.IssuerKeyId == nil || *revocation.IssuerKeyId == e.PrimaryKey.KeyId {
585			// Key revokes itself, something that we can verify.
586			err = e.PrimaryKey.VerifyRevocationSignature(e.PrimaryKey, revocation)
587			if err == nil {
588				e.Revocations = append(e.Revocations, revocation)
589			} else {
590				return nil, errors.StructuralError("revocation signature signed by alternate key")
591			}
592		} else if revocation.IssuerKeyId != nil {
593			if _, ok := designatedRevokers[*revocation.IssuerKeyId]; ok {
594				// Revocation is done by certified designated revoker,
595				// but we can't verify the revocation.
596				e.UnverifiedRevocations = append(e.UnverifiedRevocations, revocation)
597			}
598		}
599	}
600
601	return e, nil
602}
603
604func addSubkey(e *Entity, packets *packet.Reader, pub *packet.PublicKey, priv *packet.PrivateKey) error {
605	var subKey Subkey
606	subKey.PublicKey = pub
607	subKey.PrivateKey = priv
608	var lastErr error
609	for {
610		p, err := packets.Next()
611		if err == io.EOF {
612			break
613		}
614		if err != nil {
615			return errors.StructuralError("subkey signature invalid: " + err.Error())
616		}
617		sig, ok := p.(*packet.Signature)
618		if !ok {
619			// Hit a non-signature packet, so assume we're up to the next key
620			packets.Unread(p)
621			break
622		}
623		if st := sig.SigType; st != packet.SigTypeSubkeyBinding && st != packet.SigTypeSubkeyRevocation {
624
625			// Note(maxtaco):
626			// We used to error out here, but instead, let's fast-forward past
627			// packets that are in the wrong place (like misplaced 0x13 signatures)
628			// until we get to one that works.  For a test case,
629			// see TestWithBadSubkeySignaturePackets.
630
631			continue
632		}
633		err = e.PrimaryKey.VerifyKeySignature(subKey.PublicKey, sig)
634		if err != nil {
635			// Non valid signature, so again, no need to abandon all hope, just continue;
636			// make a note of the error we hit.
637			lastErr = errors.StructuralError("subkey signature invalid: " + err.Error())
638			continue
639		}
640		switch sig.SigType {
641		case packet.SigTypeSubkeyBinding:
642			// Does the "new" sig set expiration to later date than
643			// "previous" sig?
644			if subKey.Sig == nil || subKey.Sig.ExpiresBeforeOther(sig) {
645				subKey.Sig = sig
646			}
647		case packet.SigTypeSubkeyRevocation:
648			// First writer wins
649			if subKey.Revocation == nil {
650				subKey.Revocation = sig
651			}
652		}
653	}
654
655	if subKey.Sig != nil {
656		if err := subKey.PublicKey.ErrorIfDeprecated(); err != nil {
657			// Key passed signature check but is deprecated.
658			subKey.Sig = nil
659			lastErr = err
660		}
661	}
662
663	if subKey.Sig != nil {
664		e.Subkeys = append(e.Subkeys, subKey)
665	} else {
666		if lastErr == nil {
667			lastErr = errors.StructuralError("Subkey wasn't signed; expected a 'binding' signature")
668		}
669		e.BadSubkeys = append(e.BadSubkeys, BadSubkey{Subkey: subKey, Err: lastErr})
670	}
671	return nil
672}
673
674const defaultRSAKeyBits = 2048
675
676// NewEntity returns an Entity that contains a fresh RSA/RSA keypair with a
677// single identity composed of the given full name, comment and email, any of
678// which may be empty but must not contain any of "()<>\x00".
679// If config is nil, sensible defaults will be used.
680func NewEntity(name, comment, email string, config *packet.Config) (*Entity, error) {
681	currentTime := config.Now()
682
683	bits := defaultRSAKeyBits
684	if config != nil && config.RSABits != 0 {
685		bits = config.RSABits
686	}
687
688	uid := packet.NewUserId(name, comment, email)
689	if uid == nil {
690		return nil, errors.InvalidArgumentError("user id field contained invalid characters")
691	}
692	signingPriv, err := rsa.GenerateKey(config.Random(), bits)
693	if err != nil {
694		return nil, err
695	}
696	encryptingPriv, err := rsa.GenerateKey(config.Random(), bits)
697	if err != nil {
698		return nil, err
699	}
700
701	e := &Entity{
702		PrimaryKey: packet.NewRSAPublicKey(currentTime, &signingPriv.PublicKey),
703		PrivateKey: packet.NewRSAPrivateKey(currentTime, signingPriv),
704		Identities: make(map[string]*Identity),
705	}
706	isPrimaryId := true
707	e.Identities[uid.Id] = &Identity{
708		Name:   uid.Id,
709		UserId: uid,
710		SelfSignature: &packet.Signature{
711			CreationTime: currentTime,
712			SigType:      packet.SigTypePositiveCert,
713			PubKeyAlgo:   packet.PubKeyAlgoRSA,
714			Hash:         config.Hash(),
715			IsPrimaryId:  &isPrimaryId,
716			FlagsValid:   true,
717			FlagSign:     true,
718			FlagCertify:  true,
719			IssuerKeyId:  &e.PrimaryKey.KeyId,
720		},
721	}
722
723	// If the user passes in a DefaultHash via packet.Config, set the
724	// PreferredHash for the SelfSignature.
725	if config != nil && config.DefaultHash != 0 {
726		e.Identities[uid.Id].SelfSignature.PreferredHash = []uint8{hashToHashId(config.DefaultHash)}
727	}
728
729	// Likewise for DefaultCipher.
730	if config != nil && config.DefaultCipher != 0 {
731		e.Identities[uid.Id].SelfSignature.PreferredSymmetric = []uint8{uint8(config.DefaultCipher)}
732	}
733
734	e.Subkeys = make([]Subkey, 1)
735	e.Subkeys[0] = Subkey{
736		PublicKey:  packet.NewRSAPublicKey(currentTime, &encryptingPriv.PublicKey),
737		PrivateKey: packet.NewRSAPrivateKey(currentTime, encryptingPriv),
738		Sig: &packet.Signature{
739			CreationTime:              currentTime,
740			SigType:                   packet.SigTypeSubkeyBinding,
741			PubKeyAlgo:                packet.PubKeyAlgoRSA,
742			Hash:                      config.Hash(),
743			FlagsValid:                true,
744			FlagEncryptStorage:        true,
745			FlagEncryptCommunications: true,
746			IssuerKeyId:               &e.PrimaryKey.KeyId,
747		},
748	}
749	e.Subkeys[0].PublicKey.IsSubkey = true
750	e.Subkeys[0].PrivateKey.IsSubkey = true
751
752	return e, nil
753}
754
755// SerializePrivate serializes an Entity, including private key material, to
756// the given Writer. For now, it must only be used on an Entity returned from
757// NewEntity.
758// If config is nil, sensible defaults will be used.
759func (e *Entity) SerializePrivate(w io.Writer, config *packet.Config) (err error) {
760	err = e.PrivateKey.Serialize(w)
761	if err != nil {
762		return
763	}
764	for _, ident := range e.Identities {
765		err = ident.UserId.Serialize(w)
766		if err != nil {
767			return
768		}
769		if e.PrivateKey.PrivateKey != nil {
770			err = ident.SelfSignature.SignUserId(ident.UserId.Id, e.PrimaryKey, e.PrivateKey, config)
771			if err != nil {
772				return
773			}
774		}
775		err = ident.SelfSignature.Serialize(w)
776		if err != nil {
777			return
778		}
779	}
780	for _, subkey := range e.Subkeys {
781		err = subkey.PrivateKey.Serialize(w)
782		if err != nil {
783			return
784		}
785		if e.PrivateKey.PrivateKey != nil && !config.ReuseSignatures() {
786			// If not reusing existing signatures, sign subkey using private key
787			// (subkey binding), but also sign primary key using subkey (primary
788			// key binding) if subkey is used for signing.
789			if subkey.Sig.FlagSign {
790				err = subkey.Sig.CrossSignKey(e.PrimaryKey, subkey.PrivateKey, config)
791				if err != nil {
792					return err
793				}
794			}
795			err = subkey.Sig.SignKey(subkey.PublicKey, e.PrivateKey, config)
796			if err != nil {
797				return
798			}
799		}
800
801		if subkey.Revocation != nil {
802			err = subkey.Revocation.Serialize(w)
803			if err != nil {
804				return
805			}
806		}
807
808		err = subkey.Sig.Serialize(w)
809		if err != nil {
810			return
811		}
812	}
813	return nil
814}
815
816// Serialize writes the public part of the given Entity to w. (No private
817// key material will be output).
818func (e *Entity) Serialize(w io.Writer) error {
819	err := e.PrimaryKey.Serialize(w)
820	if err != nil {
821		return err
822	}
823	for _, ident := range e.Identities {
824		err = ident.UserId.Serialize(w)
825		if err != nil {
826			return err
827		}
828		err = ident.SelfSignature.Serialize(w)
829		if err != nil {
830			return err
831		}
832		for _, sig := range ident.Signatures {
833			err = sig.Serialize(w)
834			if err != nil {
835				return err
836			}
837		}
838	}
839	for _, subkey := range e.Subkeys {
840		err = subkey.PublicKey.Serialize(w)
841		if err != nil {
842			return err
843		}
844
845		if subkey.Revocation != nil {
846			err = subkey.Revocation.Serialize(w)
847			if err != nil {
848				return err
849			}
850		}
851		err = subkey.Sig.Serialize(w)
852		if err != nil {
853			return err
854		}
855	}
856	return nil
857}
858
859// SignIdentity adds a signature to e, from signer, attesting that identity is
860// associated with e. The provided identity must already be an element of
861// e.Identities and the private key of signer must have been decrypted if
862// necessary.
863// If config is nil, sensible defaults will be used.
864func (e *Entity) SignIdentity(identity string, signer *Entity, config *packet.Config) error {
865	if signer.PrivateKey == nil {
866		return errors.InvalidArgumentError("signing Entity must have a private key")
867	}
868	if signer.PrivateKey.Encrypted {
869		return errors.InvalidArgumentError("signing Entity's private key must be decrypted")
870	}
871	ident, ok := e.Identities[identity]
872	if !ok {
873		return errors.InvalidArgumentError("given identity string not found in Entity")
874	}
875
876	sig := &packet.Signature{
877		SigType:      packet.SigTypeGenericCert,
878		PubKeyAlgo:   signer.PrivateKey.PubKeyAlgo,
879		Hash:         config.Hash(),
880		CreationTime: config.Now(),
881		IssuerKeyId:  &signer.PrivateKey.KeyId,
882	}
883	if err := sig.SignUserId(identity, e.PrimaryKey, signer.PrivateKey, config); err != nil {
884		return err
885	}
886	ident.Signatures = append(ident.Signatures, sig)
887	return nil
888}
889
890// CopySubkeyRevocations copies subkey revocations from the src Entity over
891// to the receiver entity. We need this because `gpg --export-secret-key` does
892// not appear to output subkey revocations.  In this case we need to manually
893// merge with the output of `gpg --export`.
894func (e *Entity) CopySubkeyRevocations(src *Entity) {
895	m := make(map[[20]byte]*packet.Signature)
896	for _, subkey := range src.Subkeys {
897		if subkey.Revocation != nil {
898			m[subkey.PublicKey.Fingerprint] = subkey.Revocation
899		}
900	}
901	for i, subkey := range e.Subkeys {
902		if r := m[subkey.PublicKey.Fingerprint]; r != nil {
903			e.Subkeys[i].Revocation = r
904		}
905	}
906}
907
908// CheckDesignatedRevokers will try to confirm any of designated
909// revocation of entity. For this function to work, revocation
910// issuer's key should be found in keyring. First successfully
911// verified designated revocation is returned along with the key that
912// verified it.
913func FindVerifiedDesignatedRevoke(keyring KeyRing, entity *Entity) (*packet.Signature, *Key) {
914	for _, sig := range entity.UnverifiedRevocations {
915		if sig.IssuerKeyId == nil {
916			continue
917		}
918
919		issuerKeyId := *sig.IssuerKeyId
920		issuerFingerprint := sig.IssuerFingerprint
921		keys := keyring.KeysByIdUsage(issuerKeyId, issuerFingerprint, packet.KeyFlagSign)
922		if len(keys) == 0 {
923			continue
924		}
925		for _, key := range keys {
926			err := key.PublicKey.VerifyRevocationSignature(entity.PrimaryKey, sig)
927			if err == nil {
928				return sig, &key
929			}
930		}
931	}
932
933	return nil, nil
934}
935