File: user.go

package info (click to toggle)
golang-github-protonmail-go-crypto 1.1.6-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,932 kB
  • sloc: makefile: 10
file content (223 lines) | stat: -rw-r--r-- 7,618 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
package v2

import (
	"io"
	"time"

	"github.com/ProtonMail/go-crypto/openpgp/errors"
	"github.com/ProtonMail/go-crypto/openpgp/packet"
)

// Identity represents an identity claimed by an Entity and zero or more
// assertions by other entities about that claim.
type Identity struct {
	Primary             *Entity
	Name                string // by convention, has the form "Full Name (comment) <email@example.com>"
	UserId              *packet.UserId
	SelfCertifications  []*packet.VerifiableSignature
	OtherCertifications []*packet.VerifiableSignature
	Revocations         []*packet.VerifiableSignature
}

func readUser(e *Entity, packets *packet.Reader, pkt *packet.UserId) error {
	identity := Identity{
		Primary: e,
		Name:    pkt.Id,
		UserId:  pkt,
	}
	for {
		p, err := packets.NextWithUnsupported()
		if err == io.EOF {
			break
		} else if err != nil {
			return err
		}

		unsupportedPacket, unsupported := p.(*packet.UnsupportedPacket)
		sigCandidate := p
		if unsupported {
			sigCandidate = unsupportedPacket.IncompletePacket
		}
		sig, ok := sigCandidate.(*packet.Signature)
		if !ok {
			// sigCandidate is a not a signature packet, reset and stop.
			packets.Unread(p)
			break
		} else if unsupported {
			// sigCandidate is a signature packet but unsupported.
			continue
		}

		if sig.SigType != packet.SigTypeGenericCert &&
			sig.SigType != packet.SigTypePersonaCert &&
			sig.SigType != packet.SigTypeCasualCert &&
			sig.SigType != packet.SigTypePositiveCert &&
			sig.SigType != packet.SigTypeCertificationRevocation {
			// Ignore signatures with wrong type
			continue
		}

		if sig.CheckKeyIdOrFingerprint(e.PrimaryKey) {
			if sig.SigType == packet.SigTypeCertificationRevocation {
				identity.Revocations = append(identity.Revocations, packet.NewVerifiableSig(sig))
			} else {
				identity.SelfCertifications = append(identity.SelfCertifications, packet.NewVerifiableSig(sig))
			}
			e.Identities[pkt.Id] = &identity
		} else {
			identity.OtherCertifications = append(identity.OtherCertifications, packet.NewVerifiableSig(sig))
		}
	}
	return nil
}

// Serialize serializes the user id to the writer.
func (i *Identity) Serialize(w io.Writer) error {
	if err := i.UserId.Serialize(w); err != nil {
		return err
	}
	for _, sig := range i.Revocations {
		if err := sig.Packet.Serialize(w); err != nil {
			return err
		}
	}
	for _, sig := range i.SelfCertifications {
		if err := sig.Packet.Serialize(w); err != nil {
			return err
		}
	}
	for _, sig := range i.OtherCertifications {
		if err := sig.Packet.Serialize(w); err != nil {
			return err
		}
	}
	return nil
}

// Verify checks if the user-id is valid by checking:
// - that a valid self-certification exists and is not expired
// - that user-id has not been revoked at the given point in time
// If date is zero (i.e., date.IsZero() == true) the time checks are not performed.
func (i *Identity) Verify(date time.Time, config *packet.Config) (selfSignature *packet.Signature, err error) {
	if selfSignature, err = i.LatestValidSelfCertification(date, config); err != nil {
		return
	}
	if i.Revoked(selfSignature, date, config) {
		return nil, errors.StructuralError("user-id is revoked")
	}
	return
}

// Revoked returns whether the identity has been revoked by a self-signature.
// Note that third-party revocation signatures are not supported.
func (i *Identity) Revoked(selfCertification *packet.Signature, date time.Time, config *packet.Config) bool {
	// Verify revocations first
	for _, revocation := range i.Revocations {
		if selfCertification == nil || // if there is not selfCertification verify revocation
			selfCertification.IssuerKeyId == nil ||
			revocation.Packet.IssuerKeyId == nil ||
			(*selfCertification.IssuerKeyId == *revocation.Packet.IssuerKeyId) { // check matching key id
			if revocation.Valid == nil {
				// Verify revocation signature (not verified yet).
				err := i.Primary.PrimaryKey.VerifyUserIdSignature(i.Name, i.Primary.PrimaryKey, revocation.Packet)
				if err == nil {
					err = checkSignatureDetails(revocation.Packet, date, config)
				}
				valid := err == nil
				revocation.Valid = &valid
			}

			if *revocation.Valid &&
				(date.IsZero() || // Check revocation not expired
					!revocation.Packet.SigExpired(date)) &&
				(selfCertification == nil || // Check that revocation is not older than the selfCertification
					selfCertification.CreationTime.Unix() <= revocation.Packet.CreationTime.Unix()) {
				return true
			}
		}
	}
	return false
}

// ReSign resigns the latest valid self-certification with the given config.
func (i *Identity) ReSign(config *packet.Config) error {
	selectedSig, err := i.LatestValidSelfCertification(config.Now(), config)
	if err != nil {
		return err
	}
	if err = selectedSig.SignUserId(
		i.UserId.Id,
		i.Primary.PrimaryKey,
		i.Primary.PrivateKey,
		config,
	); err != nil {
		return err
	}
	return nil
}

// SignIdentity adds a signature to e, from signer, attesting that identity is
// associated with e. The provided identity must already be an element of
// e.Identities and the private key of signer must have been decrypted if
// necessary.
// If config is nil, sensible defaults will be used.
func (ident *Identity) SignIdentity(signer *Entity, config *packet.Config) error {
	certificationKey, ok := signer.CertificationKey(config.Now(), config)
	if !ok {
		return errors.InvalidArgumentError("no valid certification key found")
	}

	if certificationKey.PrivateKey.Encrypted {
		return errors.InvalidArgumentError("signing Entity's private key must be decrypted")
	}

	if !ok {
		return errors.InvalidArgumentError("given identity string not found in Entity")
	}

	sig := createSignaturePacket(certificationKey.PublicKey, packet.SigTypeGenericCert, config)

	signingUserID := config.SigningUserId()
	if signingUserID != "" {
		if _, ok := signer.Identities[signingUserID]; !ok {
			return errors.InvalidArgumentError("signer identity string not found in signer Entity")
		}
		sig.SignerUserId = &signingUserID
	}

	if err := sig.SignUserId(ident.Name, ident.Primary.PrimaryKey, certificationKey.PrivateKey, config); err != nil {
		return err
	}
	ident.OtherCertifications = append(ident.OtherCertifications, packet.NewVerifiableSig(sig))
	return nil
}

// LatestValidSelfCertification returns the latest valid self-signature of this user-id
// that is not newer than the provided date.
// Does not consider signatures that are expired.
// If date is zero (i.e., date.IsZero() == true) the expiration checks are not performed.
// Returns a StructuralError if no valid self-certification is found.
func (i *Identity) LatestValidSelfCertification(date time.Time, config *packet.Config) (selectedSig *packet.Signature, err error) {
	for sigIdx := len(i.SelfCertifications) - 1; sigIdx >= 0; sigIdx-- {
		sig := i.SelfCertifications[sigIdx]
		if (date.IsZero() || date.Unix() >= sig.Packet.CreationTime.Unix()) && // SelfCertification must be older than date
			(selectedSig == nil || selectedSig.CreationTime.Unix() < sig.Packet.CreationTime.Unix()) { // Newer ones are preferred
			if sig.Valid == nil {
				// Verify revocation signature (not verified yet).
				err = i.Primary.PrimaryKey.VerifyUserIdSignature(i.Name, i.Primary.PrimaryKey, sig.Packet)
				if err == nil {
					err = checkSignatureDetails(sig.Packet, date, config)
				}
				valid := err == nil
				sig.Valid = &valid
			}
			if *sig.Valid && (date.IsZero() || !sig.Packet.SigExpired(date)) {
				selectedSig = sig.Packet
			}
		}
	}
	if selectedSig == nil {
		return nil, errors.StructuralError("no valid certification signature found for identity")
	}
	return
}