Debian Codegraph @

openpgp/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 openpgp // import "github.com/ProtonMail/go-crypto/openpgp"
7
8 import (
9 "crypto"
10 _ "crypto/sha256"
11 _ "crypto/sha512"
12 "hash"
13 "io"
14 "strconv"
15
16 "github.com/ProtonMail/go-crypto/openpgp/armor"
17 "github.com/ProtonMail/go-crypto/openpgp/errors"
18 "github.com/ProtonMail/go-crypto/openpgp/internal/algorithm"
19 "github.com/ProtonMail/go-crypto/openpgp/packet"
20 _ "golang.org/x/crypto/sha3"
21 )
22
23 // SignatureType is the armor type for a PGP signature.
24 var SignatureType = "PGP SIGNATURE"
25
26 // MessageType is the armor type for a PGP message.
27 var MessageType = "PGP MESSAGE"
28
29 // readArmored reads an armored block with the given type.
30 func readArmored(r io.Reader, expectedType string) (body io.Reader, err error) {
31 block, err := armor.Decode(r)
32 if err != nil {
33 return
34 }
35
36 if block.Type != expectedType {
37 return nil, errors.InvalidArgumentError("expected '" + expectedType + "', got: " + block.Type)
38 }
39
40 return block.Body, nil
41 }
42
43 // MessageDetails contains the result of parsing an OpenPGP encrypted and/or
44 // signed message.
45 type MessageDetails struct {
46 IsEncrypted bool // true if the message was encrypted.
47 EncryptedToKeyIds []uint64 // the list of recipient key ids.
48 IsSymmetricallyEncrypted bool // true if a passphrase could have decrypted the message.
49 DecryptedWith Key // the private key used to decrypt the message, if any.
50 IsSigned bool // true if the message is signed.
51 SignedByKeyId uint64 // the key id of the signer, if any.
52 SignedByFingerprint []byte // the key fingerprint of the signer, if any.
53 SignedBy *Key // the key of the signer, if available.
54 LiteralData *packet.LiteralData // the metadata of the contents
55 UnverifiedBody io.Reader // the contents of the message.
56
57 // If IsSigned is true and SignedBy is non-zero then the signature will
58 // be verified as UnverifiedBody is read. The signature cannot be
59 // checked until the whole of UnverifiedBody is read so UnverifiedBody
60 // must be consumed until EOF before the data can be trusted. Even if a
61 // message isn't signed (or the signer is unknown) the data may contain
62 // an authentication code that is only checked once UnverifiedBody has
63 // been consumed. Once EOF has been seen, the following fields are
64 // valid. (An authentication code failure is reported as a
65 // SignatureError error when reading from UnverifiedBody.)
66 Signature *packet.Signature // the signature packet itself.
67 SignatureError error // nil if the signature is good.
68 UnverifiedSignatures []*packet.Signature // all other unverified signature packets.
69
70 decrypted io.ReadCloser
71 }
72
73 // A PromptFunction is used as a callback by functions that may need to decrypt
74 // a private key, or prompt for a passphrase. It is called with a list of
75 // acceptable, encrypted private keys and a boolean that indicates whether a
76 // passphrase is usable. It should either decrypt a private key or return a
77 // passphrase to try. If the decrypted private key or given passphrase isn't
78 // correct, the function will be called again, forever. Any error returned will
79 // be passed up.
80 type PromptFunction func(keys []Key, symmetric bool) ([]byte, error)
81
82 // A keyEnvelopePair is used to store a private key with the envelope that
83 // contains a symmetric key, encrypted with that key.
84 type keyEnvelopePair struct {
85 key Key
86 encryptedKey *packet.EncryptedKey
87 }
88
89 // ReadMessage parses an OpenPGP message that may be signed and/or encrypted.
90 // The given KeyRing should contain both public keys (for signature
91 // verification) and, possibly encrypted, private keys for decrypting.
92 // If config is nil, sensible defaults will be used.
93 func ReadMessage(r io.Reader, keyring KeyRing, prompt PromptFunction, config *packet.Config) (md *MessageDetails, err error) {
94 var p packet.Packet
95
96 var symKeys []*packet.SymmetricKeyEncrypted
97 var pubKeys []keyEnvelopePair
98 // Integrity protected encrypted packet: SymmetricallyEncrypted or AEADEncrypted
99 var edp packet.EncryptedDataPacket
100
101 packets := packet.NewReader(r)
102 md = new(MessageDetails)
103 md.IsEncrypted = true
104
105 // The message, if encrypted, starts with a number of packets
106 // containing an encrypted decryption key. The decryption key is either
107 // encrypted to a public key, or with a passphrase. This loop
108 // collects these packets.
109 ParsePackets:
110 for {
111 p, err = packets.Next()
112 if err != nil {
113 return nil, err
114 }
115 switch p := p.(type) {
116 case *packet.SymmetricKeyEncrypted:
117 // This packet contains the decryption key encrypted with a passphrase.
118 md.IsSymmetricallyEncrypted = true
119 symKeys = append(symKeys, p)
120 case *packet.EncryptedKey:
121 // This packet contains the decryption key encrypted to a public key.
122 md.EncryptedToKeyIds = append(md.EncryptedToKeyIds, p.KeyId)
123 switch p.Algo {
124 case packet.PubKeyAlgoRSA, packet.PubKeyAlgoRSAEncryptOnly, packet.PubKeyAlgoElGamal, packet.PubKeyAlgoECDH,
125 packet.PubKeyAlgoX25519, packet.PubKeyAlgoX448,
126 packet.PubKeyAlgoMlkem768X25519, packet.PubKeyAlgoMlkem1024X448:
127 break
128 default:
129 continue
130 }
131 if keyring != nil {
132 var keys []Key
133 if p.KeyId == 0 {
134 keys = keyring.DecryptionKeys()
135 } else {
136 keys = keyring.KeysById(p.KeyId)
137 }
138 for _, k := range keys {
139 pubKeys = append(pubKeys, keyEnvelopePair{k, p})
140 }
141 }
142 case *packet.SymmetricallyEncrypted:
143 if !p.IntegrityProtected && !config.AllowUnauthenticatedMessages() {
144 return nil, errors.UnsupportedError("message is not integrity protected")
145 }
146 edp = p
147 break ParsePackets
148 case *packet.AEADEncrypted:
149 edp = p
150 break ParsePackets
151 case *packet.Compressed, *packet.LiteralData, *packet.OnePassSignature:
152 // This message isn't encrypted.
153 if len(symKeys) != 0 || len(pubKeys) != 0 {
154 return nil, errors.StructuralError("key material not followed by encrypted message")
155 }
156 packets.Unread(p)
157 return readSignedMessage(packets, nil, keyring, config)
158 }
159 }
160
161 var candidates []Key
162 var decrypted io.ReadCloser
163
164 // Now that we have the list of encrypted keys we need to decrypt at
165 // least one of them or, if we cannot, we need to call the prompt
166 // function so that it can decrypt a key or give us a passphrase.
167 FindKey:
168 for {
169 // See if any of the keys already have a private key available
170 candidates = candidates[:0]
171 candidateFingerprints := make(map[string]bool)
172
173 for _, pk := range pubKeys {
174 if pk.key.PrivateKey == nil {
175 continue
176 }
177 if !pk.key.PrivateKey.Encrypted {
178 if len(pk.encryptedKey.Key) == 0 {
179 errDec := pk.encryptedKey.Decrypt(pk.key.PrivateKey, config)
180 if errDec != nil {
181 continue
182 }
183 }
184 // Try to decrypt symmetrically encrypted
185 decrypted, err = edp.Decrypt(pk.encryptedKey.CipherFunc, pk.encryptedKey.Key)
186 if err != nil && err != errors.ErrKeyIncorrect {
187 return nil, err
188 }
189 if decrypted != nil {
190 md.DecryptedWith = pk.key
191 break FindKey
192 }
193 } else {
194 fpr := string(pk.key.PublicKey.Fingerprint[:])
195 if v := candidateFingerprints[fpr]; v {
196 continue
197 }
198 candidates = append(candidates, pk.key)
199 candidateFingerprints[fpr] = true
200 }
201 }
202
203 if len(candidates) == 0 && len(symKeys) == 0 {
204 return nil, errors.ErrKeyIncorrect
205 }
206
207 if prompt == nil {
208 return nil, errors.ErrKeyIncorrect
209 }
210
211 passphrase, err := prompt(candidates, len(symKeys) != 0)
212 if err != nil {
213 return nil, err
214 }
215
216 // Try the symmetric passphrase first
217 if len(symKeys) != 0 && passphrase != nil {
218 for _, s := range symKeys {
219 key, cipherFunc, err := s.Decrypt(passphrase)
220 // In v4, on wrong passphrase, session key decryption is very likely to result in an invalid cipherFunc:
221 // only for < 5% of cases we will proceed to decrypt the data
222 if err == nil {
223 decrypted, err = edp.Decrypt(cipherFunc, key)
224 if err != nil {
225 return nil, err
226 }
227 if decrypted != nil {
228 break FindKey
229 }
230 }
231 }
232 }
233 }
234
235 md.decrypted = decrypted
236 if err := packets.Push(decrypted); err != nil {
237 return nil, err
238 }
239 mdFinal, sensitiveParsingErr := readSignedMessage(packets, md, keyring, config)
240 if sensitiveParsingErr != nil {
241 return nil, errors.HandleSensitiveParsingError(sensitiveParsingErr, md.decrypted != nil)
242 }
243 return mdFinal, nil
244 }
245
246 // readSignedMessage reads a possibly signed message if mdin is non-zero then
247 // that structure is updated and returned. Otherwise a fresh MessageDetails is
248 // used.
249 func readSignedMessage(packets *packet.Reader, mdin *MessageDetails, keyring KeyRing, config *packet.Config) (md *MessageDetails, err error) {
250 if mdin == nil {
251 mdin = new(MessageDetails)
252 }
253 md = mdin
254
255 var p packet.Packet
256 var h hash.Hash
257 var wrappedHash hash.Hash
258 var prevLast bool
259 FindLiteralData:
260 for {
261 p, err = packets.Next()
262 if err != nil {
263 return nil, err
264 }
265 switch p := p.(type) {
266 case *packet.Compressed:
267 if err := packets.Push(p.LimitedBodyReader(config.DecompressedMessageSizeLimit())); err != nil {
268 return nil, err
269 }
270 case *packet.OnePassSignature:
271 if prevLast {
272 return nil, errors.UnsupportedError("nested signature packets")
273 }
274
275 if p.IsLast {
276 prevLast = true
277 }
278
279 h, wrappedHash, err = hashForSignature(p.Hash, p.SigType, p.Salt)
280 if err != nil {
281 md.SignatureError = err
282 }
283
284 md.IsSigned = true
285 if p.Version == 6 {
286 md.SignedByFingerprint = p.KeyFingerprint
287 }
288 md.SignedByKeyId = p.KeyId
289
290 if keyring != nil {
291 keys := keyring.KeysByIdUsage(p.KeyId, packet.KeyFlagSign)
292 if len(keys) > 0 {
293 md.SignedBy = &keys[0]
294 }
295 }
296 case *packet.LiteralData:
297 md.LiteralData = p
298 break FindLiteralData
299 }
300 }
301
302 if md.IsSigned && md.SignatureError == nil {
303 md.UnverifiedBody = &signatureCheckReader{packets, h, wrappedHash, md, config}
304 } else if md.decrypted != nil {
305 md.UnverifiedBody = &checkReader{md, false}
306 } else {
307 md.UnverifiedBody = md.LiteralData.Body
308 }
309
310 return md, nil
311 }
312
313 func wrapHashForSignature(hashFunc hash.Hash, sigType packet.SignatureType) (hash.Hash, error) {
314 switch sigType {
315 case packet.SigTypeBinary:
316 return hashFunc, nil
317 case packet.SigTypeText:
318 return NewCanonicalTextHash(hashFunc), nil
319 }
320 return nil, errors.UnsupportedError("unsupported signature type: " + strconv.Itoa(int(sigType)))
321 }
322
323 // hashForSignature returns a pair of hashes that can be used to verify a
324 // signature. The signature may specify that the contents of the signed message
325 // should be preprocessed (i.e. to normalize line endings). Thus this function
326 // returns two hashes. The second should be used to hash the message itself and
327 // performs any needed preprocessing.
328 func hashForSignature(hashFunc crypto.Hash, sigType packet.SignatureType, sigSalt []byte) (hash.Hash, hash.Hash, error) {
329 if _, ok := algorithm.HashToHashIdWithSha1(hashFunc); !ok {
330 return nil, nil, errors.UnsupportedError("unsupported hash function")
331 }
332 if !hashFunc.Available() {
333 return nil, nil, errors.UnsupportedError("hash not available: " + strconv.Itoa(int(hashFunc)))
334 }
335 h := hashFunc.New()
336 if sigSalt != nil {
337 h.Write(sigSalt)
338 }
339 wrappedHash, err := wrapHashForSignature(h, sigType)
340 if err != nil {
341 return nil, nil, err
342 }
343 switch sigType {
344 case packet.SigTypeBinary:
345 return h, wrappedHash, nil
346 case packet.SigTypeText:
347 return h, wrappedHash, nil
348 }
349 return nil, nil, errors.UnsupportedError("unsupported signature type: " + strconv.Itoa(int(sigType)))
350 }
351
352 // checkReader wraps an io.Reader from a LiteralData packet. When it sees EOF
353 // it closes the ReadCloser from any SymmetricallyEncrypted packet to trigger
354 // MDC checks.
355 type checkReader struct {
356 md *MessageDetails
357 checked bool
358 }
359
360 func (cr *checkReader) Read(buf []byte) (int, error) {
361 n, sensitiveParsingError := cr.md.LiteralData.Body.Read(buf)
362 if sensitiveParsingError == io.EOF {
363 if cr.checked {
364 // Only check once
365 return n, io.EOF
366 }
367 mdcErr := cr.md.decrypted.Close()
368 if mdcErr != nil {
369 return n, mdcErr
370 }
371 cr.checked = true
372 return n, io.EOF
373 }
374
375 if sensitiveParsingError != nil {
376 return n, errors.HandleSensitiveParsingError(sensitiveParsingError, true)
377 }
378
379 return n, nil
380 }
381
382 // signatureCheckReader wraps an io.Reader from a LiteralData packet and hashes
383 // the data as it is read. When it sees an EOF from the underlying io.Reader
384 // it parses and checks a trailing Signature packet and triggers any MDC checks.
385 type signatureCheckReader struct {
386 packets *packet.Reader
387 h, wrappedHash hash.Hash
388 md *MessageDetails
389 config *packet.Config
390 }
391
392 func (scr *signatureCheckReader) Read(buf []byte) (int, error) {
393 n, sensitiveParsingError := scr.md.LiteralData.Body.Read(buf)
394
395 // Hash only if required
396 if scr.md.SignedBy != nil {
397 scr.wrappedHash.Write(buf[:n])
398 }
399
400 readsDecryptedData := scr.md.decrypted != nil
401 if sensitiveParsingError == io.EOF {
402 var p packet.Packet
403 var readError error
404 var sig *packet.Signature
405
406 p, readError = scr.packets.Next()
407 for readError == nil {
408 var ok bool
409 if sig, ok = p.(*packet.Signature); ok {
410 if sig.Version == 5 && (sig.SigType == 0x00 || sig.SigType == 0x01) {
411 sig.Metadata = scr.md.LiteralData
412 }
413
414 // If signature KeyID matches
415 if scr.md.SignedBy != nil && sig.IssuerKeyId != nil && *sig.IssuerKeyId == scr.md.SignedByKeyId {
416 key := scr.md.SignedBy
417 signatureError := key.PublicKey.VerifySignature(scr.h, sig)
418 if signatureError == nil {
419 signatureError = checkMessageSignatureDetails(key, sig, scr.config)
420 }
421 scr.md.Signature = sig
422 scr.md.SignatureError = signatureError
423 } else {
424 scr.md.UnverifiedSignatures = append(scr.md.UnverifiedSignatures, sig)
425 }
426 }
427
428 p, readError = scr.packets.Next()
429 }
430
431 if scr.md.SignedBy != nil && scr.md.Signature == nil {
432 if scr.md.UnverifiedSignatures == nil {
433 scr.md.SignatureError = errors.StructuralError("LiteralData not followed by signature")
434 } else {
435 scr.md.SignatureError = errors.StructuralError("No matching signature found")
436 }
437 }
438
439 // The SymmetricallyEncrypted packet, if any, might have an
440 // unsigned hash of its own. In order to check this we need to
441 // close that Reader.
442 if scr.md.decrypted != nil {
443 if sensitiveParsingError := scr.md.decrypted.Close(); sensitiveParsingError != nil {
444 return n, errors.HandleSensitiveParsingError(sensitiveParsingError, true)
445 }
446 }
447 return n, io.EOF
448 }
449
450 if sensitiveParsingError != nil {
451 return n, errors.HandleSensitiveParsingError(sensitiveParsingError, readsDecryptedData)
452 }
453
454 return n, nil
455 }
456
457 // VerifyDetachedSignature takes a signed file and a detached signature and
458 // returns the signature packet and the entity the signature was signed by,
459 // if any, and a possible signature verification error.
460 // If the signer isn't known, ErrUnknownIssuer is returned.
461 func VerifyDetachedSignature(keyring KeyRing, signed, signature io.Reader, config *packet.Config) (sig *packet.Signature, signer *Entity, err error) {
462 return verifyDetachedSignature(keyring, signed, signature, nil, false, config)
463 }
464
465 // VerifyDetachedSignatureAndHash performs the same actions as
466 // VerifyDetachedSignature and checks that the expected hash functions were used.
467 func VerifyDetachedSignatureAndHash(keyring KeyRing, signed, signature io.Reader, expectedHashes []crypto.Hash, config *packet.Config) (sig *packet.Signature, signer *Entity, err error) {
468 return verifyDetachedSignature(keyring, signed, signature, expectedHashes, true, config)
469 }
470
471 // CheckDetachedSignature takes a signed file and a detached signature and
472 // returns the entity the signature was signed by, if any, and a possible
473 // signature verification error. If the signer isn't known,
474 // ErrUnknownIssuer is returned.
475 func CheckDetachedSignature(keyring KeyRing, signed, signature io.Reader, config *packet.Config) (signer *Entity, err error) {
476 _, signer, err = verifyDetachedSignature(keyring, signed, signature, nil, false, config)
477 return
478 }
479
480 // CheckDetachedSignatureAndHash performs the same actions as
481 // CheckDetachedSignature and checks that the expected hash functions were used.
482 func CheckDetachedSignatureAndHash(keyring KeyRing, signed, signature io.Reader, expectedHashes []crypto.Hash, config *packet.Config) (signer *Entity, err error) {
483 _, signer, err = verifyDetachedSignature(keyring, signed, signature, expectedHashes, true, config)
484 return
485 }
486
487 func verifyDetachedSignature(keyring KeyRing, signed, signature io.Reader, expectedHashes []crypto.Hash, checkHashes bool, config *packet.Config) (sig *packet.Signature, signer *Entity, err error) {
488 var issuerKeyId uint64
489 var hashFunc crypto.Hash
490 var sigType packet.SignatureType
491 var keys []Key
492 var p packet.Packet
493
494 packets := packet.NewReader(signature)
495 for {
496 p, err = packets.Next()
497 if err == io.EOF {
498 return nil, nil, errors.ErrUnknownIssuer
499 }
500 if err != nil {
501 return nil, nil, err
502 }
503
504 var ok bool
505 sig, ok = p.(*packet.Signature)
506 if !ok {
507 return nil, nil, errors.StructuralError("non signature packet found")
508 }
509 if sig.IssuerKeyId == nil {
510 return nil, nil, errors.StructuralError("signature doesn't have an issuer")
511 }
512 issuerKeyId = *sig.IssuerKeyId
513 hashFunc = sig.Hash
514 sigType = sig.SigType
515 if checkHashes {
516 matchFound := false
517 // check for hashes
518 for _, expectedHash := range expectedHashes {
519 if hashFunc == expectedHash {
520 matchFound = true
521 break
522 }
523 }
524 if !matchFound {
525 return nil, nil, errors.StructuralError("hash algorithm or salt mismatch with cleartext message headers")
526 }
527 }
528 keys = keyring.KeysByIdUsage(issuerKeyId, packet.KeyFlagSign)
529 if len(keys) > 0 {
530 break
531 }
532 }
533
534 if len(keys) == 0 {
535 panic("unreachable")
536 }
537
538 h, err := sig.PrepareVerify()
539 if err != nil {
540 return nil, nil, err
541 }
542 wrappedHash, err := wrapHashForSignature(h, sigType)
543 if err != nil {
544 return nil, nil, err
545 }
546
547 if _, err := io.Copy(wrappedHash, signed); err != nil && err != io.EOF {
548 return nil, nil, err
549 }
550
551 for _, key := range keys {
552 err = key.PublicKey.VerifySignature(h, sig)
553 if err == nil {
554 return sig, key.Entity, checkMessageSignatureDetails(&key, sig, config)
555 }
556 }
557
558 return nil, nil, err
559 }
560
561 // CheckArmoredDetachedSignature performs the same actions as
562 // CheckDetachedSignature but expects the signature to be armored.
563 func CheckArmoredDetachedSignature(keyring KeyRing, signed, signature io.Reader, config *packet.Config) (signer *Entity, err error) {
564 body, err := readArmored(signature, SignatureType)
565 if err != nil {
566 return
567 }
568
569 return CheckDetachedSignature(keyring, signed, body, config)
570 }
571
572 // checkMessageSignatureDetails returns an error if:
573 // - The signature (or one of the binding signatures mentioned below)
574 // has a unknown critical notation data subpacket
575 // - The primary key of the signing entity is revoked
576 // - The primary identity is revoked
577 // - The signature is expired
578 // - The primary key of the signing entity is expired according to the
579 // primary identity binding signature
580 //
581 // ... or, if the signature was signed by a subkey and:
582 // - The signing subkey is revoked
583 // - The signing subkey is expired according to the subkey binding signature
584 // - The signing subkey binding signature is expired
585 // - The signing subkey cross-signature is expired
586 //
587 // NOTE: The order of these checks is important, as the caller may choose to
588 // ignore ErrSignatureExpired or ErrKeyExpired errors, but should never
589 // ignore any other errors.
590 func checkMessageSignatureDetails(key *Key, signature *packet.Signature, config *packet.Config) error {
591 now := config.Now()
592 primarySelfSignature, primaryIdentity := key.Entity.PrimarySelfSignature()
593 signedBySubKey := key.PublicKey != key.Entity.PrimaryKey
594 sigsToCheck := []*packet.Signature{signature, primarySelfSignature}
595 if signedBySubKey {
596 sigsToCheck = append(sigsToCheck, key.SelfSignature, key.SelfSignature.EmbeddedSignature)
597 }
598 for _, sig := range sigsToCheck {
599 for _, notation := range sig.Notations {
600 if notation.IsCritical && !config.KnownNotation(notation.Name) {
601 return errors.SignatureError("unknown critical notation: " + notation.Name)
602 }
603 }
604 }
605 if key.Entity.Revoked(now) || // primary key is revoked
606 (signedBySubKey && key.Revoked(now)) || // subkey is revoked
607 (primaryIdentity != nil && primaryIdentity.Revoked(now)) { // primary identity is revoked for v4
608 return errors.ErrKeyRevoked
609 }
610 if key.Entity.PrimaryKey.KeyExpired(primarySelfSignature, now) { // primary key is expired
611 return errors.ErrKeyExpired
612 }
613 if signedBySubKey {
614 if key.PublicKey.KeyExpired(key.SelfSignature, now) { // subkey is expired
615 return errors.ErrKeyExpired
616 }
617 }
618 for _, sig := range sigsToCheck {
619 if sig.SigExpired(now) { // any of the relevant signatures are expired
620 return errors.ErrSignatureExpired
621 }
622 }
623 return nil
624 }