Debian Codegraph @

openpgp/v2/write.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 v2
6
7 import (
8 "bytes"
9 "crypto"
10 goerrors "errors"
11 "hash"
12 "io"
13 "strconv"
14 "time"
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 )
21
22 // DetachSign signs message with the private key from signer (which must
23 // already have been decrypted) and writes the signature to w.
24 // If config is nil, sensible defaults will be used.
25 func DetachSign(w io.Writer, signers []*Entity, message io.Reader, config *packet.Config) error {
26 return detachSign(w, signers, message, packet.SigTypeBinary, config)
27 }
28
29 // DetachSignWithParams signs message with the private key from signer (which must
30 // already have been decrypted) and writes the signature to the Writer.
31 // If config is nil, sensible defaults will be used.
32 func DetachSignWithParams(w io.Writer, signers []*Entity, message io.Reader, params *SignParams) error {
33 if params == nil {
34 params = &SignParams{}
35 }
36 sigType := packet.SigTypeBinary
37 if params.TextSig {
38 sigType = packet.SigTypeText
39 }
40 return detachSign(w, signers, message, sigType, params.Config)
41 }
42
43 // ArmoredDetachSign signs message with the private key from signer (which
44 // must already have been decrypted) and writes an armored signature to the Writer.
45 // If config is nil, sensible defaults will be used.
46 func ArmoredDetachSign(w io.Writer, signers []*Entity, message io.Reader, params *SignParams) (err error) {
47 if params == nil {
48 params = &SignParams{}
49 }
50 sigType := packet.SigTypeBinary
51 if params.TextSig {
52 sigType = packet.SigTypeText
53 }
54 return armoredDetachSign(w, signers, message, sigType, params.Config)
55 }
56
57 // DetachSignWriter signs a message with the private key from a signer (which must
58 // already have been decrypted) and writes the signature to the Writer.
59 // DetachSignWriter returns a WriteCloser to which the message can be written to.
60 // The resulting WriteCloser must be closed after the contents of the message have
61 // been written. If utf8Message is set to true, the line endings of the message are
62 // canonicalised and the type of the signature will be SigTypeText.
63 // If config is nil, sensible defaults will be used.
64 func DetachSignWriter(w io.Writer, signers []*Entity, params *SignParams) (io.WriteCloser, error) {
65 if params == nil {
66 params = &SignParams{}
67 }
68 sigType := packet.SigTypeBinary
69 if params.TextSig {
70 sigType = packet.SigTypeText
71 }
72 return detachSignWithWriter(w, signers, sigType, params.Config)
73 }
74
75 func armoredDetachSign(w io.Writer, signers []*Entity, message io.Reader, sigType packet.SignatureType, config *packet.Config) (err error) {
76 out, err := armor.EncodeWithChecksumOption(w, SignatureType, nil, false)
77 if err != nil {
78 return
79 }
80 err = detachSign(out, signers, message, sigType, config)
81 if err != nil {
82 return
83 }
84 return out.Close()
85 }
86
87 func detachSign(w io.Writer, signers []*Entity, message io.Reader, sigType packet.SignatureType, config *packet.Config) (err error) {
88 ptWriter, err := detachSignWithWriter(w, signers, sigType, config)
89 if err != nil {
90 return
91 }
92 _, err = io.Copy(ptWriter, message)
93 if err != nil {
94 return
95 }
96 return ptWriter.Close()
97 }
98
99 type detachSignWriter struct {
100 signatureWriter io.Writer
101 signatures []*detachSignContext
102 config *packet.Config
103 }
104
105 type detachSignContext struct {
106 wrappedHash hash.Hash
107 h hash.Hash
108 signer *packet.PrivateKey
109 sig *packet.Signature
110 }
111
112 func (s detachSignWriter) Write(data []byte) (int, error) {
113 for _, signature := range s.signatures {
114 if n, err := signature.wrappedHash.Write(data); err != nil {
115 return n, err
116 }
117 }
118 return len(data), nil
119 }
120
121 func (s detachSignWriter) Close() error {
122 for _, signature := range s.signatures {
123 err := signature.sig.Sign(signature.h, signature.signer, s.config)
124 if err != nil {
125 return err
126 }
127 err = signature.sig.Serialize(s.signatureWriter)
128 if err != nil {
129 return err
130 }
131 }
132 return nil
133 }
134
135 func detachSignWithWriter(w io.Writer, signers []*Entity, sigType packet.SignatureType, config *packet.Config) (ptWriter io.WriteCloser, err error) {
136 var detachSignContexts []*detachSignContext
137 for _, signer := range signers {
138 signingKey, ok := signer.SigningKeyById(config.Now(), config.SigningKey(), config)
139 if !ok {
140 return nil, errors.InvalidArgumentError("no valid signing keys")
141 }
142 if signingKey.PrivateKey == nil {
143 return nil, errors.InvalidArgumentError("signing key doesn't have a private key")
144 }
145 if signingKey.PrivateKey.Encrypted {
146 return nil, errors.InvalidArgumentError("signing key is encrypted")
147 }
148 candidateHashes := []uint8{
149 hashToHashId(crypto.SHA256),
150 hashToHashId(crypto.SHA384),
151 hashToHashId(crypto.SHA512),
152 hashToHashId(crypto.SHA3_256),
153 hashToHashId(crypto.SHA3_512),
154 }
155 defaultHashes := candidateHashes[0:1]
156 primarySelfSignature, _ := signer.PrimarySelfSignature(config.Now(), config)
157 if primarySelfSignature == nil {
158 return nil, errors.StructuralError("signed entity has no valid self-signature")
159 }
160 preferredHashes := primarySelfSignature.PreferredHash
161 if len(preferredHashes) == 0 {
162 preferredHashes = defaultHashes
163 }
164 candidateHashes = intersectPreferences(candidateHashes, preferredHashes)
165
166 var hash crypto.Hash
167 if hash, err = selectHash(candidateHashes, config.Hash(), signingKey.PrivateKey); err != nil {
168 return
169 }
170
171 detachSignCtx := detachSignContext{
172 signer: signingKey.PrivateKey,
173 }
174
175 detachSignCtx.sig = createSignaturePacket(signingKey.PublicKey, sigType, config)
176 detachSignCtx.sig.Hash = hash
177
178 detachSignCtx.h, err = detachSignCtx.sig.PrepareSign(config)
179 if err != nil {
180 return
181 }
182 detachSignCtx.wrappedHash, err = wrapHashForSignature(detachSignCtx.h, sigType)
183 if err != nil {
184 return
185 }
186 detachSignContexts = append(detachSignContexts, &detachSignCtx)
187 }
188
189 return &detachSignWriter{
190 signatureWriter: w,
191 signatures: detachSignContexts,
192 config: config,
193 }, nil
194 }
195
196 // FileHints contains metadata about encrypted files. This metadata is, itself,
197 // encrypted. OpenPGP signatures do not include the FileHints in a signature hash and
198 // thus those fields are not protected against tampering in a signed document.
199 // The crypto[refresh does not recommend to set the data in file hints.
200 // See https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-12.html#section-5.9.
201 type FileHints struct {
202 // IsUTF8 can be set to hint that the contents are utf8 encoded data.
203 IsUTF8 bool
204 // FileName hints at the name of the file that should be written.
205 FileName string
206 // ModTime contains the modification time of the file, or the zero time if not applicable.
207 ModTime time.Time
208 }
209
210 type EncryptParams struct {
211 // KeyWriter is a Writer to which the encrypted
212 // session keys are written to.
213 // If nil, DataWriter is used instead.
214 KeyWriter io.Writer
215 // Hints contains file metadata for the literal data packet.
216 // If nil, default is used.
217 Hints *FileHints
218 // SiningEntities contains the private keys to produce signatures with
219 // If nil, no signatures are created.
220 Signers []*Entity
221 // TextSig indicates if signatures of type SigTypeText should be produced.
222 TextSig bool
223 // Passwords defines additional passwords that the message should be encrypted to.
224 // i.e., for each defined password an additional SKESK packet is written.
225 Passwords [][]byte
226 // SessionKey provides a session key to be used for encryption.
227 // If nil, a random one-time session key is generated.
228 SessionKey []byte
229 // OutsideSig allows to set a signature that should be included
230 // in the message to encrypt.
231 // Should only be used for exceptional cases.
232 // If nil, ignored.
233 OutsideSig []byte
234 // EncryptionTime allows to override the time that is used
235 // for selecting the encryption key.
236 // If EncryptionTime is zero (i.e., EncryptionTime.isZero()) expiration checks
237 // are not performed on the encryption key.
238 // If nil, the default clock in config is used.
239 EncryptionTime *time.Time
240 // Config provides the config to be used.
241 // If Config is nil, sensible defaults will be used.
242 Config *packet.Config
243 }
244
245 // SymmetricallyEncrypt acts like gpg -c: it encrypts a file with a passphrase.
246 // The resulting WriteCloser must be closed after the contents of the file have
247 // been written.
248 // If config is nil, sensible defaults will be used.
249 func SymmetricallyEncrypt(ciphertext io.Writer, passphrase []byte, hints *FileHints, config *packet.Config) (plaintext io.WriteCloser, err error) {
250 return SymmetricallyEncryptWithParams(passphrase, ciphertext, &EncryptParams{
251 Hints: hints,
252 Config: config,
253 })
254 }
255
256 // SymmetricallyEncryptWithParams acts like SymmetricallyEncrypt but provides more configuration options.
257 // EncryptParams provides the optional parameters.
258 // The resulting WriteCloser must be closed after the contents of the file have been written.
259 func SymmetricallyEncryptWithParams(passphrase []byte, dataWriter io.Writer, params *EncryptParams) (plaintext io.WriteCloser, err error) {
260 if params == nil {
261 params = &EncryptParams{}
262 }
263 return symmetricallyEncrypt(passphrase, dataWriter, params)
264 }
265
266 func symmetricallyEncrypt(passphrase []byte, dataWriter io.Writer, params *EncryptParams) (plaintext io.WriteCloser, err error) {
267 if params.KeyWriter == nil {
268 params.KeyWriter = dataWriter
269 }
270 if params.Hints == nil {
271 params.Hints = &FileHints{}
272 }
273 if params.SessionKey == nil {
274 params.SessionKey, err = packet.SerializeSymmetricKeyEncrypted(params.KeyWriter, passphrase, params.Config)
275 defer func() {
276 // zero the session key after we are done
277 for i := range params.SessionKey {
278 params.SessionKey[i] = 0
279 }
280 params.SessionKey = nil
281 }()
282 } else {
283 err = packet.SerializeSymmetricKeyEncryptedReuseKey(params.KeyWriter, params.SessionKey, passphrase, params.Config)
284 }
285 if err != nil {
286 return
287 }
288 for _, additionalPassword := range params.Passwords {
289 if err = packet.SerializeSymmetricKeyEncryptedReuseKey(params.KeyWriter, params.SessionKey, additionalPassword, params.Config); err != nil {
290 return
291 }
292 }
293
294 config := params.Config
295 candidateCompression := []uint8{uint8(config.Compression())}
296 cipherSuite := packet.CipherSuite{
297 Cipher: config.Cipher(),
298 Mode: config.AEAD().Mode(),
299 }
300 var candidateHashesPerSignature [][]uint8
301 if params.Signers != nil {
302 for _, signer := range params.Signers {
303 // candidateHashes := []uint8{hashToHashId(config.Hash())}
304 // Check what the preferred hashes are for the signing key
305 candidateHashes := []uint8{
306 hashToHashId(crypto.SHA256),
307 hashToHashId(crypto.SHA384),
308 hashToHashId(crypto.SHA512),
309 hashToHashId(crypto.SHA3_256),
310 hashToHashId(crypto.SHA3_512),
311 }
312 defaultHashes := candidateHashes[0:1]
313 primarySelfSignature, _ := signer.PrimarySelfSignature(params.Config.Now(), params.Config)
314 if primarySelfSignature == nil {
315 return nil, errors.StructuralError("signed entity has no self-signature")
316 }
317 preferredHashes := primarySelfSignature.PreferredHash
318 if len(preferredHashes) == 0 {
319 preferredHashes = defaultHashes
320 }
321 candidateHashes = intersectPreferences(candidateHashes, preferredHashes)
322 if len(candidateHashes) == 0 {
323 candidateHashes = []uint8{hashToHashId(crypto.SHA256)}
324 }
325 candidateHashesPerSignature = append(candidateHashesPerSignature, candidateHashes)
326 }
327 }
328 return encryptDataAndSign(dataWriter, params, candidateHashesPerSignature, candidateCompression, config.Cipher(), config.AEAD() != nil, cipherSuite, nil)
329 }
330
331 // intersectPreferences mutates and returns a prefix of a that contains only
332 // the values in the intersection of a and b. The order of a is preserved.
333 func intersectPreferences(a []uint8, b []uint8) (intersection []uint8) {
334 var j int
335 for _, v := range a {
336 for _, v2 := range b {
337 if v == v2 {
338 a[j] = v
339 j++
340 break
341 }
342 }
343 }
344
345 return a[:j]
346 }
347
348 // intersectCipherSuites mutates and returns a prefix of a that contains only
349 // the values in the intersection of a and b. The order of a is preserved.
350 func intersectCipherSuites(a [][2]uint8, b [][2]uint8) (intersection [][2]uint8) {
351 var j int
352 for _, v := range a {
353 for _, v2 := range b {
354 if v[0] == v2[0] && v[1] == v2[1] {
355 a[j] = v
356 j++
357 break
358 }
359 }
360 }
361
362 return a[:j]
363 }
364
365 func hashToHashId(h crypto.Hash) uint8 {
366 v, ok := algorithm.HashToHashId(h)
367 if !ok {
368 panic("tried to convert unknown hash")
369 }
370 return v
371 }
372
373 // EncryptWithParams encrypts a message to a number of recipients and, optionally,
374 // signs it. The resulting WriteCloser must be closed after the contents of the file have been written.
375 // The to argument contains recipients that are explicitly mentioned in signatures and encrypted keys,
376 // whereas the toHidden argument contains recipients that will be hidden and not mentioned.
377 // Params contains all optional parameters.
378 func EncryptWithParams(ciphertext io.Writer, to, toHidden []*Entity, params *EncryptParams) (plaintext io.WriteCloser, err error) {
379 if params == nil {
380 params = &EncryptParams{}
381 }
382 if params.KeyWriter == nil {
383 params.KeyWriter = ciphertext
384 }
385 return encrypt(to, toHidden, ciphertext, params)
386 }
387
388 // Encrypt encrypts a message to a number of recipients and, optionally, signs
389 // it. Hints contains optional information, that is also encrypted, that aids
390 // the recipients in processing the message. The crypto-refresh recommends
391 // to not set file hints since the data is not included in the signature hash.
392 // See https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-12.html#section-5.9.
393 // The resulting WriteCloser must be closed after the contents of the file have been written.
394 // The to argument contains recipients that are explicitly mentioned in signatures and encrypted keys,
395 // whereas the toHidden argument contains recipients that will be hidden and not mentioned.
396 // If config is nil, sensible defaults will be used.
397 func Encrypt(ciphertext io.Writer, to, toHidden []*Entity, signers []*Entity, hints *FileHints, config *packet.Config) (plaintext io.WriteCloser, err error) {
398 return EncryptWithParams(ciphertext, to, toHidden, &EncryptParams{
399 Signers: signers,
400 Hints: hints,
401 Config: config,
402 })
403 }
404
405 // writeAndSign writes the data as a payload package and, optionally, signs
406 // it. Hints contains optional information, that is also encrypted,
407 // that aids the recipients in processing the message. The resulting
408 // WriteCloser must be closed after the contents of the file have been
409 // written. If config is nil, sensible defaults will be used.
410 func writeAndSign(payload io.WriteCloser, candidateHashes [][]uint8, signEntities []*Entity, hints *FileHints, sigType packet.SignatureType, intendedRecipients []*packet.Recipient, outsideSig []byte, config *packet.Config) (plaintext io.WriteCloser, err error) {
411 var signers []*signatureContext
412 var numberOfOutsideSigs int
413
414 if outsideSig != nil {
415 outSigPacket, err := parseOutsideSig(outsideSig)
416 if err != nil {
417 return nil, err
418 }
419 opsVersion := 3
420 if outSigPacket.Version == 6 {
421 opsVersion = 6
422 }
423 opsOutside := &packet.OnePassSignature{
424 Version: opsVersion,
425 SigType: outSigPacket.SigType,
426 Hash: outSigPacket.Hash,
427 PubKeyAlgo: outSigPacket.PubKeyAlgo,
428 KeyId: *outSigPacket.IssuerKeyId,
429 IsLast: len(signEntities) == 0,
430 }
431 sigContext := signatureContext{
432 outsideSig: outSigPacket,
433 }
434 if outSigPacket.Version == 6 {
435 opsOutside.KeyFingerprint = outSigPacket.IssuerFingerprint
436 sigContext.salt = outSigPacket.Salt()
437 opsOutside.Salt = outSigPacket.Salt()
438 }
439 sigContext.h, sigContext.wrappedHash, err = hashForSignature(outSigPacket.Hash, sigType, sigContext.salt)
440 if err != nil {
441 return nil, err
442 }
443 if err := opsOutside.Serialize(payload); err != nil {
444 return nil, err
445 }
446 signers = append([]*signatureContext{&sigContext}, signers...)
447 numberOfOutsideSigs = 1
448 }
449
450 for signEntityIdx, signEntity := range signEntities {
451 if signEntity == nil {
452 continue
453 }
454 signKey, ok := signEntity.SigningKeyById(config.Now(), config.SigningKey(), config)
455 if !ok {
456 return nil, errors.InvalidArgumentError("no valid signing keys")
457 }
458 signer := signKey.PrivateKey
459 if signer == nil {
460 return nil, errors.InvalidArgumentError("no private key in signing key")
461 }
462 if signer.Encrypted {
463 return nil, errors.InvalidArgumentError("signing key must be decrypted")
464 }
465 sigContext := signatureContext{
466 signer: signer,
467 }
468
469 if signKey.PrimarySelfSignature == nil {
470 return nil, errors.InvalidArgumentError("signing key has no self-signature")
471 }
472 candidateHashes[signEntityIdx] = intersectPreferences(candidateHashes[signEntityIdx], signKey.PrimarySelfSignature.PreferredHash)
473 hash, err := selectHash(candidateHashes[signEntityIdx], config.Hash(), signKey.PrivateKey)
474 if err != nil {
475 return nil, err
476 }
477 sigContext.hashType = hash
478
479 var opsVersion = 3
480 if signer.Version == 6 {
481 opsVersion = signer.Version
482 }
483 isLast := signEntityIdx == len(signEntities)-1
484 ops := &packet.OnePassSignature{
485 Version: opsVersion,
486 SigType: sigType,
487 Hash: hash,
488 PubKeyAlgo: signer.PubKeyAlgo,
489 KeyId: signer.KeyId,
490 IsLast: isLast,
491 }
492 if opsVersion == 6 {
493 ops.KeyFingerprint = signer.Fingerprint
494 sigContext.salt, err = packet.SignatureSaltForHash(hash, config.Random())
495 if err != nil {
496 return nil, err
497 }
498 ops.Salt = sigContext.salt
499 }
500 if err := ops.Serialize(payload); err != nil {
501 return nil, err
502 }
503
504 sigContext.h, sigContext.wrappedHash, err = hashForSignature(hash, sigType, sigContext.salt)
505 if err != nil {
506 return nil, err
507 }
508 // Prepend since the last signature has to be written first
509 signers = append([]*signatureContext{&sigContext}, signers...)
510 }
511
512 if signEntities != nil && len(signEntities)+numberOfOutsideSigs != len(signers) {
513 return nil, errors.InvalidArgumentError("no valid signing key")
514 }
515
516 if hints == nil {
517 hints = &FileHints{}
518 }
519
520 w := payload
521 if signers != nil || numberOfOutsideSigs > 0 {
522 // If we need to write a signature packet after the literal
523 // data then we need to stop literalData from closing
524 // encryptedData.
525 w = noOpCloser{w}
526
527 }
528 var epochSeconds uint32
529 if !hints.ModTime.IsZero() {
530 epochSeconds = uint32(hints.ModTime.Unix())
531 }
532 literalData, err := packet.SerializeLiteral(w, !hints.IsUTF8, hints.FileName, epochSeconds)
533 if err != nil {
534 return nil, err
535 }
536
537 if signers != nil || numberOfOutsideSigs > 0 {
538 metadata := &packet.LiteralData{
539 Format: 'b',
540 FileName: hints.FileName,
541 Time: epochSeconds,
542 }
543 if hints.IsUTF8 {
544 metadata.Format = 'u'
545 }
546 return signatureWriter{payload, literalData, signers, sigType, config, metadata, intendedRecipients, 0}, nil
547 }
548 return literalData, nil
549 }
550
551 // encrypt encrypts a message to a number of recipients and, optionally, signs
552 // it. The resulting WriteCloser must
553 // be closed after the contents of the file have been written.
554 func encrypt(
555 to, toHidden []*Entity,
556 dataWriter io.Writer,
557 params *EncryptParams,
558 ) (plaintext io.WriteCloser, err error) {
559 if len(to)+len(toHidden) == 0 {
560 return nil, errors.InvalidArgumentError("no encryption recipient provided")
561 }
562
563 // These are the possible ciphers that we'll use for the message.
564 candidateCiphers := []uint8{
565 uint8(packet.CipherAES256),
566 uint8(packet.CipherAES128),
567 }
568
569 // These are the possible hash functions that we'll use for the signature.
570 candidateHashes := []uint8{
571 hashToHashId(crypto.SHA256),
572 hashToHashId(crypto.SHA384),
573 hashToHashId(crypto.SHA512),
574 hashToHashId(crypto.SHA3_256),
575 hashToHashId(crypto.SHA3_512),
576 }
577
578 // Prefer GCM if everyone supports it
579 candidateCipherSuites := [][2]uint8{
580 {uint8(packet.CipherAES256), uint8(packet.AEADModeGCM)},
581 {uint8(packet.CipherAES256), uint8(packet.AEADModeEAX)},
582 {uint8(packet.CipherAES256), uint8(packet.AEADModeOCB)},
583 {uint8(packet.CipherAES128), uint8(packet.AEADModeGCM)},
584 {uint8(packet.CipherAES128), uint8(packet.AEADModeEAX)},
585 {uint8(packet.CipherAES128), uint8(packet.AEADModeOCB)},
586 }
587
588 candidateCompression := []uint8{
589 uint8(packet.CompressionNone),
590 uint8(packet.CompressionZIP),
591 uint8(packet.CompressionZLIB),
592 }
593
594 encryptKeys := make([]Key, len(to)+len(toHidden))
595
596 config := params.Config
597 // AEAD is used if every key supports it
598 aeadSupported := true
599
600 var intendedRecipients []*packet.Recipient
601 // Intended Recipient Fingerprint subpacket SHOULD be used when creating a signed and encrypted message
602 for _, publicRecipient := range to {
603 if config.IntendedRecipients() {
604 intendedRecipients = append(intendedRecipients, &packet.Recipient{KeyVersion: publicRecipient.PrimaryKey.Version, Fingerprint: publicRecipient.PrimaryKey.Fingerprint})
605 }
606 }
607
608 timeForEncryptionKey := config.Now()
609 if params.EncryptionTime != nil {
610 // Override the time to select the encryption key with the provided one.
611 timeForEncryptionKey = *params.EncryptionTime
612 }
613
614 allPQ := len(encryptKeys) > 0
615 for i, recipient := range append(to, toHidden...) {
616 if encryptKeys[i], err = recipient.EncryptionKeyWithError(timeForEncryptionKey, config); err != nil {
617 return nil, err
618 }
619
620 if !encryptKeys[i].PublicKey.IsPQ() {
621 allPQ = false
622 }
623
624 primarySelfSignature, _ := recipient.PrimarySelfSignature(timeForEncryptionKey, config)
625 if primarySelfSignature == nil {
626 return nil, errors.StructuralError("entity without a self-signature")
627 }
628
629 if !primarySelfSignature.SEIPDv2 {
630 aeadSupported = false
631 }
632
633 candidateCiphers = intersectPreferences(candidateCiphers, primarySelfSignature.PreferredSymmetric)
634 candidateHashes = intersectPreferences(candidateHashes, primarySelfSignature.PreferredHash)
635 candidateCipherSuites = intersectCipherSuites(candidateCipherSuites, primarySelfSignature.PreferredCipherSuites)
636 candidateCompression = intersectPreferences(candidateCompression, primarySelfSignature.PreferredCompression)
637 }
638
639 // In the event that the intersection of supported algorithms is empty we use the ones
640 // labelled as MUST that every implementation supports.
641 if len(candidateCiphers) == 0 {
642 // https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-07.html#section-9.3
643 candidateCiphers = []uint8{uint8(packet.CipherAES128)}
644 }
645 if len(candidateHashes) == 0 {
646 // https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-07.html#hash-algos
647 candidateHashes = []uint8{hashToHashId(crypto.SHA256)}
648 }
649 if len(candidateCipherSuites) == 0 {
650 if allPQ {
651 candidateCipherSuites = [][2]uint8{{uint8(packet.CipherAES256), uint8(packet.AEADModeOCB)}}
652 } else {
653 // https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-07.html#section-9.6
654 candidateCipherSuites = [][2]uint8{{uint8(packet.CipherAES128), uint8(packet.AEADModeOCB)}}
655 }
656 }
657
658 cipher := packet.CipherFunction(candidateCiphers[0])
659 aeadCipherSuite := packet.CipherSuite{
660 Cipher: packet.CipherFunction(candidateCipherSuites[0][0]),
661 Mode: packet.AEADMode(candidateCipherSuites[0][1]),
662 }
663
664 // If the cipher specified by config is a candidate, we'll use that.
665 configuredCipher := config.Cipher()
666 for _, c := range candidateCiphers {
667 cipherFunc := packet.CipherFunction(c)
668 if cipherFunc == configuredCipher {
669 cipher = cipherFunc
670 break
671 }
672 }
673
674 if params.SessionKey == nil {
675 if aeadSupported {
676 params.SessionKey = make([]byte, aeadCipherSuite.Cipher.KeySize())
677 } else {
678 params.SessionKey = make([]byte, cipher.KeySize())
679 }
680
681 if _, err := io.ReadFull(config.Random(), params.SessionKey); err != nil {
682 return nil, err
683 }
684 defer func() {
685 // zero the session key after we are done
686 for i := range params.SessionKey {
687 params.SessionKey[i] = 0
688 }
689 params.SessionKey = nil
690 }()
691 }
692
693 for idx, key := range encryptKeys {
694 // hide the keys of the hidden recipients
695 hidden := idx >= len(to)
696 if err := packet.SerializeEncryptedKeyAEADwithHiddenOption(params.KeyWriter, key.PublicKey, cipher, aeadSupported, params.SessionKey, hidden, config); err != nil {
697 return nil, err
698 }
699 }
700
701 for _, password := range params.Passwords {
702 if err = packet.SerializeSymmetricKeyEncryptedAEADReuseKey(params.KeyWriter, params.SessionKey, password, aeadSupported, params.Config); err != nil {
703 return nil, err
704 }
705 }
706
707 var candidateHashesPerSignature [][]uint8
708 for range params.Signers {
709 candidateHashesPerSignature = append(candidateHashesPerSignature, candidateHashes)
710 }
711 return encryptDataAndSign(dataWriter, params, candidateHashesPerSignature, candidateCompression, cipher, aeadSupported, aeadCipherSuite, intendedRecipients)
712 }
713
714 func encryptDataAndSign(
715 dataWriter io.Writer,
716 params *EncryptParams,
717 candidateHashes [][]uint8,
718 candidateCompression []uint8,
719 cipher packet.CipherFunction,
720 aeadSupported bool,
721 aeadCipherSuite packet.CipherSuite,
722 intendedRecipients []*packet.Recipient,
723 ) (plaintext io.WriteCloser, err error) {
724 sigType := packet.SigTypeBinary
725 if params.TextSig {
726 sigType = packet.SigTypeText
727 }
728 payload, err := packet.SerializeSymmetricallyEncrypted(dataWriter, cipher, aeadSupported, aeadCipherSuite, params.SessionKey, params.Config)
729 if err != nil {
730 return
731 }
732 payload, err = handleCompression(payload, candidateCompression, params.Config)
733 if err != nil {
734 return nil, err
735 }
736 return writeAndSign(payload, candidateHashes, params.Signers, params.Hints, sigType, intendedRecipients, params.OutsideSig, params.Config)
737 }
738
739 type SignParams struct {
740 // Hints contains file metadata for the literal data packet.
741 // The crypto-refresh recommends to not set file hints since the data is not included in the signature hash.
742 // See https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-12.html#section-5.9.
743 // If nil, default is used.
744 Hints *FileHints
745 // TextSig indicates if signatures of type SigTypeText should be produced
746 TextSig bool
747 // OutsideSig allows to set a signature that should be included
748 // in an inline signed message.
749 // Should only be used for exceptional cases.
750 // If nil, ignored.
751 OutsideSig []byte
752 // Config provides the config to be used.
753 // If Config is nil, sensible defaults will be used.
754 Config *packet.Config
755 }
756
757 // SignWithParams signs a message. The resulting WriteCloser must be closed after the
758 // contents of the file have been written.
759 // SignParams can contain optional params and can be nil for defaults.
760 func SignWithParams(output io.Writer, signers []*Entity, params *SignParams) (input io.WriteCloser, err error) {
761 if params == nil {
762 params = &SignParams{}
763 }
764 if len(signers) < 1 && params.OutsideSig == nil {
765 return nil, errors.InvalidArgumentError("no signer provided")
766 }
767 var candidateHashesPerSignature [][]uint8
768 candidateCompression := []uint8{
769 uint8(packet.CompressionNone),
770 uint8(packet.CompressionZIP),
771 uint8(packet.CompressionZLIB),
772 }
773 for _, signer := range signers {
774 // These are the possible hash functions that we'll use for the signature.
775 candidateHashes := []uint8{
776 hashToHashId(crypto.SHA256),
777 hashToHashId(crypto.SHA384),
778 hashToHashId(crypto.SHA512),
779 hashToHashId(crypto.SHA3_256),
780 hashToHashId(crypto.SHA3_512),
781 }
782 defaultHashes := candidateHashes[0:1]
783 primarySelfSignature, _ := signer.PrimarySelfSignature(params.Config.Now(), params.Config)
784 if primarySelfSignature == nil {
785 return nil, errors.StructuralError("signed entity has no self-signature")
786 }
787 preferredHashes := primarySelfSignature.PreferredHash
788 if len(preferredHashes) == 0 {
789 preferredHashes = defaultHashes
790 }
791 candidateHashes = intersectPreferences(candidateHashes, preferredHashes)
792 if len(candidateHashes) == 0 {
793 return nil, errors.StructuralError("cannot sign because signing key shares no common algorithms with candidate hashes")
794 }
795 candidateHashesPerSignature = append(candidateHashesPerSignature, candidateHashes)
796 candidateCompression = intersectPreferences(candidateCompression, primarySelfSignature.PreferredCompression)
797
798 }
799
800 sigType := packet.SigTypeBinary
801 if params.TextSig {
802 sigType = packet.SigTypeText
803 }
804
805 var payload io.WriteCloser
806 payload = noOpCloser{output}
807 payload, err = handleCompression(payload, candidateCompression, params.Config)
808 if err != nil {
809 return nil, err
810 }
811 return writeAndSign(payload, candidateHashesPerSignature, signers, params.Hints, sigType, nil, params.OutsideSig, params.Config)
812 }
813
814 // Sign signs a message. The resulting WriteCloser must be closed after the
815 // contents of the file have been written. Hints contains optional information
816 // that aids the recipients in processing the message.
817 // The crypto-refresh recommends to not set file hints since the data is not included in the signature hash.
818 // See https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-12.html#section-5.9.
819 // If config is nil, sensible defaults will be used.
820 func Sign(output io.Writer, signers []*Entity, hints *FileHints, config *packet.Config) (input io.WriteCloser, err error) {
821 return SignWithParams(output, signers, &SignParams{
822 Config: config,
823 Hints: hints,
824 })
825 }
826
827 // signatureWriter hashes the contents of a message while passing it along to
828 // literalData. When closed, it closes literalData, writes a signature packet
829 // to encryptedData and then also closes encryptedData.
830 type signatureWriter struct {
831 encryptedData io.WriteCloser
832 literalData io.WriteCloser
833 signatureContexts []*signatureContext
834 sigType packet.SignatureType
835 config *packet.Config
836 metadata *packet.LiteralData // V5 signatures protect document metadata
837 intendedRecipients []*packet.Recipient
838 flag int
839 }
840
841 type signatureContext struct {
842 hashType crypto.Hash
843 wrappedHash hash.Hash
844 h hash.Hash
845 salt []byte // v6 only
846 signer *packet.PrivateKey
847 outsideSig *packet.Signature
848 }
849
850 func (s signatureWriter) Write(data []byte) (int, error) {
851 for _, ctx := range s.signatureContexts {
852 if _, err := ctx.wrappedHash.Write(data); err != nil {
853 return 0, err
854 }
855 }
856 switch s.sigType {
857 case packet.SigTypeBinary:
858 return s.literalData.Write(data)
859 case packet.SigTypeText:
860 return writeCanonical(s.literalData, data, &s.flag)
861 }
862 return 0, errors.UnsupportedError("unsupported signature type: " + strconv.Itoa(int(s.sigType)))
863 }
864
865 func (s signatureWriter) Close() error {
866 if err := s.literalData.Close(); err != nil {
867 return err
868 }
869 for _, ctx := range s.signatureContexts {
870 var sig *packet.Signature
871 if ctx.outsideSig != nil {
872 // Signature that was supplied outside
873 sig = ctx.outsideSig
874 } else {
875 sig = createSignaturePacket(&ctx.signer.PublicKey, s.sigType, s.config)
876 sig.Hash = ctx.hashType
877 sig.Metadata = s.metadata
878 sig.IntendedRecipients = s.intendedRecipients
879 if err := sig.SetSalt(ctx.salt); err != nil {
880 return err
881 }
882 if err := sig.Sign(ctx.h, ctx.signer, s.config); err != nil {
883 return err
884 }
885 }
886 if err := sig.Serialize(s.encryptedData); err != nil {
887 return err
888 }
889 }
890 return s.encryptedData.Close()
891 }
892
893 func selectHashForSigningKey(config *packet.Config, primary *packet.PublicKey) crypto.Hash {
894 acceptableHashes := acceptableHashesToWrite(primary)
895 hash, ok := algorithm.HashToHashId(config.Hash())
896 if !ok {
897 return config.Hash()
898 }
899 for _, acceptableHashes := range acceptableHashes {
900 if acceptableHashes == hash {
901 return config.Hash()
902 }
903 }
904 if len(acceptableHashes) > 0 {
905 defaultAcceptedHash, ok := algorithm.HashIdToHash(acceptableHashes[0])
906 if ok {
907 return defaultAcceptedHash
908 }
909 }
910 return config.Hash()
911 }
912
913 func createSignaturePacket(signer *packet.PublicKey, sigType packet.SignatureType, config *packet.Config) *packet.Signature {
914 sigLifetimeSecs := config.SigLifetime()
915 hash := selectHashForSigningKey(config, signer)
916 return &packet.Signature{
917 Version: signer.Version,
918 SigType: sigType,
919 PubKeyAlgo: signer.PubKeyAlgo,
920 Hash: hash,
921 CreationTime: config.Now(),
922 IssuerKeyId: &signer.KeyId,
923 IssuerKeyVersion: uint8(signer.Version),
924 IssuerFingerprint: signer.Fingerprint,
925 Notations: config.Notations(),
926 SigLifetimeSecs: &sigLifetimeSecs,
927 }
928 }
929
930 // noOpCloser is like an ioutil.NopCloser, but for an io.Writer.
931 // TODO: we have two of these in OpenPGP packages alone. This probably needs
932 // to be promoted somewhere more common.
933 type noOpCloser struct {
934 w io.Writer
935 }
936
937 func (c noOpCloser) Write(data []byte) (n int, err error) {
938 return c.w.Write(data)
939 }
940
941 func (c noOpCloser) Close() error {
942 return nil
943 }
944
945 func handleCompression(compressed io.WriteCloser, candidateCompression []uint8, config *packet.Config) (data io.WriteCloser, err error) {
946 data = compressed
947 confAlgo := config.Compression()
948 if confAlgo == packet.CompressionNone {
949 return
950 }
951
952 // Set algorithm labelled as MUST as fallback
953 // https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-07.html#section-9.4
954 finalAlgo := packet.CompressionNone
955 // if compression specified by config available we will use it
956 for _, c := range candidateCompression {
957 if uint8(confAlgo) == c {
958 finalAlgo = confAlgo
959 break
960 }
961 }
962
963 if finalAlgo != packet.CompressionNone {
964 var compConfig *packet.CompressionConfig
965 if config != nil {
966 compConfig = config.CompressionConfig
967 }
968 data, err = packet.SerializeCompressed(compressed, finalAlgo, compConfig)
969 if err != nil {
970 return
971 }
972 }
973 return data, nil
974 }
975
976 // selectHash selects the preferred hash given the candidateHashes and the configuredHash
977 func selectHash(candidateHashes []byte, configuredHash crypto.Hash, signer *packet.PrivateKey) (hash crypto.Hash, err error) {
978 acceptableHashes := acceptableHashesToWrite(&signer.PublicKey)
979 candidateHashes = intersectPreferences(acceptableHashes, candidateHashes)
980
981 for _, hashId := range candidateHashes {
982 if h, ok := algorithm.HashIdToHash(hashId); ok && h.Available() {
983 hash = h
984 break
985 }
986 }
987
988 // If the hash specified by config is a candidate, we'll use that.
989 if configuredHash.Available() {
990 for _, hashId := range candidateHashes {
991 if h, ok := algorithm.HashIdToHash(hashId); ok && h == configuredHash {
992 hash = h
993 break
994 }
995 }
996 }
997
998 if hash == 0 {
999 if len(acceptableHashes) > 0 {
1000 if h, ok := algorithm.HashIdToHash(acceptableHashes[0]); ok {
1001 hash = h
1002 } else {
1003 return 0, errors.UnsupportedError("no candidate hash functions are compiled in.")
1004 }
1005 } else {
1006 return 0, errors.UnsupportedError("no candidate hash functions are compiled in.")
1007 }
1008 }
1009 return
1010 }
1011
1012 func parseOutsideSig(outsideSig []byte) (outSigPacket *packet.Signature, err error) {
1013 packets := packet.NewReader(bytes.NewReader(outsideSig))
1014 p, err := packets.Next()
1015 if goerrors.Is(err, io.EOF) {
1016 return nil, errors.ErrUnknownIssuer
1017 }
1018 if err != nil {
1019 return nil, err
1020 }
1021
1022 var ok bool
1023 outSigPacket, ok = p.(*packet.Signature)
1024 if !ok {
1025 return nil, errors.StructuralError("non signature packet found")
1026 }
1027 if outSigPacket.IssuerKeyId == nil {
1028 return nil, errors.StructuralError("signature doesn't have an issuer")
1029 }
1030 return outSigPacket, nil
1031 }
1032
1033 func acceptableHashesToWrite(singingKey *packet.PublicKey) []uint8 {
1034 switch singingKey.PubKeyAlgo {
1035 case packet.PubKeyAlgoEd448, packet.PubKeyAlgoMldsa87Ed448, packet.PubKeyAlgoSlhdsaShake256s:
1036 return []uint8{
1037 hashToHashId(crypto.SHA512),
1038 hashToHashId(crypto.SHA3_512),
1039 }
1040 case packet.PubKeyAlgoECDSA, packet.PubKeyAlgoEdDSA:
1041 if curve, err := singingKey.Curve(); err == nil {
1042 if curve == packet.Curve448 ||
1043 curve == packet.CurveNistP521 ||
1044 curve == packet.CurveBrainpoolP512 {
1045 return []uint8{
1046 hashToHashId(crypto.SHA512),
1047 hashToHashId(crypto.SHA3_512),
1048 }
1049 } else if curve == packet.CurveBrainpoolP384 ||
1050 curve == packet.CurveNistP384 {
1051 return []uint8{
1052 hashToHashId(crypto.SHA384),
1053 hashToHashId(crypto.SHA512),
1054 hashToHashId(crypto.SHA3_512),
1055 }
1056 }
1057 }
1058 }
1059 return []uint8{
1060 hashToHashId(crypto.SHA256),
1061 hashToHashId(crypto.SHA384),
1062 hashToHashId(crypto.SHA512),
1063 hashToHashId(crypto.SHA3_256),
1064 hashToHashId(crypto.SHA3_512),
1065 }
1066 }