Debian Codegraph @

openpgp/v2/read.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 implements high level operations on OpenPGP messages.
6 package v2
7
8 import (
9 "bytes"
10 "crypto"
11 _ "crypto/sha256"
12 _ "crypto/sha512"
13 "hash"
14 "io"
15 "io/ioutil"
16 "strconv"
17 "time"
18
19 "github.com/ProtonMail/go-crypto/openpgp/armor"
20 "github.com/ProtonMail/go-crypto/openpgp/errors"
21 "github.com/ProtonMail/go-crypto/openpgp/internal/algorithm"
22 "github.com/ProtonMail/go-crypto/openpgp/packet"
23 _ "golang.org/x/crypto/sha3"
24 )
25
26 // SignatureType is the armor type for a PGP signature.
27 var SignatureType = "PGP SIGNATURE"
28
29 // MessageType is the armor type for a PGP message.
30 var MessageType = "PGP MESSAGE"
31
32 // readArmored reads an armored block with the given type.
33 func readArmored(r io.Reader, expectedType string) (body io.Reader, err error) {
34 block, err := armor.Decode(r)
35 if err != nil {
36 return
37 }
38
39 if block.Type != expectedType {
40 return nil, errors.InvalidArgumentError("expected '" + expectedType + "', got: " + block.Type)
41 }
42
43 return block.Body, nil
44 }
45
46 // MessageDetails contains the result of parsing an OpenPGP encrypted and/or
47 // signed message.
48 type MessageDetails struct {
49 IsEncrypted bool // true if the message was encrypted.
50 EncryptedToKeyIds []uint64 // the list of recipient key ids.
51 IsSymmetricallyEncrypted bool // true if a passphrase could have decrypted the message.
52 DecryptedWith Key // the private key used to decrypt the message, if any.
53 DecryptedWithAlgorithm packet.CipherFunction // Stores the algorithm used to decrypt the message, if any.
54 IsSigned bool // true if the message is signed.
55 LiteralData *packet.LiteralData // the metadata of the contents
56 UnverifiedBody io.Reader // the contents of the message.
57 CheckRecipients bool // Indicates if the intended recipients should be checked
58
59 SessionKey []byte // Caches the session key if the flag in packet.Config is set to true and a session key was present.
60
61 // If IsSigned is true then the signature candidates will
62 // be verified as UnverifiedBody is read. The signature cannot be
63 // checked until the whole of UnverifiedBody is read so UnverifiedBody
64 // must be consumed until EOF before the data can be trusted. Even if a
65 // message isn't signed (or the signer is unknown) the data may contain
66 // an authentication code that is only checked once UnverifiedBody has
67 // been consumed. Once EOF has been seen, the following fields are
68 // valid. (An authentication code failure is reported as a
69 // SignatureError error when reading from UnverifiedBody.)
70 IsVerified bool // true if the signatures have been verified else false
71 SignatureCandidates []*SignatureCandidate // stores state for all signatures of this message
72 SignedBy *Key // the issuer key of the fist successfully verified signature, if any found.
73 Signature *packet.Signature // the first successfully verified signature, if any found.
74 // SignatureError is nil if one of the signatures in the message verifies successfully
75 // else it points to the last observed signature error.
76 // The error of each signature verification can be inspected by iterating trough
77 // SignatureCandidates.
78 SignatureError error
79 // SelectedCandidate points to the signature candidate the SignatureError error stems from or
80 // the selected successfully verified signature candidate.
81 SelectedCandidate *SignatureCandidate
82
83 decrypted io.ReadCloser
84 }
85
86 // A PromptFunction is used as a callback by functions that may need to decrypt
87 // a private key, or prompt for a passphrase. It is called with a list of
88 // acceptable, encrypted private keys and a boolean that indicates whether a
89 // passphrase is usable. It should either decrypt a private key or return a
90 // passphrase to try. If the decrypted private key or given passphrase isn't
91 // correct, the function will be called again, forever. Any error returned will
92 // be passed up.
93 type PromptFunction func(keys []Key, symmetric bool) ([]byte, error)
94
95 // A keyEnvelopePair is used to store a private key with the envelope that
96 // contains a symmetric key, encrypted with that key.
97 type keyEnvelopePair struct {
98 key Key
99 encryptedKey *packet.EncryptedKey
100 }
101
102 // ReadMessage parses an OpenPGP message that may be signed and/or encrypted.
103 // The given KeyRing should contain both public keys (for signature
104 // verification) and, possibly encrypted, private keys for decrypting.
105 // If config is nil, sensible defaults will be used.
106 func ReadMessage(r io.Reader, keyring KeyRing, prompt PromptFunction, config *packet.Config) (md *MessageDetails, err error) {
107 var p packet.Packet
108
109 var symKeys []*packet.SymmetricKeyEncrypted
110 var pubKeys []keyEnvelopePair
111 // Integrity protected encrypted packet: SymmetricallyEncrypted or AEADEncrypted
112 var edp packet.EncryptedDataPacket
113 var packets packet.PacketReader
114 if config.StrictPacketSequence() {
115 packets = packet.NewCheckReader(r)
116 } else {
117 packets = packet.NewReader(r)
118 }
119 md = new(MessageDetails)
120 md.IsEncrypted = true
121 md.CheckRecipients = config.IntendedRecipients()
122
123 // The message, if encrypted, starts with a number of packets
124 // containing an encrypted decryption key. The decryption key is either
125 // encrypted to a public key, or with a passphrase. This loop
126 // collects these packets.
127 ParsePackets:
128 for {
129 p, err = packets.Next()
130 if err != nil {
131 return nil, err
132 }
133 switch p := p.(type) {
134 case *packet.SymmetricKeyEncrypted:
135 // This packet contains the decryption key encrypted with a passphrase.
136 md.IsSymmetricallyEncrypted = true
137 symKeys = append(symKeys, p)
138 case *packet.EncryptedKey:
139 // This packet contains the decryption key encrypted to a public key.
140 md.EncryptedToKeyIds = append(md.EncryptedToKeyIds, p.KeyId)
141 switch p.Algo {
142 case packet.PubKeyAlgoRSA, packet.PubKeyAlgoRSAEncryptOnly, packet.PubKeyAlgoElGamal, packet.PubKeyAlgoECDH,
143 packet.PubKeyAlgoX25519, packet.PubKeyAlgoX448,
144 packet.PubKeyAlgoMlkem768X25519, packet.PubKeyAlgoMlkem1024X448:
145 break
146 default:
147 continue
148 }
149 if keyring != nil {
150 unverifiedEntities := keyring.EntitiesById(p.KeyId)
151 for _, unverifiedEntity := range unverifiedEntities {
152 // Do not check key expiration to allow decryption of old messages
153 keys := unverifiedEntity.DecryptionKeys(p.KeyId, time.Time{}, config)
154 for _, key := range keys {
155 pubKeys = append(pubKeys, keyEnvelopePair{key, p})
156 }
157 }
158 }
159 case *packet.SymmetricallyEncrypted:
160 if !p.IntegrityProtected && !config.AllowUnauthenticatedMessages() {
161 return nil, errors.UnsupportedError("message is not integrity protected")
162 }
163 edp = p
164 if p.Version == 2 { // SEIPD v2 packet stores the decryption algorithm
165 md.DecryptedWithAlgorithm = p.Cipher
166 }
167 break ParsePackets
168 case *packet.AEADEncrypted:
169 edp = p
170 break ParsePackets
171 case *packet.Compressed, *packet.LiteralData, *packet.OnePassSignature, *packet.Signature:
172 // This message isn't encrypted.
173 if len(symKeys) != 0 || len(pubKeys) != 0 {
174 return nil, errors.StructuralError("key material not followed by encrypted message")
175 }
176 packets.Unread(p)
177 md.IsEncrypted = false
178 return readSignedMessage(packets, md, keyring, config)
179 }
180 }
181
182 var candidates []Key
183 var decrypted io.ReadCloser
184
185 // Now that we have the list of encrypted keys we need to decrypt at
186 // least one of them or, if we cannot, we need to call the prompt
187 // function so that it can decrypt a key or give us a passphrase.
188 FindKey:
189 for {
190 // See if any of the keys already have a private key available
191 candidates = candidates[:0]
192 candidateFingerprints := make(map[string]bool)
193
194 for _, pk := range pubKeys {
195 if pk.key.PrivateKey == nil {
196 continue
197 }
198 if !pk.key.PrivateKey.Encrypted {
199 if len(pk.encryptedKey.Key) == 0 {
200 errDec := pk.encryptedKey.Decrypt(pk.key.PrivateKey, config)
201 if errDec != nil {
202 continue
203 }
204 }
205 // Try to decrypt symmetrically encrypted
206 decrypted, err = edp.Decrypt(pk.encryptedKey.CipherFunc, pk.encryptedKey.Key)
207 if err != nil && err != errors.ErrKeyIncorrect {
208 return nil, err
209 }
210 if decrypted != nil {
211 md.DecryptedWith = pk.key
212 if md.DecryptedWithAlgorithm == 0 { // if no SEIPD v2 packet, key packet stores the decryption algorithm
213 md.DecryptedWithAlgorithm = pk.encryptedKey.CipherFunc
214 }
215 if config.RetrieveSessionKey() {
216 md.SessionKey = pk.encryptedKey.Key
217 }
218 break FindKey
219 }
220 } else {
221 fpr := string(pk.key.PublicKey.Fingerprint[:])
222 if v := candidateFingerprints[fpr]; v {
223 continue
224 }
225 candidates = append(candidates, pk.key)
226 candidateFingerprints[fpr] = true
227 }
228 }
229
230 if len(candidates) == 0 && len(symKeys) == 0 {
231 return nil, errors.ErrKeyIncorrect
232 }
233
234 if prompt == nil {
235 return nil, errors.ErrKeyIncorrect
236 }
237
238 passphrase, err := prompt(candidates, len(symKeys) != 0)
239 if err != nil {
240 return nil, err
241 }
242
243 // Try the symmetric passphrase first
244 if len(symKeys) != 0 && passphrase != nil {
245 for _, s := range symKeys {
246 key, cipherFunc, err := s.Decrypt(passphrase)
247 // In v4, on wrong passphrase, session key decryption is very likely to result in an invalid cipherFunc:
248 // only for < 5% of cases we will proceed to decrypt the data
249 if err == nil {
250 decrypted, err = edp.Decrypt(cipherFunc, key)
251 if err != nil {
252 return nil, err
253 }
254 if decrypted != nil {
255 if md.DecryptedWithAlgorithm == 0 { // if no SEIPD v2 packet, key packet stores the decryption algorithm
256 md.DecryptedWithAlgorithm = cipherFunc
257 }
258 if config.RetrieveSessionKey() {
259 md.SessionKey = key
260 }
261 break FindKey
262 }
263 }
264 }
265 }
266 }
267
268 md.decrypted = decrypted
269 if err := packets.Push(decrypted); err != nil {
270 return nil, err
271 }
272 mdFinal, sensitiveParsingErr := readSignedMessage(packets, md, keyring, config)
273 if sensitiveParsingErr != nil {
274 return nil, errors.HandleSensitiveParsingError(sensitiveParsingErr, md.decrypted != nil)
275 }
276 return mdFinal, nil
277 }
278
279 // SignatureCandidate keeps state about a signature that can be potentially verified.
280 type SignatureCandidate struct {
281 OPSVersion int
282 SigType packet.SignatureType
283 HashAlgorithm crypto.Hash
284 PubKeyAlgo packet.PublicKeyAlgorithm
285 IssuerKeyId uint64
286 IssuerFingerprint []byte
287 Salt []byte // v6 only
288
289 SignedByEntity *Entity
290 SignedBy *Key // the key of the signer, if available. (OPS)
291 SignatureError error // nil if the signature is valid or not checked.
292 CorrespondingSig *packet.Signature // the candidate's signature packet
293 Hash, WrappedHash hash.Hash // hashes for this signature candidate (OPS)
294 }
295
296 func newSignatureCandidate(ops *packet.OnePassSignature) (sigCandidate *SignatureCandidate) {
297 sigCandidate = &SignatureCandidate{
298 OPSVersion: ops.Version,
299 SigType: ops.SigType,
300 HashAlgorithm: ops.Hash,
301 PubKeyAlgo: ops.PubKeyAlgo,
302 IssuerKeyId: ops.KeyId,
303 IssuerFingerprint: ops.KeyFingerprint,
304 Salt: ops.Salt,
305 }
306 sigCandidate.Hash, sigCandidate.WrappedHash, sigCandidate.SignatureError = hashForSignature(
307 sigCandidate.HashAlgorithm,
308 sigCandidate.SigType,
309 sigCandidate.Salt,
310 )
311 return
312 }
313
314 func newSignatureCandidateFromSignature(sig *packet.Signature) (sigCandidate *SignatureCandidate, err error) {
315 if sig.IssuerKeyId == nil {
316 return nil, errors.StructuralError("signature doesn't have an issuer")
317 }
318
319 sigCandidate = &SignatureCandidate{
320 SigType: sig.SigType,
321 HashAlgorithm: sig.Hash,
322 PubKeyAlgo: sig.PubKeyAlgo,
323 IssuerKeyId: *sig.IssuerKeyId,
324 IssuerFingerprint: sig.IssuerFingerprint,
325 Salt: sig.Salt(),
326 }
327 sigCandidate.OPSVersion = 3
328 if sig.Version == 6 {
329 sigCandidate.OPSVersion = sig.Version
330 }
331 sigCandidate.Hash, sigCandidate.WrappedHash, sigCandidate.SignatureError = hashForSignature(
332 sigCandidate.HashAlgorithm,
333 sigCandidate.SigType,
334 sigCandidate.Salt,
335 )
336 sigCandidate.CorrespondingSig = sig
337 return
338 }
339
340 func (sc *SignatureCandidate) validate() bool {
341 if sc.CorrespondingSig == nil {
342 return false
343 }
344 correspondingSig := sc.CorrespondingSig
345 invalidV3 := sc.OPSVersion == 3 && correspondingSig.Version == 6
346 invalidV6 := sc.OPSVersion == 6 &&
347 (correspondingSig.Version != 6 ||
348 !bytes.Equal(sc.IssuerFingerprint, correspondingSig.IssuerFingerprint) ||
349 !bytes.Equal(sc.Salt, correspondingSig.Salt()))
350 return !invalidV3 && !invalidV6 &&
351 sc.SigType == correspondingSig.SigType &&
352 sc.HashAlgorithm == correspondingSig.Hash &&
353 sc.PubKeyAlgo == correspondingSig.PubKeyAlgo &&
354 correspondingSig.IssuerKeyId != nil &&
355 sc.IssuerKeyId == *correspondingSig.IssuerKeyId
356 }
357
358 // readSignedMessage reads a possibly signed message if mdin is non-zero then
359 // that structure is updated and returned. Otherwise a fresh MessageDetails is
360 // used.
361 func readSignedMessage(packets packet.PacketReader, mdin *MessageDetails, keyring KeyRing, config *packet.Config) (md *MessageDetails, err error) {
362 if mdin == nil {
363 mdin = new(MessageDetails)
364 }
365 md = mdin
366
367 var p packet.Packet
368 var prevLast bool
369 FindLiteralData:
370 for {
371 p, err = packets.Next()
372 if err != nil {
373 return nil, err
374 }
375 switch p := p.(type) {
376 case *packet.Compressed:
377 if err := packets.Push(p.LimitedBodyReader(config.DecompressedMessageSizeLimit())); err != nil {
378 return nil, err
379 }
380 case *packet.OnePassSignature:
381 if prevLast {
382 return nil, errors.UnsupportedError("nested signature packets")
383 }
384
385 if p.IsLast {
386 prevLast = true
387 }
388
389 sigCandidate := newSignatureCandidate(p)
390 md.IsSigned = true
391 if keyring != nil {
392 keys := keyring.EntitiesById(p.KeyId)
393 if len(keys) > 0 {
394 sigCandidate.SignedByEntity = keys[0]
395 }
396 }
397 // If a message contains more than one one-pass signature, then the Signature packets bracket the message
398 md.SignatureCandidates = append([]*SignatureCandidate{sigCandidate}, md.SignatureCandidates...)
399 case *packet.Signature:
400 // Old style signature i.e., sig | literal
401 sigCandidate, err := newSignatureCandidateFromSignature(p)
402 if err != nil {
403 return nil, err
404 }
405 md.IsSigned = true
406 if keyring != nil {
407 keys := keyring.EntitiesById(sigCandidate.IssuerKeyId)
408 if len(keys) > 0 {
409 sigCandidate.SignedByEntity = keys[0]
410 }
411 }
412 md.SignatureCandidates = append([]*SignatureCandidate{sigCandidate}, md.SignatureCandidates...)
413 case *packet.LiteralData:
414 md.LiteralData = p
415 break FindLiteralData
416 case *packet.EncryptedKey,
417 *packet.SymmetricKeyEncrypted,
418 *packet.AEADEncrypted,
419 *packet.SymmetricallyEncrypted:
420 return nil, errors.UnsupportedError("cannot read signed message with encrypted data")
421 }
422 }
423
424 if md.IsSigned {
425 md.UnverifiedBody = &signatureCheckReader{packets, md, config, md.LiteralData.Body}
426 } else {
427 md.UnverifiedBody = &checkReader{md, packets, false}
428 }
429
430 return md, nil
431 }
432
433 func wrapHashForSignature(hashFunc hash.Hash, sigType packet.SignatureType) (hash.Hash, error) {
434 switch sigType {
435 case packet.SigTypeBinary:
436 return hashFunc, nil
437 case packet.SigTypeText:
438 return NewCanonicalTextHash(hashFunc), nil
439 }
440 return nil, errors.UnsupportedError("unsupported signature type: " + strconv.Itoa(int(sigType)))
441 }
442
443 // hashForSignature returns a pair of hashes that can be used to verify a
444 // signature. The signature may specify that the contents of the signed message
445 // should be preprocessed (i.e. to normalize line endings). Thus this function
446 // returns two hashes. The first, directHash, will feed directly into the signature algorithm.
447 // The second, wrappedHash, should be used to hash the message itself and performs any needed preprocessing.
448 func hashForSignature(hashFunc crypto.Hash, sigType packet.SignatureType, sigSalt []byte) (directHash hash.Hash, wrappedHash hash.Hash, err error) {
449 if _, ok := algorithm.HashToHashIdWithSha1(hashFunc); !ok {
450 return nil, nil, errors.UnsupportedError("unsupported hash function")
451 }
452 if !hashFunc.Available() {
453 return nil, nil, errors.UnsupportedError("hash not available: " + strconv.Itoa(int(hashFunc)))
454 }
455 h := hashFunc.New()
456 if sigSalt != nil {
457 h.Write(sigSalt)
458 }
459 wrappedHash, err = wrapHashForSignature(h, sigType)
460 if err != nil {
461 return nil, nil, err
462 }
463 switch sigType {
464 case packet.SigTypeBinary:
465 return h, wrappedHash, nil
466 case packet.SigTypeText:
467 return h, wrappedHash, nil
468 }
469 return nil, nil, errors.UnsupportedError("unsupported signature type: " + strconv.Itoa(int(sigType)))
470 }
471
472 // checkReader wraps an io.Reader from a LiteralData packet. When it sees EOF
473 // it closes the ReadCloser from any SymmetricallyEncrypted packet to trigger
474 // MDC checks.
475 type checkReader struct {
476 md *MessageDetails
477 packets packet.PacketReader
478 checked bool
479 }
480
481 func (cr *checkReader) Read(buf []byte) (int, error) {
482 n, sensitiveParsingError := cr.md.LiteralData.Body.Read(buf)
483 if sensitiveParsingError == io.EOF {
484 if cr.checked {
485 return n, io.EOF
486 }
487 for {
488 _, err := cr.packets.Next()
489 if err == io.EOF {
490 break
491 }
492 if err != nil {
493 return n, err
494 }
495 }
496 if cr.md.decrypted != nil {
497 if sensitiveParsingError := cr.md.decrypted.Close(); sensitiveParsingError != nil {
498 return n, errors.HandleSensitiveParsingError(sensitiveParsingError, true)
499 }
500 }
501 cr.checked = true
502 return n, io.EOF
503 }
504 if sensitiveParsingError != nil {
505 return n, errors.HandleSensitiveParsingError(sensitiveParsingError, true)
506 }
507 return n, nil
508 }
509
510 // signatureCheckReader wraps an io.Reader from a LiteralData packet and hashes
511 // the data as it is read. When it sees an EOF from the underlying io.Reader
512 // it parses and checks a trailing Signature packet and triggers any MDC checks.
513 type signatureCheckReader struct {
514 packets packet.PacketReader
515 md *MessageDetails
516 config *packet.Config
517 data io.Reader
518 }
519
520 func (scr *signatureCheckReader) Read(buf []byte) (int, error) {
521 n, sensitiveParsingError := scr.data.Read(buf)
522
523 for _, candidate := range scr.md.SignatureCandidates {
524 if candidate.SignatureError == nil && candidate.SignedByEntity != nil {
525 candidate.WrappedHash.Write(buf[:n])
526 }
527 }
528
529 readsDecryptedData := scr.md.decrypted != nil
530 if sensitiveParsingError == io.EOF {
531
532 var signatures []*packet.Signature
533
534 // Read all signature packets and discard others.
535 for {
536 p, sensitiveParsingErrorPacket := scr.packets.Next()
537 if sensitiveParsingErrorPacket == io.EOF {
538 break
539 }
540 if sensitiveParsingErrorPacket != nil {
541 return n, errors.HandleSensitiveParsingError(sensitiveParsingErrorPacket, readsDecryptedData)
542 }
543 if sig, ok := p.(*packet.Signature); ok {
544 if sig.Version == 5 && scr.md.LiteralData != nil && (sig.SigType == 0x00 || sig.SigType == 0x01) {
545 sig.Metadata = scr.md.LiteralData
546 }
547 signatures = append(signatures, sig)
548 }
549 }
550
551 // Verify the integrity of the decrypted data before verifying the signatures.
552 if scr.md.decrypted != nil {
553 sensitiveParsingErrorPacket := scr.md.decrypted.Close()
554 if sensitiveParsingErrorPacket != nil {
555 return n, errors.HandleSensitiveParsingError(sensitiveParsingErrorPacket, true)
556 }
557 }
558
559 numberOfOpsSignatures := 0
560 for _, candidate := range scr.md.SignatureCandidates {
561 if candidate.CorrespondingSig == nil {
562 numberOfOpsSignatures++
563 }
564 }
565
566 if len(signatures) != numberOfOpsSignatures {
567 // Cannot handle this case yet with no information about invalid packets, should fail.
568 // This case can happen if a known OPS version is used but an unknown signature version.
569 noMatchError := errors.StructuralError("number of ops signature candidates does not match the number of signature packets")
570 for _, candidate := range scr.md.SignatureCandidates {
571 candidate.SignatureError = noMatchError
572 }
573 } else {
574 var sigIndex int
575 // Verify all signature candidates.
576 for _, candidate := range scr.md.SignatureCandidates {
577 if candidate.CorrespondingSig == nil {
578 candidate.CorrespondingSig = signatures[sigIndex]
579 sigIndex++
580 }
581 if !candidate.validate() {
582 candidate.SignatureError = errors.StructuralError("signature does not match the expected ops data")
583 }
584 if candidate.SignatureError == nil {
585 sig := candidate.CorrespondingSig
586 if candidate.SignedByEntity == nil {
587 candidate.SignatureError = errors.ErrUnknownIssuer
588 scr.md.SignatureError = candidate.SignatureError
589 } else {
590 // Verify and retrieve signing key at signature creation time
591 key, err := candidate.SignedByEntity.signingKeyByIdUsage(sig.CreationTime, candidate.IssuerKeyId, packet.KeyFlagSign, scr.config)
592 if err != nil {
593 candidate.SignatureError = err
594 continue
595 } else {
596 candidate.SignedBy = &key
597 }
598 signatureError := key.PublicKey.VerifySignature(candidate.Hash, sig)
599 if signatureError == nil {
600 signatureError = checkMessageSignatureDetails(&key, sig, scr.config)
601 }
602 if !scr.md.IsSymmetricallyEncrypted && len(sig.IntendedRecipients) > 0 && scr.md.CheckRecipients && signatureError == nil {
603 if !scr.md.IsEncrypted {
604 signatureError = errors.SignatureError("intended recipients in non-encrypted message")
605 } else {
606 // Check signature matches one of the recipients
607 signatureError = checkIntendedRecipientsMatch(&scr.md.DecryptedWith, sig)
608 }
609 }
610 candidate.SignatureError = signatureError
611 }
612 }
613 }
614 }
615
616 // Check if there is a valid candidate.
617 for _, candidate := range scr.md.SignatureCandidates {
618 if candidate.SignedBy == nil {
619 // Ignore candidates that have no matching key
620 continue
621 }
622 // md.SignatureError points to the last candidate with a key match, if
623 // all signature verifications have failed.
624 scr.md.SignatureError = candidate.SignatureError
625 scr.md.SelectedCandidate = candidate
626 if candidate.SignatureError == nil {
627 // There is a valid signature.
628 scr.md.Signature = candidate.CorrespondingSig
629 scr.md.SignedBy = candidate.SignedBy
630 break
631 }
632 }
633
634 if len(scr.md.SignatureCandidates) == 0 {
635 scr.md.SignatureError = errors.StructuralError("no signature found")
636 }
637
638 if len(scr.md.SignatureCandidates) > 0 && scr.md.SelectedCandidate == nil {
639 // No candidate with a matching key present.
640 // Just point to the last candidate in this case.
641 candidate := scr.md.SignatureCandidates[len(scr.md.SignatureCandidates)-1]
642 scr.md.SignatureError = candidate.SignatureError
643 scr.md.SelectedCandidate = candidate
644 }
645
646 if scr.md.SignatureError == nil && scr.md.Signature == nil {
647 scr.md.SignatureError = errors.StructuralError("no matching signature found")
648 }
649
650 scr.md.IsVerified = true
651 return n, io.EOF
652 }
653
654 if sensitiveParsingError != nil {
655 return n, errors.HandleSensitiveParsingError(sensitiveParsingError, readsDecryptedData)
656 }
657
658 return n, nil
659 }
660
661 // VerifyDetachedSignature takes a signed file and a detached signature and
662 // returns the signature packet and the entity the signature was signed by,
663 // if any, and a possible signature verification error.
664 // If the signer isn't known, ErrUnknownIssuer is returned.
665 func VerifyDetachedSignature(keyring KeyRing, signed, signature io.Reader, config *packet.Config) (sig *packet.Signature, signer *Entity, err error) {
666 return verifyDetachedSignature(keyring, signed, signature, config)
667 }
668
669 // VerifyDetachedSignatureReader takes a signed file and a detached signature and
670 // returns message details struct similar to the ReadMessage function.
671 // Once all data is read from md.UnverifiedBody the detached signature is verified.
672 // If a verification error occurs it is stored in md.SignatureError
673 // If the signer isn't known, ErrUnknownIssuer is returned.
674 func VerifyDetachedSignatureReader(keyring KeyRing, signed, signature io.Reader, config *packet.Config) (md *MessageDetails, err error) {
675 return verifyDetachedSignatureReader(keyring, signed, signature, config)
676 }
677
678 // VerifyArmoredDetachedSignature performs the same actions as
679 // VerifyDetachedSignature but expects the signature to be armored.
680 func VerifyArmoredDetachedSignature(keyring KeyRing, signed, signature io.Reader, config *packet.Config) (sig *packet.Signature, signer *Entity, err error) {
681 body, err := readArmored(signature, SignatureType)
682 if err != nil {
683 return
684 }
685
686 return VerifyDetachedSignature(keyring, signed, body, config)
687 }
688
689 func verifyDetachedSignature(keyring KeyRing, signed, signature io.Reader, config *packet.Config) (sig *packet.Signature, signer *Entity, err error) {
690 md, err := verifyDetachedSignatureReader(keyring, signed, signature, config)
691 if err != nil {
692 return nil, nil, err
693 }
694 _, err = io.Copy(ioutil.Discard, md.UnverifiedBody)
695 if err != nil {
696 return nil, nil, err
697 }
698 if md.SignatureError != nil {
699 return nil, nil, md.SignatureError
700 }
701 return md.Signature, md.SignedBy.Entity, nil
702 }
703
704 func verifyDetachedSignatureReader(keyring KeyRing, signed, signature io.Reader, config *packet.Config) (md *MessageDetails, err error) {
705 var p packet.Packet
706 md = &MessageDetails{
707 IsEncrypted: false,
708 CheckRecipients: false,
709 IsSigned: true,
710 }
711
712 packets := packet.NewReader(signature)
713 for {
714 p, err = packets.Next()
715 if err == io.EOF {
716 break
717 }
718 if err != nil {
719 return nil, err
720 }
721 sig, ok := p.(*packet.Signature)
722 if !ok {
723 continue
724 }
725 candidate, err := newSignatureCandidateFromSignature(sig)
726 if err != nil {
727 return nil, err
728 }
729 md.SignatureCandidates = append(md.SignatureCandidates, candidate)
730
731 keys := keyring.EntitiesById(candidate.IssuerKeyId)
732 if len(keys) > 0 {
733 candidate.SignedByEntity = keys[0]
734 }
735 }
736
737 if len(md.SignatureCandidates) == 0 {
738 return nil, errors.ErrUnknownIssuer
739 }
740 md.UnverifiedBody = &signatureCheckReader{packets, md, config, signed}
741 return md, nil
742 }
743
744 // checkSignatureDetails verifies the metadata of the signature.
745 // It checks the following:
746 // - Hash function should not be invalid according to
747 // config.RejectHashAlgorithms.
748 // - Check signature notations.
749 // - Signature is not expired (unless a zero time is passed to
750 // explicitly ignore expiration).
751 func checkSignatureDetails(signature *packet.Signature, now time.Time, config *packet.Config) error {
752 if config.RejectHashAlgorithm(signature.Hash) {
753 return errors.SignatureError("insecure hash algorithm: " + signature.Hash.String())
754 }
755
756 for _, notation := range signature.Notations {
757 if notation.IsCritical && !config.KnownNotation(notation.Name) {
758 return errors.SignatureError("unknown critical notation: " + notation.Name)
759 }
760 }
761
762 if !now.IsZero() && signature.SigExpired(now) {
763 return errors.ErrSignatureExpired
764 }
765 return nil
766 }
767
768 // checkMessageSignatureDetails verifies the metadata of the signature.
769 // It checks the criteria of checkSignatureDetails for the message
770 // signature and all relevant binding signatures.
771 // In addition, the message signature hash algorithm is checked against
772 // config.RejectMessageHashAlgorithms.
773 // Finally, the signature must be newer than the verification key.
774 func checkMessageSignatureDetails(verifiedKey *Key, signature *packet.Signature, config *packet.Config) error {
775 if config.RejectMessageHashAlgorithm(signature.Hash) {
776 return errors.SignatureError("insecure message hash algorithm: " + signature.Hash.String())
777 }
778
779 if signature.CreationTime.Unix() < verifiedKey.PublicKey.CreationTime.Unix() {
780 return errors.ErrSignatureOlderThanKey
781 }
782
783 sigsToCheck := []*packet.Signature{signature, verifiedKey.PrimarySelfSignature}
784 if !verifiedKey.IsPrimary() {
785 sigsToCheck = append(sigsToCheck, verifiedKey.SelfSignature, verifiedKey.SelfSignature.EmbeddedSignature)
786 }
787 var errs []error
788 for _, sig := range sigsToCheck {
789 var time time.Time
790 if sig == signature {
791 time = config.Now()
792 } else {
793 time = signature.CreationTime
794 }
795 if err := checkSignatureDetails(sig, time, config); err != nil {
796 errs = append(errs, err)
797 }
798 }
799
800 // Return errors.ErrSignatureExpired last as gopenpgp might ignore it.
801 for _, err := range errs {
802 if err != errors.ErrSignatureExpired {
803 return err
804 }
805 }
806 if len(errs) != 0 {
807 return errs[0]
808 }
809 return nil
810 }
811
812 // checkIntendedRecipientsMatch checks if the fingerprint of the primary key matching the decryption key
813 // is found in the signature's intended recipients list.
814 func checkIntendedRecipientsMatch(decryptionKey *Key, sig *packet.Signature) error {
815 match := false
816 for _, recipient := range sig.IntendedRecipients {
817 if bytes.Equal(recipient.Fingerprint, decryptionKey.Entity.PrimaryKey.Fingerprint) {
818 match = true
819 break
820 }
821 }
822 if !match {
823 return errors.SignatureError("intended recipients in the signature does not match the decryption key")
824 }
825 return nil
826 }