Debian Codegraph @

crypto/signature.go

raw symbols SCIP
1 package crypto
2
3 import (
4 "bytes"
5 "errors"
6 "fmt"
7 "time"
8
9 pgpErrors "github.com/ProtonMail/go-crypto/openpgp/errors"
10 "github.com/ProtonMail/go-crypto/openpgp/packet"
11 openpgp "github.com/ProtonMail/go-crypto/openpgp/v2"
12
13 "github.com/ProtonMail/gopenpgp/v3/constants"
14 )
15
16 // VerifiedSignature is a result of a signature verification.
17 type VerifiedSignature struct {
18 Signature *packet.Signature
19 SignedBy *Key
20 SignatureError *SignatureVerificationError
21 }
22
23 // SignatureVerificationError is returned from Decrypt and VerifyDetached
24 // functions when signature verification fails.
25 type SignatureVerificationError struct {
26 Status int
27 Message string
28 Cause error
29 }
30
31 // VerifyResult is a result of a pgp message signature verification.
32 type VerifyResult struct {
33 // All signatures found in the message.
34 Signatures []*VerifiedSignature
35 // The selected signature for the result.
36 // i.e., the first successfully verified signature in Signatures
37 // or the last signature Signatures[len(Signatures)-1].
38 selectedSignature *VerifiedSignature
39 // The signature error of the selected signature.
40 // Is nil for a successful verification.
41 signatureError *SignatureVerificationError
42 }
43
44 // SignatureCreationTime returns the creation time of
45 // the selected verified signature if found, else returns 0.
46 func (vr *VerifyResult) SignatureCreationTime() int64 {
47 if vr.selectedSignature == nil || vr.selectedSignature.Signature == nil {
48 return 0
49 }
50 return vr.selectedSignature.Signature.CreationTime.Unix()
51 }
52
53 // SignedWithType returns the type of the signature if found, else returns 0.
54 // Not supported in go-mobile use SignedWithTypeInteger instead.
55 func (vr *VerifyResult) SignedWithType() packet.SignatureType {
56 if vr.selectedSignature == nil || vr.selectedSignature.Signature == nil {
57 return 0
58 }
59 return vr.selectedSignature.Signature.SigType
60 }
61
62 // SignedWithTypeInt8 returns the type of the signature as int8 type if found, else returns 0.
63 // See constants.SigType... for the different types.
64 func (vr *VerifyResult) SignedWithTypeInt8() int8 {
65 return int8(vr.SignedWithType())
66 }
67
68 // SignedByKeyId returns the key id of the key that was used to verify the selected signature,
69 // if found, else returns 0.
70 // Not supported in go-mobile use SignedByKeyIdString instead.
71 func (vr *VerifyResult) SignedByKeyId() uint64 {
72 if vr.selectedSignature == nil || vr.selectedSignature.Signature == nil {
73 return 0
74 }
75 return *vr.selectedSignature.Signature.IssuerKeyId
76 }
77
78 // SignedByKeyIdHex returns the key id of the key that was used to verify the selected signature
79 // as a hex encoded string.
80 // Helper for go-mobile.
81 func (vr *VerifyResult) SignedByKeyIdHex() string {
82 return keyIDToHex(vr.SignedByKeyId())
83 }
84
85 // SignedByFingerprint returns the key fingerprint of the key that was used to verify the selected signature,
86 // if found, else returns nil.
87 func (vr *VerifyResult) SignedByFingerprint() []byte {
88 if vr.selectedSignature == nil || vr.selectedSignature.Signature == nil {
89 return nil
90 }
91 if vr.selectedSignature.Signature.IssuerFingerprint != nil {
92 return vr.selectedSignature.Signature.IssuerFingerprint
93 }
94 if vr.selectedSignature.SignedBy != nil {
95 return vr.selectedSignature.SignedBy.GetFingerprintBytes()
96 }
97 return nil
98 }
99
100 // SignedByKey returns the key that was used to verify the selected signature,
101 // if found, else returns nil.
102 func (vr *VerifyResult) SignedByKey() *Key {
103 if vr.selectedSignature == nil || vr.selectedSignature.Signature == nil {
104 return nil
105 }
106 key := vr.selectedSignature.SignedBy
107 if key == nil {
108 return nil
109 }
110 return &Key{
111 entity: key.entity,
112 }
113 }
114
115 // Signature returns the serialized openpgp signature packet of the selected signature.
116 func (vr *VerifyResult) Signature() ([]byte, error) {
117 if vr.selectedSignature == nil || vr.selectedSignature.Signature == nil {
118 return nil, errors.New("gopenpgp: no signature present")
119 }
120 var serializedSignature bytes.Buffer
121 if err := vr.selectedSignature.Signature.Serialize(&serializedSignature); err != nil {
122 return nil, fmt.Errorf("gopenpgp: signature serialization failed: %w", err)
123 }
124 return serializedSignature.Bytes(), nil
125 }
126
127 // SignatureError returns nil if no signature err occurred else
128 // the signature error.
129 func (vr *VerifyResult) SignatureError() error {
130 if vr == nil || vr.signatureError == nil {
131 return nil
132 }
133 return *vr.signatureError
134 }
135
136 // SignatureErrorExplicit returns nil if no signature err occurred else
137 // the explicit signature error.
138 func (vr *VerifyResult) SignatureErrorExplicit() *SignatureVerificationError {
139 return vr.signatureError
140 }
141
142 // ConstrainToTimeRange updates the signature result to only consider
143 // signatures with a creation time within the given time frame.
144 // unixFrom and unixTo are in unix time and are inclusive.
145 func (vr *VerifyResult) ConstrainToTimeRange(unixFrom int64, unixTo int64) {
146 for _, signature := range vr.Signatures {
147 if signature.Signature != nil && signature.SignatureError == nil {
148 sigUnixTime := signature.Signature.CreationTime.Unix()
149 if sigUnixTime < unixFrom || sigUnixTime > unixTo {
150 sigError := newSignatureFailed(errors.New("gopenpgp: signature creation time is out of range"))
151 signature.SignatureError = &sigError
152 }
153 }
154 }
155 // Reselect
156 vr.selectSignature()
157 }
158
159 // Error is the base method for all errors.
160 func (e SignatureVerificationError) Error() string {
161 if e.Cause != nil {
162 return fmt.Sprintf("Signature Verification Error: %v caused by %v", e.Message, e.Cause)
163 }
164 return fmt.Sprintf("Signature Verification Error: %v", e.Message)
165 }
166
167 // Unwrap returns the cause of failure.
168 func (e SignatureVerificationError) Unwrap() error {
169 return e.Cause
170 }
171
172 // ------------------
173 // Internal functions
174 // ------------------
175
176 // selectSignature selects the main signature to show in the result.
177 // Selection policy:
178 // first successfully verified or
179 // last signature with an error and a matching key or
180 // last signature with an error if no key matched.
181 func (vr *VerifyResult) selectSignature() {
182 var keyMatch bool
183 for _, signature := range vr.Signatures {
184 if signature.SignedBy != nil {
185 keyMatch = true
186 vr.selectedSignature = signature
187 vr.signatureError = signature.SignatureError
188 if signature.SignatureError == nil {
189 break
190 }
191 }
192 }
193 if !keyMatch && len(vr.Signatures) > 0 {
194 signature := vr.Signatures[len(vr.Signatures)-1]
195 vr.selectedSignature = signature
196 vr.signatureError = signature.SignatureError
197 }
198 }
199
200 // newSignatureFailed creates a new SignatureVerificationError, type
201 // SignatureFailed.
202 func newSignatureBadContext(cause error) SignatureVerificationError {
203 return SignatureVerificationError{
204 Status: constants.SIGNATURE_BAD_CONTEXT,
205 Message: "Invalid signature context",
206 Cause: cause,
207 }
208 }
209
210 func newSignatureFailed(cause error) SignatureVerificationError {
211 return SignatureVerificationError{
212 Status: constants.SIGNATURE_FAILED,
213 Message: "Invalid signature",
214 Cause: cause,
215 }
216 }
217
218 // newSignatureNotSigned creates a new SignatureVerificationError, type
219 // SignatureNotSigned.
220 func newSignatureNotSigned() SignatureVerificationError {
221 return SignatureVerificationError{
222 Status: constants.SIGNATURE_NOT_SIGNED,
223 Message: "Missing signature",
224 }
225 }
226
227 // newSignatureNoVerifier creates a new SignatureVerificationError, type
228 // SignatureNoVerifier.
229 func newSignatureNoVerifier() SignatureVerificationError {
230 return SignatureVerificationError{
231 Status: constants.SIGNATURE_NO_VERIFIER,
232 Message: "No matching signature",
233 }
234 }
235
236 // processSignatureExpiration handles signature time verification manually, so
237 // we can ignore signature expired errors if configured so.
238 func processSignatureExpiration(sig *packet.Signature, toCheck error, verifyTime int64, disableTimeCheck bool) error {
239 if sig == nil || !errors.Is(toCheck, pgpErrors.ErrSignatureExpired) {
240 return toCheck
241 }
242 if disableTimeCheck || verifyTime == 0 {
243 return nil
244 }
245 return toCheck
246 }
247
248 func createVerifyResult(
249 md *openpgp.MessageDetails,
250 verifierKey *KeyRing,
251 verificationContext *VerificationContext,
252 verifyTime int64,
253 disableTimeCheck bool,
254 ) (*VerifyResult, error) {
255 if !md.IsSigned {
256 signatureError := newSignatureNotSigned()
257 return &VerifyResult{
258 signatureError: &signatureError,
259 }, nil
260 }
261 if !md.IsVerified {
262 return nil, errors.New("gopenpgp: message has not been verified")
263 }
264
265 verifiedSignatures := make([]*VerifiedSignature, len(md.SignatureCandidates))
266 for candidateIndex, signature := range md.SignatureCandidates {
267 var singedBy *Key
268 if signature.SignedBy != nil {
269 singedBy = &Key{
270 entity: signature.SignedBy.Entity,
271 }
272 }
273 verifiedSignature := &VerifiedSignature{
274 Signature: signature.CorrespondingSig,
275 SignedBy: singedBy,
276 }
277 signature.SignatureError = processSignatureExpiration(
278 signature.CorrespondingSig,
279 signature.SignatureError,
280 verifyTime,
281 disableTimeCheck,
282 )
283 var signatureError SignatureVerificationError
284
285 switch {
286 case verifierKey == nil || len(verifierKey.entities) == 0 ||
287 errors.Is(signature.SignatureError, pgpErrors.ErrUnknownIssuer):
288 signatureError = newSignatureNoVerifier()
289 case signature.SignatureError != nil:
290 signatureError = newSignatureFailed(signature.SignatureError)
291 case verificationContext != nil:
292 err := verificationContext.verifyContext(signature.CorrespondingSig)
293 if err != nil {
294 signatureError = newSignatureBadContext(err)
295 }
296 }
297 if signatureError.Status != constants.SIGNATURE_OK {
298 verifiedSignature.SignatureError = &signatureError
299 }
300 verifiedSignatures[candidateIndex] = verifiedSignature
301 }
302
303 verifyResult := &VerifyResult{
304 Signatures: verifiedSignatures,
305 }
306
307 // Select the signature to show in the result
308 verifyResult.selectSignature()
309 return verifyResult, nil
310 }
311
312 // SigningContext gives the context that will be
313 // included in the signature's notation data.
314 type SigningContext struct {
315 Value string
316 IsCritical bool
317 }
318
319 // NewSigningContext creates a new signing context.
320 // The value is set to the notation data.
321 // isCritical controls whether the notation is flagged as a critical packet.
322 func NewSigningContext(value string, isCritical bool) *SigningContext {
323 return &SigningContext{Value: value, IsCritical: isCritical}
324 }
325
326 func (context *SigningContext) getNotation() *packet.Notation {
327 return &packet.Notation{
328 Name: constants.SignatureContextName,
329 Value: []byte(context.Value),
330 IsCritical: context.IsCritical,
331 IsHumanReadable: true,
332 }
333 }
334
335 // VerificationContext gives the context that will be
336 // used to verify the signature.
337 type VerificationContext struct {
338 Value string
339 IsRequired bool
340 RequiredAfter int64
341 }
342
343 // NewVerificationContext creates a new verification context.
344 // The value is checked against the signature's notation data.
345 // If isRequired is false, the signature is allowed to have no context set.
346 // If requiredAfter is != 0, the signature is allowed to have no context set if it
347 // was created before the unix time set in requiredAfter.
348 func NewVerificationContext(value string, isRequired bool, requiredAfter int64) *VerificationContext {
349 return &VerificationContext{
350 Value: value,
351 IsRequired: isRequired,
352 RequiredAfter: requiredAfter,
353 }
354 }
355
356 func (context *VerificationContext) isRequiredAtTime(signatureTime time.Time) bool {
357 return context.IsRequired &&
358 (context.RequiredAfter == 0 || signatureTime.After(time.Unix(context.RequiredAfter, 0)))
359 }
360
361 func findContext(notations []*packet.Notation) (string, error) {
362 context := ""
363 for _, notation := range notations {
364 if notation.Name == constants.SignatureContextName {
365 if context != "" {
366 return "", errors.New("gopenpgp: signature has multiple context notations")
367 }
368 if !notation.IsHumanReadable {
369 return "", errors.New("gopenpgp: context notation was not set as human-readable")
370 }
371 context = string(notation.Value)
372 }
373 }
374 return context, nil
375 }
376
377 func (context *VerificationContext) verifyContext(sig *packet.Signature) error {
378 if sig == nil {
379 return errors.New("gopenpgp: no signature packet found for signature")
380 }
381 signatureContext, err := findContext(sig.Notations)
382 if err != nil {
383 return err
384 }
385 if signatureContext != context.Value {
386 contextRequired := context.isRequiredAtTime(sig.CreationTime)
387 if contextRequired {
388 return errors.New("gopenpgp: signature did not have the required context")
389 } else if signatureContext != "" {
390 return errors.New("gopenpgp: signature had a wrong context")
391 }
392 }
393
394 return nil
395 }