Debian Codegraph @

openpgp/packet/signature.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 packet
6
7 import (
8 "bytes"
9 "crypto"
10 "crypto/dsa"
11 "encoding/asn1"
12 "encoding/binary"
13 "hash"
14 "io"
15 "math/big"
16 "strconv"
17 "time"
18
19 "github.com/ProtonMail/go-crypto/openpgp/ecdsa"
20 "github.com/ProtonMail/go-crypto/openpgp/ed25519"
21 "github.com/ProtonMail/go-crypto/openpgp/ed448"
22 "github.com/ProtonMail/go-crypto/openpgp/eddsa"
23 "github.com/ProtonMail/go-crypto/openpgp/errors"
24 "github.com/ProtonMail/go-crypto/openpgp/internal/algorithm"
25 "github.com/ProtonMail/go-crypto/openpgp/internal/encoding"
26 "github.com/ProtonMail/go-crypto/openpgp/mldsa_eddsa"
27 "github.com/ProtonMail/go-crypto/openpgp/slhdsa"
28 "github.com/cloudflare/circl/sign/mldsa/mldsa65"
29 "github.com/cloudflare/circl/sign/mldsa/mldsa87"
30 )
31
32 const (
33 // First octet of key flags.
34 // See RFC 9580, section 5.2.3.29 for details.
35 KeyFlagCertify = 1 << iota
36 KeyFlagSign
37 KeyFlagEncryptCommunications
38 KeyFlagEncryptStorage
39 KeyFlagSplitKey
40 KeyFlagAuthenticate
41 _
42 KeyFlagGroupKey
43 )
44
45 const (
46 // First octet of keyserver preference flags.
47 // See RFC 9580, section 5.2.3.25 for details.
48 _ = 1 << iota
49 _
50 _
51 _
52 _
53 _
54 _
55 KeyserverPrefNoModify
56 )
57
58 const SaltNotationName = "[email protected]"
59
60 // Signature represents a signature. See RFC 9580, section 5.2.
61 type Signature struct {
62 Version int
63 SigType SignatureType
64 PubKeyAlgo PublicKeyAlgorithm
65 Hash crypto.Hash
66 // salt contains a random salt value for v6 signatures
67 // See RFC 9580 Section 5.2.4.
68 salt []byte
69
70 // HashSuffix is extra data that is hashed in after the signed data.
71 HashSuffix []byte
72 // HashTag contains the first two bytes of the hash for fast rejection
73 // of bad signed data.
74 HashTag [2]byte
75
76 // Metadata includes format, filename and time, and is protected by v5
77 // signatures of type 0x00 or 0x01. This metadata is included into the hash
78 // computation; if nil, six 0x00 bytes are used instead. See section 5.2.4.
79 Metadata *LiteralData
80
81 CreationTime time.Time
82
83 RSASignature encoding.Field
84 DSASigR, DSASigS encoding.Field
85 ECDSASigR, ECDSASigS encoding.Field
86 EdDSASigR, EdDSASigS encoding.Field
87 EdSig []byte
88 MldsaSig []byte
89 SlhdsaSig []byte
90
91 // rawSubpackets contains the unparsed subpackets, in order.
92 rawSubpackets []outputSubpacket
93
94 // The following are optional so are nil when not included in the
95 // signature.
96 // The exception is IssuerKeyVersion, which defaults to 0.
97
98 SigLifetimeSecs, KeyLifetimeSecs *uint32
99 PreferredSymmetric, PreferredHash, PreferredCompression []uint8
100 PreferredCipherSuites [][2]uint8
101 IssuerKeyId *uint64
102 IssuerKeyVersion uint8
103 IssuerFingerprint []byte
104 SignerUserId *string
105 IsPrimaryId *bool
106 Notations []*Notation
107 IntendedRecipients []*Recipient
108
109 // TrustLevel and TrustAmount can be set by the signer to assert that
110 // the key is not only valid but also trustworthy at the specified
111 // level.
112 // See RFC 9580, section 5.2.3.21 for details.
113 TrustLevel TrustLevel
114 TrustAmount TrustAmount
115
116 // TrustRegularExpression can be used in conjunction with trust Signature
117 // packets to limit the scope of the trust that is extended.
118 // See RFC 9580, section 5.2.3.22 for details.
119 TrustRegularExpression *string
120
121 // KeyserverPrefsValid is set if any keyserver preferences were given. See RFC 9580, section
122 // 5.2.3.25 for details.
123 KeyserverPrefsValid bool
124 KeyserverPrefNoModify bool
125
126 // PreferredKeyserver can be set to a URI where the latest version of the
127 // key that this signature is made over can be found. See RFC 9580, section
128 // 5.2.3.26 for details.
129 PreferredKeyserver string
130
131 // PolicyURI can be set to the URI of a document that describes the
132 // policy under which the signature was issued. See RFC 9580, section
133 // 5.2.3.28 for details.
134 PolicyURI string
135
136 // FlagsValid is set if any flags were given. See RFC 9580, section
137 // 5.2.3.29 for details.
138 FlagsValid bool
139 FlagCertify, FlagSign, FlagEncryptCommunications, FlagEncryptStorage, FlagSplitKey, FlagAuthenticate, FlagGroupKey bool
140
141 // RevocationReason is set if this signature has been revoked.
142 // See RFC 9580, section 5.2.3.31 for details.
143 RevocationReason *ReasonForRevocation
144 RevocationReasonText string
145
146 // In a self-signature, these flags are set there is a features subpacket
147 // indicating that the issuer implementation supports these features
148 // see https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh#features-subpacket
149 SEIPDv1, SEIPDv2 bool
150
151 // EmbeddedSignature, if non-nil, is a signature of the parent key, by
152 // this key. This prevents an attacker from claiming another's signing
153 // subkey as their own.
154 EmbeddedSignature *Signature
155
156 outSubpackets []outputSubpacket
157 }
158
159 // VerifiableSignature internally keeps state if the
160 // the signature has been verified before.
161 type VerifiableSignature struct {
162 Valid *bool // nil if it has not been verified yet
163 Packet *Signature
164 }
165
166 // NewVerifiableSig returns a struct of type VerifiableSignature referencing the input signature.
167 func NewVerifiableSig(signature *Signature) *VerifiableSignature {
168 return &VerifiableSignature{
169 Packet: signature,
170 }
171 }
172
173 // Salt returns the signature salt for v6 signatures.
174 func (sig *Signature) Salt() []byte {
175 if sig == nil {
176 return nil
177 }
178 return sig.salt
179 }
180
181 func (sig *Signature) parse(r io.Reader) (err error) {
182 // RFC 9580, section 5.2.3
183 var buf [7]byte
184 _, err = readFull(r, buf[:1])
185 if err != nil {
186 return
187 }
188 sig.Version = int(buf[0])
189 if sig.Version != 4 && sig.Version != 5 && sig.Version != 6 {
190 err = errors.UnsupportedError("signature packet version " + strconv.Itoa(int(buf[0])))
191 return
192 }
193
194 if V5Disabled && sig.Version == 5 {
195 return errors.UnsupportedError("support for parsing v5 entities is disabled; build with `-tags v5` if needed")
196 }
197
198 if sig.Version == 6 {
199 _, err = readFull(r, buf[:7])
200 } else {
201 _, err = readFull(r, buf[:5])
202 }
203 if err != nil {
204 return
205 }
206 sig.SigType = SignatureType(buf[0])
207 sig.PubKeyAlgo = PublicKeyAlgorithm(buf[1])
208 switch sig.PubKeyAlgo {
209 case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly, PubKeyAlgoDSA,
210 PubKeyAlgoECDSA, PubKeyAlgoEdDSA,
211 PubKeyAlgoEd25519, PubKeyAlgoEd448,
212 PubKeyAlgoMldsa65Ed25519, PubKeyAlgoMldsa87Ed448,
213 PubKeyAlgoSlhdsaShake128s, PubKeyAlgoSlhdsaShake128f, PubKeyAlgoSlhdsaShake256s:
214 default:
215 err = errors.UnsupportedError("public key algorithm " + strconv.Itoa(int(sig.PubKeyAlgo)))
216 return
217 }
218
219 var ok bool
220
221 if sig.Version < 5 {
222 sig.Hash, ok = algorithm.HashIdToHashWithSha1(buf[2])
223 } else {
224 sig.Hash, ok = algorithm.HashIdToHash(buf[2])
225 }
226
227 if !ok {
228 return errors.UnsupportedError("hash function " + strconv.Itoa(int(buf[2])))
229 }
230
231 var hashedSubpacketsLength uint32
232 if sig.Version == 6 {
233 // For a v6 signature, a four-octet length is used.
234 hashedSubpacketsLength =
235 uint32(buf[3])<<24 |
236 uint32(buf[4])<<16 |
237 uint32(buf[5])<<8 |
238 uint32(buf[6])
239 } else {
240 hashedSubpacketsLength = uint32(buf[3])<<8 | uint32(buf[4])
241 }
242 hashedSubpackets, err := readN(r, hashedSubpacketsLength)
243 if err != nil {
244 return
245 }
246 err = sig.buildHashSuffix(hashedSubpackets)
247 if err != nil {
248 return
249 }
250
251 err = parseSignatureSubpackets(sig, hashedSubpackets, true)
252 if err != nil {
253 return
254 }
255
256 if sig.Version == 6 {
257 _, err = readFull(r, buf[:4])
258 } else {
259 _, err = readFull(r, buf[:2])
260 }
261
262 if err != nil {
263 return
264 }
265 var unhashedSubpacketsLength uint32
266 if sig.Version == 6 {
267 unhashedSubpacketsLength = uint32(buf[0])<<24 | uint32(buf[1])<<16 | uint32(buf[2])<<8 | uint32(buf[3])
268 } else {
269 unhashedSubpacketsLength = uint32(buf[0])<<8 | uint32(buf[1])
270 }
271 unhashedSubpackets, err := readN(r, unhashedSubpacketsLength)
272 if err != nil {
273 return
274 }
275 err = parseSignatureSubpackets(sig, unhashedSubpackets, false)
276 if err != nil {
277 return
278 }
279
280 _, err = readFull(r, sig.HashTag[:2])
281 if err != nil {
282 return
283 }
284
285 if sig.Version == 6 {
286 // Only for v6 signatures, a variable-length field containing the salt
287 _, err = readFull(r, buf[:1])
288 if err != nil {
289 return
290 }
291 saltLength := int(buf[0])
292 var expectedSaltLength int
293 expectedSaltLength, err = SaltLengthForHash(sig.Hash)
294 if err != nil {
295 return
296 }
297 if saltLength != expectedSaltLength {
298 err = errors.StructuralError("unexpected salt size for the given hash algorithm")
299 return
300 }
301 salt := make([]byte, expectedSaltLength)
302 _, err = readFull(r, salt)
303 if err != nil {
304 return
305 }
306 sig.salt = salt
307 }
308
309 switch sig.PubKeyAlgo {
310 case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly:
311 sig.RSASignature = new(encoding.MPI)
312 _, err = sig.RSASignature.ReadFrom(r)
313 case PubKeyAlgoDSA:
314 sig.DSASigR = new(encoding.MPI)
315 if _, err = sig.DSASigR.ReadFrom(r); err != nil {
316 return
317 }
318
319 sig.DSASigS = new(encoding.MPI)
320 _, err = sig.DSASigS.ReadFrom(r)
321 case PubKeyAlgoECDSA:
322 sig.ECDSASigR = new(encoding.MPI)
323 if _, err = sig.ECDSASigR.ReadFrom(r); err != nil {
324 return
325 }
326
327 sig.ECDSASigS = new(encoding.MPI)
328 _, err = sig.ECDSASigS.ReadFrom(r)
329 case PubKeyAlgoEdDSA:
330 sig.EdDSASigR = new(encoding.MPI)
331 if _, err = sig.EdDSASigR.ReadFrom(r); err != nil {
332 return
333 }
334
335 sig.EdDSASigS = new(encoding.MPI)
336 if _, err = sig.EdDSASigS.ReadFrom(r); err != nil {
337 return
338 }
339 case PubKeyAlgoEd25519:
340 sig.EdSig, err = ed25519.ReadSignature(r)
341 if err != nil {
342 return
343 }
344 case PubKeyAlgoEd448:
345 sig.EdSig, err = ed448.ReadSignature(r)
346 if err != nil {
347 return
348 }
349 case PubKeyAlgoMldsa65Ed25519:
350 if err = sig.parseMldsaEddsaSignature(r, 64, mldsa65.SignatureSize); err != nil {
351 return
352 }
353 case PubKeyAlgoMldsa87Ed448:
354 if err = sig.parseMldsaEddsaSignature(r, 114, mldsa87.SignatureSize); err != nil {
355 return
356 }
357 case PubKeyAlgoSlhdsaShake128s, PubKeyAlgoSlhdsaShake128f, PubKeyAlgoSlhdsaShake256s:
358 if err = sig.parseSlhdsaSignature(r, sig.PubKeyAlgo); err != nil {
359 return
360 }
361 default:
362 panic("unreachable")
363 }
364 return
365 }
366
367 // parseMldsaEddsaSignature parses an ML-DSA + EdDSA signature as specified in
368 // https://www.rfc-editor.org/rfc/rfc9980.html#name-signature-packet-packet-typ
369 func (sig *Signature) parseMldsaEddsaSignature(r io.Reader, ecLen, dLen int) (err error) {
370 sig.EdSig = make([]byte, ecLen)
371 if _, err = io.ReadFull(r, sig.EdSig); err != nil {
372 return
373 }
374
375 sig.MldsaSig = make([]byte, dLen)
376 _, err = io.ReadFull(r, sig.MldsaSig)
377 return
378 }
379
380 // parseSlhdsaSignature parses an SLH-DSA signature as specified in
381 func (sig *Signature) parseSlhdsaSignature(r io.Reader, algID PublicKeyAlgorithm) (err error) {
382 scheme, err := GetSlhdsaSchemeFromAlgID(algID)
383 if err != nil {
384 return err
385 }
386 sig.SlhdsaSig = make([]byte, scheme.SignatureSize())
387 _, err = io.ReadFull(r, sig.SlhdsaSig)
388 return
389 }
390
391 // parseSignatureSubpackets parses subpackets of the main signature packet. See
392 // RFC 9580, section 5.2.3.1.
393 func parseSignatureSubpackets(sig *Signature, subpackets []byte, isHashed bool) (err error) {
394 for len(subpackets) > 0 {
395 subpackets, err = parseSignatureSubpacket(sig, subpackets, isHashed)
396 if err != nil {
397 return
398 }
399 }
400
401 if sig.CreationTime.IsZero() {
402 err = errors.StructuralError("no creation time in signature")
403 }
404
405 return
406 }
407
408 type signatureSubpacketType uint8
409
410 const (
411 creationTimeSubpacket signatureSubpacketType = 2
412 signatureExpirationSubpacket signatureSubpacketType = 3
413 exportableCertSubpacket signatureSubpacketType = 4
414 trustSubpacket signatureSubpacketType = 5
415 regularExpressionSubpacket signatureSubpacketType = 6
416 keyExpirationSubpacket signatureSubpacketType = 9
417 prefSymmetricAlgosSubpacket signatureSubpacketType = 11
418 issuerSubpacket signatureSubpacketType = 16
419 notationDataSubpacket signatureSubpacketType = 20
420 prefHashAlgosSubpacket signatureSubpacketType = 21
421 prefCompressionSubpacket signatureSubpacketType = 22
422 keyserverPrefsSubpacket signatureSubpacketType = 23
423 prefKeyserverSubpacket signatureSubpacketType = 24
424 primaryUserIdSubpacket signatureSubpacketType = 25
425 policyUriSubpacket signatureSubpacketType = 26
426 keyFlagsSubpacket signatureSubpacketType = 27
427 signerUserIdSubpacket signatureSubpacketType = 28
428 reasonForRevocationSubpacket signatureSubpacketType = 29
429 featuresSubpacket signatureSubpacketType = 30
430 embeddedSignatureSubpacket signatureSubpacketType = 32
431 issuerFingerprintSubpacket signatureSubpacketType = 33
432 intendedRecipientSubpacket signatureSubpacketType = 35
433 prefCipherSuitesSubpacket signatureSubpacketType = 39
434 )
435
436 // parseSignatureSubpacket parses a single subpacket. len(subpacket) is >= 1.
437 func parseSignatureSubpacket(sig *Signature, subpacket []byte, isHashed bool) (rest []byte, err error) {
438 // RFC 9580, section 5.2.3.7
439 var (
440 length uint32
441 packetType signatureSubpacketType
442 isCritical bool
443 )
444 if len(subpacket) == 0 {
445 err = errors.StructuralError("zero length signature subpacket")
446 return
447 }
448 switch {
449 case subpacket[0] < 192:
450 length = uint32(subpacket[0])
451 subpacket = subpacket[1:]
452 case subpacket[0] < 255:
453 if len(subpacket) < 2 {
454 goto Truncated
455 }
456 length = uint32(subpacket[0]-192)<<8 + uint32(subpacket[1]) + 192
457 subpacket = subpacket[2:]
458 default:
459 if len(subpacket) < 5 {
460 goto Truncated
461 }
462 length = uint32(subpacket[1])<<24 |
463 uint32(subpacket[2])<<16 |
464 uint32(subpacket[3])<<8 |
465 uint32(subpacket[4])
466 subpacket = subpacket[5:]
467 }
468 if length > uint32(len(subpacket)) {
469 goto Truncated
470 }
471 rest = subpacket[length:]
472 subpacket = subpacket[:length]
473 if len(subpacket) == 0 {
474 err = errors.StructuralError("zero length signature subpacket")
475 return
476 }
477 packetType = signatureSubpacketType(subpacket[0] & 0x7f)
478 isCritical = subpacket[0]&0x80 == 0x80
479 subpacket = subpacket[1:]
480 sig.rawSubpackets = append(sig.rawSubpackets, outputSubpacket{isHashed, packetType, isCritical, subpacket})
481 if !isHashed &&
482 packetType != issuerSubpacket &&
483 packetType != issuerFingerprintSubpacket &&
484 packetType != embeddedSignatureSubpacket {
485 return
486 }
487 switch packetType {
488 case creationTimeSubpacket:
489 if len(subpacket) != 4 {
490 err = errors.StructuralError("signature creation time not four bytes")
491 return
492 }
493 t := binary.BigEndian.Uint32(subpacket)
494 sig.CreationTime = time.Unix(int64(t), 0)
495 case signatureExpirationSubpacket:
496 // Signature expiration time, section 5.2.3.18
497 if len(subpacket) != 4 {
498 err = errors.StructuralError("expiration subpacket with bad length")
499 return
500 }
501 sig.SigLifetimeSecs = new(uint32)
502 *sig.SigLifetimeSecs = binary.BigEndian.Uint32(subpacket)
503 case exportableCertSubpacket:
504 if len(subpacket) < 1 {
505 err = errors.StructuralError("exportable certification subpacket with a bad length")
506 return
507 }
508 if subpacket[0] == 0 {
509 err = errors.UnsupportedError("signature with non-exportable certification")
510 return
511 }
512 case trustSubpacket:
513 if len(subpacket) != 2 {
514 err = errors.StructuralError("trust subpacket with bad length")
515 return
516 }
517 // Trust level and amount, section 5.2.3.21
518 sig.TrustLevel = TrustLevel(subpacket[0])
519 sig.TrustAmount = TrustAmount(subpacket[1])
520 case regularExpressionSubpacket:
521 if len(subpacket) == 0 {
522 err = errors.StructuralError("regexp subpacket with bad length")
523 return
524 }
525 // Trust regular expression, section 5.2.3.22
526 // RFC specifies the string should be null-terminated; remove a null byte from the end
527 if subpacket[len(subpacket)-1] != 0x00 {
528 err = errors.StructuralError("expected regular expression to be null-terminated")
529 return
530 }
531 trustRegularExpression := string(subpacket[:len(subpacket)-1])
532 sig.TrustRegularExpression = &trustRegularExpression
533 case keyExpirationSubpacket:
534 // Key expiration time, section 5.2.3.13
535 if len(subpacket) != 4 {
536 err = errors.StructuralError("key expiration subpacket with bad length")
537 return
538 }
539 sig.KeyLifetimeSecs = new(uint32)
540 *sig.KeyLifetimeSecs = binary.BigEndian.Uint32(subpacket)
541 case prefSymmetricAlgosSubpacket:
542 // Preferred symmetric algorithms, section 5.2.3.14
543 sig.PreferredSymmetric = make([]byte, len(subpacket))
544 copy(sig.PreferredSymmetric, subpacket)
545 case issuerSubpacket:
546 // Issuer, section 5.2.3.12
547 if sig.Version > 4 && isHashed {
548 err = errors.StructuralError("issuer subpacket found in v6 key")
549 return
550 }
551 if len(subpacket) != 8 {
552 err = errors.StructuralError("issuer subpacket with bad length")
553 return
554 }
555 if sig.Version <= 4 {
556 sig.IssuerKeyId = new(uint64)
557 *sig.IssuerKeyId = binary.BigEndian.Uint64(subpacket)
558 }
559 case notationDataSubpacket:
560 // Notation data, section 5.2.3.24
561 if len(subpacket) < 8 {
562 err = errors.StructuralError("notation data subpacket with bad length")
563 return
564 }
565
566 nameLength := uint32(subpacket[4])<<8 | uint32(subpacket[5])
567 valueLength := uint32(subpacket[6])<<8 | uint32(subpacket[7])
568 if len(subpacket) != int(nameLength)+int(valueLength)+8 {
569 err = errors.StructuralError("notation data subpacket with bad length")
570 return
571 }
572
573 notation := Notation{
574 IsHumanReadable: (subpacket[0] & 0x80) == 0x80,
575 Name: string(subpacket[8:(nameLength + 8)]),
576 Value: subpacket[(nameLength + 8):(valueLength + nameLength + 8)],
577 IsCritical: isCritical,
578 }
579
580 sig.Notations = append(sig.Notations, &notation)
581 case prefHashAlgosSubpacket:
582 // Preferred hash algorithms, section 5.2.3.16
583 sig.PreferredHash = make([]byte, len(subpacket))
584 copy(sig.PreferredHash, subpacket)
585 case prefCompressionSubpacket:
586 // Preferred compression algorithms, section 5.2.3.17
587 sig.PreferredCompression = make([]byte, len(subpacket))
588 copy(sig.PreferredCompression, subpacket)
589 case keyserverPrefsSubpacket:
590 // Keyserver preferences, section 5.2.3.25
591 sig.KeyserverPrefsValid = true
592 if len(subpacket) == 0 {
593 return
594 }
595 if subpacket[0]&KeyserverPrefNoModify != 0 {
596 sig.KeyserverPrefNoModify = true
597 }
598 case prefKeyserverSubpacket:
599 // Preferred keyserver, section 5.2.3.26
600 sig.PreferredKeyserver = string(subpacket)
601 case primaryUserIdSubpacket:
602 // Primary User ID, section 5.2.3.27
603 if len(subpacket) != 1 {
604 err = errors.StructuralError("primary user id subpacket with bad length")
605 return
606 }
607 sig.IsPrimaryId = new(bool)
608 if subpacket[0] > 0 {
609 *sig.IsPrimaryId = true
610 }
611 case keyFlagsSubpacket:
612 // Key flags, section 5.2.3.29
613 sig.FlagsValid = true
614 if len(subpacket) == 0 {
615 return
616 }
617 if subpacket[0]&KeyFlagCertify != 0 {
618 sig.FlagCertify = true
619 }
620 if subpacket[0]&KeyFlagSign != 0 {
621 sig.FlagSign = true
622 }
623 if subpacket[0]&KeyFlagEncryptCommunications != 0 {
624 sig.FlagEncryptCommunications = true
625 }
626 if subpacket[0]&KeyFlagEncryptStorage != 0 {
627 sig.FlagEncryptStorage = true
628 }
629 if subpacket[0]&KeyFlagSplitKey != 0 {
630 sig.FlagSplitKey = true
631 }
632 if subpacket[0]&KeyFlagAuthenticate != 0 {
633 sig.FlagAuthenticate = true
634 }
635 if subpacket[0]&KeyFlagGroupKey != 0 {
636 sig.FlagGroupKey = true
637 }
638 case signerUserIdSubpacket:
639 userId := string(subpacket)
640 sig.SignerUserId = &userId
641 case reasonForRevocationSubpacket:
642 // Reason For Revocation, section 5.2.3.31
643 if len(subpacket) == 0 {
644 err = errors.StructuralError("empty revocation reason subpacket")
645 return
646 }
647 sig.RevocationReason = new(ReasonForRevocation)
648 *sig.RevocationReason = NewReasonForRevocation(subpacket[0])
649 sig.RevocationReasonText = string(subpacket[1:])
650 case featuresSubpacket:
651 // Features subpacket, section 5.2.3.32 specifies a very general
652 // mechanism for OpenPGP implementations to signal support for new
653 // features.
654 if len(subpacket) > 0 {
655 if subpacket[0]&0x01 != 0 {
656 sig.SEIPDv1 = true
657 }
658 // 0x02 and 0x04 are reserved
659 if subpacket[0]&0x08 != 0 {
660 sig.SEIPDv2 = true
661 }
662 }
663 case embeddedSignatureSubpacket:
664 // Only usage is in signatures that cross-certify
665 // signing subkeys. section 5.2.3.34 describes the
666 // format, with its usage described in section 11.1
667 if sig.EmbeddedSignature != nil {
668 err = errors.StructuralError("Cannot have multiple embedded signatures")
669 return
670 }
671 // A Primary Key Binding signature must not itself carry an embedded
672 // signature, otherwise the structure can recurse without bound.
673 if sig.SigType == SigTypePrimaryKeyBinding {
674 return nil, errors.StructuralError("embedded signature within a primary key binding signature")
675 }
676 sig.EmbeddedSignature = new(Signature)
677 if err := sig.EmbeddedSignature.parse(bytes.NewBuffer(subpacket)); err != nil {
678 return nil, err
679 }
680 if sigType := sig.EmbeddedSignature.SigType; sigType != SigTypePrimaryKeyBinding {
681 return nil, errors.StructuralError("cross-signature has unexpected type " + strconv.Itoa(int(sigType)))
682 }
683 case policyUriSubpacket:
684 // Policy URI, section 5.2.3.28
685 sig.PolicyURI = string(subpacket)
686 case issuerFingerprintSubpacket:
687 if len(subpacket) == 0 {
688 err = errors.StructuralError("empty issuer fingerprint subpacket")
689 return
690 }
691 v, l := subpacket[0], len(subpacket[1:])
692 if v >= 5 && l != 32 || v < 5 && l != 20 {
693 return nil, errors.StructuralError("bad fingerprint length")
694 }
695 sig.IssuerKeyVersion = subpacket[0]
696 sig.IssuerFingerprint = make([]byte, l)
697 copy(sig.IssuerFingerprint, subpacket[1:])
698 sig.IssuerKeyId = new(uint64)
699 if v >= 5 {
700 *sig.IssuerKeyId = binary.BigEndian.Uint64(subpacket[1:9])
701 } else {
702 *sig.IssuerKeyId = binary.BigEndian.Uint64(subpacket[13:21])
703 }
704 case intendedRecipientSubpacket:
705 // Intended Recipient Fingerprint, section 5.2.3.36
706 if len(subpacket) < 1 {
707 return nil, errors.StructuralError("invalid intended recipient fingerpring length")
708 }
709 version, length := subpacket[0], len(subpacket[1:])
710 if version >= 5 && length != 32 || version < 5 && length != 20 {
711 return nil, errors.StructuralError("invalid fingerprint length")
712 }
713 fingerprint := make([]byte, length)
714 copy(fingerprint, subpacket[1:])
715 sig.IntendedRecipients = append(sig.IntendedRecipients, &Recipient{int(version), fingerprint})
716 case prefCipherSuitesSubpacket:
717 // Preferred AEAD cipher suites, section 5.2.3.15
718 if len(subpacket)%2 != 0 {
719 err = errors.StructuralError("invalid aead cipher suite length")
720 return
721 }
722
723 sig.PreferredCipherSuites = make([][2]byte, len(subpacket)/2)
724
725 for i := 0; i < len(subpacket)/2; i++ {
726 sig.PreferredCipherSuites[i] = [2]uint8{subpacket[2*i], subpacket[2*i+1]}
727 }
728 default:
729 if isCritical {
730 err = errors.UnsupportedError("unknown critical signature subpacket type " + strconv.Itoa(int(packetType)))
731 return
732 }
733 }
734 return
735
736 Truncated:
737 err = errors.StructuralError("signature subpacket truncated")
738 return
739 }
740
741 // subpacketLengthLength returns the length, in bytes, of an encoded length value.
742 func subpacketLengthLength(length int) int {
743 if length < 192 {
744 return 1
745 }
746 if length < 16320 {
747 return 2
748 }
749 return 5
750 }
751
752 func (sig *Signature) CheckKeyIdOrFingerprint(pk *PublicKey) bool {
753 if sig.IssuerKeyVersion != 0 && len(sig.IssuerFingerprint) >= 20 {
754 return int(sig.IssuerKeyVersion) == pk.Version && bytes.Equal(sig.IssuerFingerprint, pk.Fingerprint)
755 }
756 return sig.IssuerKeyId != nil && *sig.IssuerKeyId == pk.KeyId
757 }
758
759 func (sig *Signature) CheckKeyIdOrFingerprintExplicit(fingerprint []byte, keyId uint64) bool {
760 if sig.IssuerKeyVersion != 0 && len(sig.IssuerFingerprint) >= 20 && fingerprint != nil {
761 return bytes.Equal(sig.IssuerFingerprint, fingerprint)
762 }
763 return sig.IssuerKeyId != nil && *sig.IssuerKeyId == keyId
764 }
765
766 // serializeSubpacketLength marshals the given length into to.
767 func serializeSubpacketLength(to []byte, length int) int {
768 // RFC 9580, Section 4.2.1.
769 if length < 192 {
770 to[0] = byte(length)
771 return 1
772 }
773 if length < 16320 {
774 length -= 192
775 to[0] = byte((length >> 8) + 192)
776 to[1] = byte(length)
777 return 2
778 }
779 to[0] = 255
780 to[1] = byte(length >> 24)
781 to[2] = byte(length >> 16)
782 to[3] = byte(length >> 8)
783 to[4] = byte(length)
784 return 5
785 }
786
787 // subpacketsLength returns the serialized length, in bytes, of the given
788 // subpackets.
789 func subpacketsLength(subpackets []outputSubpacket, hashed bool) (length int) {
790 for _, subpacket := range subpackets {
791 if subpacket.hashed == hashed {
792 length += subpacketLengthLength(len(subpacket.contents) + 1)
793 length += 1 // type byte
794 length += len(subpacket.contents)
795 }
796 }
797 return
798 }
799
800 // serializeSubpackets marshals the given subpackets into to.
801 func serializeSubpackets(to []byte, subpackets []outputSubpacket, hashed bool) {
802 for _, subpacket := range subpackets {
803 if subpacket.hashed == hashed {
804 n := serializeSubpacketLength(to, len(subpacket.contents)+1)
805 to[n] = byte(subpacket.subpacketType)
806 if subpacket.isCritical {
807 to[n] |= 0x80
808 }
809 to = to[1+n:]
810 n = copy(to, subpacket.contents)
811 to = to[n:]
812 }
813 }
814 }
815
816 // SigExpired returns whether sig is a signature that has expired or is created
817 // in the future.
818 func (sig *Signature) SigExpired(currentTime time.Time) bool {
819 if sig.CreationTime.Unix() > currentTime.Unix() {
820 return true
821 }
822 if sig.SigLifetimeSecs == nil || *sig.SigLifetimeSecs == 0 {
823 return false
824 }
825 expiry := sig.CreationTime.Add(time.Duration(*sig.SigLifetimeSecs) * time.Second)
826 return currentTime.Unix() > expiry.Unix()
827 }
828
829 // buildHashSuffix constructs the HashSuffix member of sig in preparation for signing.
830 func (sig *Signature) buildHashSuffix(hashedSubpackets []byte) (err error) {
831 var hashId byte
832 var ok bool
833
834 if sig.Version < 5 {
835 hashId, ok = algorithm.HashToHashIdWithSha1(sig.Hash)
836 } else {
837 hashId, ok = algorithm.HashToHashId(sig.Hash)
838 }
839
840 if !ok {
841 sig.HashSuffix = nil
842 return errors.InvalidArgumentError("hash cannot be represented in OpenPGP: " + strconv.Itoa(int(sig.Hash)))
843 }
844
845 hashedFields := bytes.NewBuffer([]byte{
846 uint8(sig.Version),
847 uint8(sig.SigType),
848 uint8(sig.PubKeyAlgo),
849 uint8(hashId),
850 })
851 hashedSubpacketsLength := len(hashedSubpackets)
852 if sig.Version == 6 {
853 // v6 signatures store the length in 4 octets
854 hashedFields.Write([]byte{
855 uint8(hashedSubpacketsLength >> 24),
856 uint8(hashedSubpacketsLength >> 16),
857 uint8(hashedSubpacketsLength >> 8),
858 uint8(hashedSubpacketsLength),
859 })
860 } else {
861 hashedFields.Write([]byte{
862 uint8(hashedSubpacketsLength >> 8),
863 uint8(hashedSubpacketsLength),
864 })
865 }
866 lenPrefix := hashedFields.Len()
867 hashedFields.Write(hashedSubpackets)
868
869 var l uint64 = uint64(lenPrefix + len(hashedSubpackets))
870 if sig.Version == 5 {
871 // v5 case
872 hashedFields.Write([]byte{0x05, 0xff})
873 hashedFields.Write([]byte{
874 uint8(l >> 56), uint8(l >> 48), uint8(l >> 40), uint8(l >> 32),
875 uint8(l >> 24), uint8(l >> 16), uint8(l >> 8), uint8(l),
876 })
877 } else {
878 // v4 and v6 case
879 hashedFields.Write([]byte{byte(sig.Version), 0xff})
880 hashedFields.Write([]byte{
881 uint8(l >> 24), uint8(l >> 16), uint8(l >> 8), uint8(l),
882 })
883 }
884 sig.HashSuffix = make([]byte, hashedFields.Len())
885 copy(sig.HashSuffix, hashedFields.Bytes())
886 return
887 }
888
889 func (sig *Signature) signPrepareHash(h hash.Hash) (digest []byte, err error) {
890 hashedSubpacketsLen := subpacketsLength(sig.outSubpackets, true)
891 hashedSubpackets := make([]byte, hashedSubpacketsLen)
892 serializeSubpackets(hashedSubpackets, sig.outSubpackets, true)
893 err = sig.buildHashSuffix(hashedSubpackets)
894 if err != nil {
895 return
896 }
897 if sig.Version == 5 && (sig.SigType == 0x00 || sig.SigType == 0x01) {
898 sig.AddMetadataToHashSuffix()
899 }
900
901 h.Write(sig.HashSuffix)
902 digest = h.Sum(nil)
903 copy(sig.HashTag[:], digest)
904 return
905 }
906
907 // PrepareSign must be called to create a hash object before Sign for v6 signatures.
908 // The created hash object initially hashes a randomly generated salt
909 // as required by v6 signatures. The generated salt is stored in sig. If the signature is not v6,
910 // the method returns an empty hash object.
911 // See RFC 9580 Section 5.2.4.
912 func (sig *Signature) PrepareSign(config *Config) (hash.Hash, error) {
913 if !sig.Hash.Available() {
914 return nil, errors.UnsupportedError("hash function")
915 }
916 hasher := sig.Hash.New()
917 if sig.Version == 6 {
918 if sig.salt == nil {
919 var err error
920 sig.salt, err = SignatureSaltForHash(sig.Hash, config.Random())
921 if err != nil {
922 return nil, err
923 }
924 }
925 hasher.Write(sig.salt)
926 }
927 return hasher, nil
928 }
929
930 // SetSalt sets the signature salt for v6 signatures.
931 // Assumes salt is generated correctly and checks if length matches.
932 // If the signature is not v6, the method ignores the salt.
933 // Use PrepareSign whenever possible instead of generating and
934 // hashing the salt externally.
935 // See RFC 9580 Section 5.2.4.
936 func (sig *Signature) SetSalt(salt []byte) error {
937 if sig.Version == 6 {
938 expectedSaltLength, err := SaltLengthForHash(sig.Hash)
939 if err != nil {
940 return err
941 }
942 if salt == nil || len(salt) != expectedSaltLength {
943 return errors.InvalidArgumentError("unexpected salt size for the given hash algorithm")
944 }
945 sig.salt = salt
946 }
947 return nil
948 }
949
950 // PrepareVerify must be called to create a hash object before verifying v6 signatures.
951 // The created hash object initially hashes the internally stored salt.
952 // If the signature is not v6, the method returns an empty hash object.
953 // See RFC 9580 Section 5.2.4.
954 func (sig *Signature) PrepareVerify() (hash.Hash, error) {
955 if !sig.Hash.Available() {
956 return nil, errors.UnsupportedError("hash function")
957 }
958 hasher := sig.Hash.New()
959 if sig.Version == 6 {
960 if sig.salt == nil {
961 return nil, errors.StructuralError("v6 requires a salt for the hash to be signed")
962 }
963 hasher.Write(sig.salt)
964 }
965 return hasher, nil
966 }
967
968 // Sign signs a message with a private key. The hash, h, must contain
969 // the hash of the message to be signed and will be mutated by this function.
970 // On success, the signature is stored in sig. Call Serialize to write it out.
971 // If config is nil, sensible defaults will be used.
972 func (sig *Signature) Sign(h hash.Hash, priv *PrivateKey, config *Config) (err error) {
973 if priv.Dummy() {
974 return errors.ErrDummyPrivateKey("dummy key found")
975 }
976 sig.Version = priv.PublicKey.Version
977 sig.IssuerKeyVersion = uint8(priv.PublicKey.Version)
978 sig.IssuerFingerprint = priv.PublicKey.Fingerprint
979 if sig.Version < 6 && config.RandomizeSignaturesViaNotation() {
980 sig.removeNotationsWithName(SaltNotationName)
981 salt, err := SignatureSaltForHash(sig.Hash, config.Random())
982 if err != nil {
983 return err
984 }
985 notation := Notation{
986 Name: SaltNotationName,
987 Value: salt,
988 IsCritical: false,
989 IsHumanReadable: false,
990 }
991 sig.Notations = append(sig.Notations, &notation)
992 }
993 sig.outSubpackets, err = sig.buildSubpackets(config)
994 if err != nil {
995 return err
996 }
997 digest, err := sig.signPrepareHash(h)
998 if err != nil {
999 return
1000 }
1001 switch priv.PubKeyAlgo {
1002 case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly:
1003 // supports both *rsa.PrivateKey and crypto.Signer
1004 sigdata, err := priv.PrivateKey.(crypto.Signer).Sign(config.Random(), digest, sig.Hash)
1005 if err == nil {
1006 sig.RSASignature = encoding.NewMPI(sigdata)
1007 }
1008 case PubKeyAlgoDSA:
1009 dsaPriv := priv.PrivateKey.(*dsa.PrivateKey)
1010
1011 // Need to truncate hashBytes to match FIPS 186-3 section 4.6.
1012 subgroupSize := (dsaPriv.Q.BitLen() + 7) / 8
1013 if len(digest) > subgroupSize {
1014 digest = digest[:subgroupSize]
1015 }
1016 r, s, err := dsa.Sign(config.Random(), dsaPriv, digest)
1017 if err == nil {
1018 sig.DSASigR = new(encoding.MPI).SetBig(r)
1019 sig.DSASigS = new(encoding.MPI).SetBig(s)
1020 }
1021 case PubKeyAlgoECDSA:
1022 var r, s *big.Int
1023 if sk, ok := priv.PrivateKey.(*ecdsa.PrivateKey); ok {
1024 r, s, err = ecdsa.Sign(config.Random(), sk, digest)
1025 } else {
1026 var b []byte
1027 b, err = priv.PrivateKey.(crypto.Signer).Sign(config.Random(), digest, sig.Hash)
1028 if err == nil {
1029 r, s, err = unwrapECDSASig(b)
1030 }
1031 }
1032
1033 if err == nil {
1034 sig.ECDSASigR = new(encoding.MPI).SetBig(r)
1035 sig.ECDSASigS = new(encoding.MPI).SetBig(s)
1036 }
1037 case PubKeyAlgoEdDSA:
1038 sk := priv.PrivateKey.(*eddsa.PrivateKey)
1039 r, s, err := eddsa.Sign(sk, digest)
1040 if err == nil {
1041 sig.EdDSASigR = encoding.NewMPI(r)
1042 sig.EdDSASigS = encoding.NewMPI(s)
1043 }
1044 case PubKeyAlgoEd25519:
1045 sk := priv.PrivateKey.(*ed25519.PrivateKey)
1046 signature, err := ed25519.Sign(sk, digest)
1047 if err == nil {
1048 sig.EdSig = signature
1049 }
1050 case PubKeyAlgoEd448:
1051 sk := priv.PrivateKey.(*ed448.PrivateKey)
1052 signature, err := ed448.Sign(sk, digest)
1053 if err == nil {
1054 sig.EdSig = signature
1055 }
1056 case PubKeyAlgoMldsa65Ed25519, PubKeyAlgoMldsa87Ed448:
1057 if sig.Version != 6 {
1058 return errors.StructuralError("cannot use MldsaEdDsa on a non-v6 signature")
1059 }
1060 sk := priv.PrivateKey.(*mldsa_eddsa.PrivateKey)
1061 dSig, ecSig, err := mldsa_eddsa.Sign(sk, digest)
1062
1063 if err == nil {
1064 sig.MldsaSig = dSig
1065 sig.EdSig = ecSig
1066 }
1067 case PubKeyAlgoSlhdsaShake128s, PubKeyAlgoSlhdsaShake128f, PubKeyAlgoSlhdsaShake256s:
1068 if sig.Version != 6 {
1069 return errors.StructuralError("cannot use SLH-DSA on a non-v6 signature")
1070 }
1071 sk := priv.PrivateKey.(*slhdsa.PrivateKey)
1072 dSig, err := slhdsa.Sign(sk, digest)
1073
1074 if err == nil {
1075 sig.SlhdsaSig = dSig
1076 }
1077 default:
1078 err = errors.UnsupportedError("public key algorithm: " + strconv.Itoa(int(sig.PubKeyAlgo)))
1079 }
1080
1081 return
1082 }
1083
1084 // unwrapECDSASig parses the two integer components of an ASN.1-encoded ECDSA signature.
1085 func unwrapECDSASig(b []byte) (r, s *big.Int, err error) {
1086 var ecsdaSig struct {
1087 R, S *big.Int
1088 }
1089 _, err = asn1.Unmarshal(b, &ecsdaSig)
1090 if err != nil {
1091 return
1092 }
1093 return ecsdaSig.R, ecsdaSig.S, nil
1094 }
1095
1096 // SignUserId computes a signature from priv, asserting that pub is a valid
1097 // key for the identity id. On success, the signature is stored in sig. Call
1098 // Serialize to write it out.
1099 // If config is nil, sensible defaults will be used.
1100 func (sig *Signature) SignUserId(id string, pub *PublicKey, priv *PrivateKey, config *Config) error {
1101 if priv.Dummy() {
1102 return errors.ErrDummyPrivateKey("dummy key found")
1103 }
1104 prepareHash, err := sig.PrepareSign(config)
1105 if err != nil {
1106 return err
1107 }
1108 if err := userIdSignatureHash(id, pub, prepareHash); err != nil {
1109 return err
1110 }
1111 return sig.Sign(prepareHash, priv, config)
1112 }
1113
1114 // SignDirectKeyBinding computes a signature from priv
1115 // On success, the signature is stored in sig.
1116 // Call Serialize to write it out.
1117 // If config is nil, sensible defaults will be used.
1118 func (sig *Signature) SignDirectKeyBinding(pub *PublicKey, priv *PrivateKey, config *Config) error {
1119 if priv.Dummy() {
1120 return errors.ErrDummyPrivateKey("dummy key found")
1121 }
1122 prepareHash, err := sig.PrepareSign(config)
1123 if err != nil {
1124 return err
1125 }
1126 if err := directKeySignatureHash(pub, prepareHash); err != nil {
1127 return err
1128 }
1129 return sig.Sign(prepareHash, priv, config)
1130 }
1131
1132 // CrossSignKey computes a signature from signingKey on pub hashed using hashKey. On success,
1133 // the signature is stored in sig. Call Serialize to write it out.
1134 // If config is nil, sensible defaults will be used.
1135 func (sig *Signature) CrossSignKey(pub *PublicKey, hashKey *PublicKey, signingKey *PrivateKey,
1136 config *Config) error {
1137 prepareHash, err := sig.PrepareSign(config)
1138 if err != nil {
1139 return err
1140 }
1141 h, err := keySignatureHash(hashKey, pub, prepareHash)
1142 if err != nil {
1143 return err
1144 }
1145 return sig.Sign(h, signingKey, config)
1146 }
1147
1148 // SignKey computes a signature from priv, asserting that pub is a subkey. On
1149 // success, the signature is stored in sig. Call Serialize to write it out.
1150 // If config is nil, sensible defaults will be used.
1151 func (sig *Signature) SignKey(pub *PublicKey, priv *PrivateKey, config *Config) error {
1152 if priv.Dummy() {
1153 return errors.ErrDummyPrivateKey("dummy key found")
1154 }
1155 prepareHash, err := sig.PrepareSign(config)
1156 if err != nil {
1157 return err
1158 }
1159 h, err := keySignatureHash(&priv.PublicKey, pub, prepareHash)
1160 if err != nil {
1161 return err
1162 }
1163 return sig.Sign(h, priv, config)
1164 }
1165
1166 // RevokeKey computes a revocation signature of pub using priv. On success, the signature is
1167 // stored in sig. Call Serialize to write it out.
1168 // If config is nil, sensible defaults will be used.
1169 func (sig *Signature) RevokeKey(pub *PublicKey, priv *PrivateKey, config *Config) error {
1170 prepareHash, err := sig.PrepareSign(config)
1171 if err != nil {
1172 return err
1173 }
1174 if err := keyRevocationHash(pub, prepareHash); err != nil {
1175 return err
1176 }
1177 return sig.Sign(prepareHash, priv, config)
1178 }
1179
1180 // RevokeSubkey computes a subkey revocation signature of pub using priv.
1181 // On success, the signature is stored in sig. Call Serialize to write it out.
1182 // If config is nil, sensible defaults will be used.
1183 func (sig *Signature) RevokeSubkey(pub *PublicKey, priv *PrivateKey, config *Config) error {
1184 // Identical to a subkey binding signature
1185 return sig.SignKey(pub, priv, config)
1186 }
1187
1188 // Serialize marshals sig to w. Sign, SignUserId or SignKey must have been
1189 // called first.
1190 func (sig *Signature) Serialize(w io.Writer) (err error) {
1191 if len(sig.outSubpackets) == 0 {
1192 sig.outSubpackets = sig.rawSubpackets
1193 }
1194 if sig.RSASignature == nil && sig.DSASigR == nil && sig.ECDSASigR == nil && sig.EdDSASigR == nil && sig.EdSig == nil && sig.SlhdsaSig == nil {
1195 return errors.InvalidArgumentError("Signature: need to call Sign, SignUserId or SignKey before Serialize")
1196 }
1197
1198 sigLength := 0
1199 switch sig.PubKeyAlgo {
1200 case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly:
1201 sigLength = int(sig.RSASignature.EncodedLength())
1202 case PubKeyAlgoDSA:
1203 sigLength = int(sig.DSASigR.EncodedLength())
1204 sigLength += int(sig.DSASigS.EncodedLength())
1205 case PubKeyAlgoECDSA:
1206 sigLength = int(sig.ECDSASigR.EncodedLength())
1207 sigLength += int(sig.ECDSASigS.EncodedLength())
1208 case PubKeyAlgoEdDSA:
1209 sigLength = int(sig.EdDSASigR.EncodedLength())
1210 sigLength += int(sig.EdDSASigS.EncodedLength())
1211 case PubKeyAlgoEd25519:
1212 sigLength = ed25519.SignatureSize
1213 case PubKeyAlgoEd448:
1214 sigLength = ed448.SignatureSize
1215 case PubKeyAlgoMldsa65Ed25519, PubKeyAlgoMldsa87Ed448:
1216 sigLength = len(sig.EdSig)
1217 sigLength += len(sig.MldsaSig)
1218 case PubKeyAlgoSlhdsaShake128s, PubKeyAlgoSlhdsaShake128f, PubKeyAlgoSlhdsaShake256s:
1219 sigLength += len(sig.SlhdsaSig)
1220 default:
1221 panic("impossible")
1222 }
1223
1224 hashedSubpacketsLen := subpacketsLength(sig.outSubpackets, true)
1225 unhashedSubpacketsLen := subpacketsLength(sig.outSubpackets, false)
1226 length := 4 + /* length of version|signature type|public-key algorithm|hash algorithm */
1227 2 /* length of hashed subpackets */ + hashedSubpacketsLen +
1228 2 /* length of unhashed subpackets */ + unhashedSubpacketsLen +
1229 2 /* hash tag */ + sigLength
1230 if sig.Version == 6 {
1231 length += 4 + /* the two length fields are four-octet instead of two */
1232 1 + /* salt length */
1233 len(sig.salt) /* length salt */
1234 }
1235 err = serializeHeader(w, packetTypeSignature, length)
1236 if err != nil {
1237 return
1238 }
1239 err = sig.serializeBody(w)
1240 if err != nil {
1241 return err
1242 }
1243 return
1244 }
1245
1246 func (sig *Signature) serializeBody(w io.Writer) (err error) {
1247 var fields []byte
1248 if sig.Version == 6 {
1249 // v6 signatures use 4 octets for length
1250 hashedSubpacketsLen :=
1251 uint32(uint32(sig.HashSuffix[4])<<24) |
1252 uint32(uint32(sig.HashSuffix[5])<<16) |
1253 uint32(uint32(sig.HashSuffix[6])<<8) |
1254 uint32(sig.HashSuffix[7])
1255 fields = sig.HashSuffix[:8+hashedSubpacketsLen]
1256 } else {
1257 hashedSubpacketsLen := uint16(uint16(sig.HashSuffix[4])<<8) |
1258 uint16(sig.HashSuffix[5])
1259 fields = sig.HashSuffix[:6+hashedSubpacketsLen]
1260
1261 }
1262 _, err = w.Write(fields)
1263 if err != nil {
1264 return
1265 }
1266
1267 unhashedSubpacketsLen := subpacketsLength(sig.outSubpackets, false)
1268 var unhashedSubpackets []byte
1269 if sig.Version == 6 {
1270 unhashedSubpackets = make([]byte, 4+unhashedSubpacketsLen)
1271 unhashedSubpackets[0] = byte(unhashedSubpacketsLen >> 24)
1272 unhashedSubpackets[1] = byte(unhashedSubpacketsLen >> 16)
1273 unhashedSubpackets[2] = byte(unhashedSubpacketsLen >> 8)
1274 unhashedSubpackets[3] = byte(unhashedSubpacketsLen)
1275 serializeSubpackets(unhashedSubpackets[4:], sig.outSubpackets, false)
1276 } else {
1277 unhashedSubpackets = make([]byte, 2+unhashedSubpacketsLen)
1278 unhashedSubpackets[0] = byte(unhashedSubpacketsLen >> 8)
1279 unhashedSubpackets[1] = byte(unhashedSubpacketsLen)
1280 serializeSubpackets(unhashedSubpackets[2:], sig.outSubpackets, false)
1281 }
1282
1283 _, err = w.Write(unhashedSubpackets)
1284 if err != nil {
1285 return
1286 }
1287 _, err = w.Write(sig.HashTag[:])
1288 if err != nil {
1289 return
1290 }
1291
1292 if sig.Version == 6 {
1293 // write salt for v6 signatures
1294 _, err = w.Write([]byte{uint8(len(sig.salt))})
1295 if err != nil {
1296 return
1297 }
1298 _, err = w.Write(sig.salt)
1299 if err != nil {
1300 return
1301 }
1302 }
1303
1304 switch sig.PubKeyAlgo {
1305 case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly:
1306 _, err = w.Write(sig.RSASignature.EncodedBytes())
1307 case PubKeyAlgoDSA:
1308 if _, err = w.Write(sig.DSASigR.EncodedBytes()); err != nil {
1309 return
1310 }
1311 _, err = w.Write(sig.DSASigS.EncodedBytes())
1312 case PubKeyAlgoECDSA:
1313 if _, err = w.Write(sig.ECDSASigR.EncodedBytes()); err != nil {
1314 return
1315 }
1316 _, err = w.Write(sig.ECDSASigS.EncodedBytes())
1317 case PubKeyAlgoEdDSA:
1318 if _, err = w.Write(sig.EdDSASigR.EncodedBytes()); err != nil {
1319 return
1320 }
1321 _, err = w.Write(sig.EdDSASigS.EncodedBytes())
1322 case PubKeyAlgoEd25519:
1323 err = ed25519.WriteSignature(w, sig.EdSig)
1324 case PubKeyAlgoEd448:
1325 err = ed448.WriteSignature(w, sig.EdSig)
1326 case PubKeyAlgoMldsa65Ed25519, PubKeyAlgoMldsa87Ed448:
1327 if _, err = w.Write(sig.EdSig); err != nil {
1328 return
1329 }
1330 _, err = w.Write(sig.MldsaSig)
1331 case PubKeyAlgoSlhdsaShake128s, PubKeyAlgoSlhdsaShake128f, PubKeyAlgoSlhdsaShake256s:
1332 _, err = w.Write(sig.SlhdsaSig)
1333 default:
1334 panic("impossible")
1335 }
1336 return
1337 }
1338
1339 // outputSubpacket represents a subpacket to be marshaled.
1340 type outputSubpacket struct {
1341 hashed bool // true if this subpacket is in the hashed area.
1342 subpacketType signatureSubpacketType
1343 isCritical bool
1344 contents []byte
1345 }
1346
1347 func (sig *Signature) buildSubpackets(config *Config) (subpackets []outputSubpacket, err error) {
1348 creationTime := make([]byte, 4)
1349 binary.BigEndian.PutUint32(creationTime, uint32(sig.CreationTime.Unix()))
1350 // Signature Creation Time
1351 subpackets = append(subpackets, outputSubpacket{true, creationTimeSubpacket, !config.GenerateNonCriticalSignatureCreationTime(), creationTime})
1352 // Signature Expiration Time
1353 if sig.SigLifetimeSecs != nil && *sig.SigLifetimeSecs != 0 {
1354 sigLifetime := make([]byte, 4)
1355 binary.BigEndian.PutUint32(sigLifetime, *sig.SigLifetimeSecs)
1356 subpackets = append(subpackets, outputSubpacket{true, signatureExpirationSubpacket, true, sigLifetime})
1357 }
1358 // Trust Signature
1359 if sig.TrustLevel != 0 {
1360 subpackets = append(subpackets, outputSubpacket{true, trustSubpacket, true, []byte{byte(sig.TrustLevel), byte(sig.TrustAmount)}})
1361 }
1362 // Regular Expression
1363 if sig.TrustRegularExpression != nil {
1364 // RFC specifies the string should be null-terminated; add a null byte to the end
1365 subpackets = append(subpackets, outputSubpacket{true, regularExpressionSubpacket, true, []byte(*sig.TrustRegularExpression + "\000")})
1366 }
1367 // Key Expiration Time
1368 if sig.KeyLifetimeSecs != nil && *sig.KeyLifetimeSecs != 0 {
1369 keyLifetime := make([]byte, 4)
1370 binary.BigEndian.PutUint32(keyLifetime, *sig.KeyLifetimeSecs)
1371 subpackets = append(subpackets, outputSubpacket{true, keyExpirationSubpacket, true, keyLifetime})
1372 }
1373 // Preferred Symmetric Ciphers for v1 SEIPD
1374 if len(sig.PreferredSymmetric) > 0 {
1375 subpackets = append(subpackets, outputSubpacket{true, prefSymmetricAlgosSubpacket, false, sig.PreferredSymmetric})
1376 }
1377 // Issuer Key ID
1378 if sig.IssuerKeyId != nil && sig.Version == 4 {
1379 keyId := make([]byte, 8)
1380 binary.BigEndian.PutUint64(keyId, *sig.IssuerKeyId)
1381 // Note: making this critical breaks RPM <=4.16.
1382 // See: https://github.com/ProtonMail/go-crypto/issues/263
1383 subpackets = append(subpackets, outputSubpacket{true, issuerSubpacket, false, keyId})
1384 }
1385 // Notation Data
1386 for _, notation := range sig.Notations {
1387 subpackets = append(
1388 subpackets,
1389 outputSubpacket{
1390 true,
1391 notationDataSubpacket,
1392 notation.IsCritical,
1393 notation.getData(),
1394 })
1395 }
1396 // Preferred Hash Algorithms
1397 if len(sig.PreferredHash) > 0 {
1398 subpackets = append(subpackets, outputSubpacket{true, prefHashAlgosSubpacket, false, sig.PreferredHash})
1399 }
1400 // Preferred Compression Algorithms
1401 if len(sig.PreferredCompression) > 0 {
1402 subpackets = append(subpackets, outputSubpacket{true, prefCompressionSubpacket, false, sig.PreferredCompression})
1403 }
1404 // Keyserver Preferences
1405 // Keyserver preferences may only appear in self-signatures or certification signatures.
1406 if sig.KeyserverPrefsValid {
1407 var prefs byte
1408 if sig.KeyserverPrefNoModify {
1409 prefs |= KeyserverPrefNoModify
1410 }
1411 subpackets = append(subpackets, outputSubpacket{true, keyserverPrefsSubpacket, false, []byte{prefs}})
1412 }
1413 // Preferred Keyserver
1414 if len(sig.PreferredKeyserver) > 0 {
1415 subpackets = append(subpackets, outputSubpacket{true, prefKeyserverSubpacket, false, []uint8(sig.PreferredKeyserver)})
1416 }
1417 // Primary User ID
1418 if sig.IsPrimaryId != nil && *sig.IsPrimaryId {
1419 subpackets = append(subpackets, outputSubpacket{true, primaryUserIdSubpacket, false, []byte{1}})
1420 }
1421 // Policy URI
1422 if len(sig.PolicyURI) > 0 {
1423 subpackets = append(subpackets, outputSubpacket{true, policyUriSubpacket, false, []uint8(sig.PolicyURI)})
1424 }
1425 // Key Flags
1426 // Key flags may only appear in self-signatures or certification signatures.
1427 if sig.FlagsValid {
1428 var flags byte
1429 if sig.FlagCertify {
1430 flags |= KeyFlagCertify
1431 }
1432 if sig.FlagSign {
1433 flags |= KeyFlagSign
1434 }
1435 if sig.FlagEncryptCommunications {
1436 flags |= KeyFlagEncryptCommunications
1437 }
1438 if sig.FlagEncryptStorage {
1439 flags |= KeyFlagEncryptStorage
1440 }
1441 if sig.FlagSplitKey {
1442 flags |= KeyFlagSplitKey
1443 }
1444 if sig.FlagAuthenticate {
1445 flags |= KeyFlagAuthenticate
1446 }
1447 if sig.FlagGroupKey {
1448 flags |= KeyFlagGroupKey
1449 }
1450 subpackets = append(subpackets, outputSubpacket{true, keyFlagsSubpacket, !config.GenerateNonCriticalKeyFlags(), []byte{flags}})
1451 }
1452 // Signer's User ID
1453 if sig.SignerUserId != nil {
1454 subpackets = append(subpackets, outputSubpacket{true, signerUserIdSubpacket, false, []byte(*sig.SignerUserId)})
1455 }
1456 // Reason for Revocation
1457 // Revocation reason appears only in revocation signatures and is serialized as per section 5.2.3.31.
1458 if sig.RevocationReason != nil {
1459 subpackets = append(subpackets, outputSubpacket{true, reasonForRevocationSubpacket, true,
1460 append([]uint8{uint8(*sig.RevocationReason)}, []uint8(sig.RevocationReasonText)...)})
1461 }
1462 // Features
1463 var features = byte(0x00)
1464 if sig.SEIPDv1 {
1465 features |= 0x01
1466 }
1467 if sig.SEIPDv2 {
1468 features |= 0x08
1469 }
1470 if features != 0x00 {
1471 subpackets = append(subpackets, outputSubpacket{true, featuresSubpacket, false, []byte{features}})
1472 }
1473 // Embedded Signature
1474 // EmbeddedSignature appears only in subkeys capable of signing and is serialized as per section 5.2.3.34.
1475 if sig.EmbeddedSignature != nil {
1476 var buf bytes.Buffer
1477 err = sig.EmbeddedSignature.serializeBody(&buf)
1478 if err != nil {
1479 return
1480 }
1481 subpackets = append(subpackets, outputSubpacket{true, embeddedSignatureSubpacket, true, buf.Bytes()})
1482 }
1483 // Issuer Fingerprint
1484 if sig.IssuerKeyVersion != 0 && sig.IssuerFingerprint != nil {
1485 contents := append([]uint8{sig.IssuerKeyVersion}, sig.IssuerFingerprint...)
1486 subpackets = append(subpackets, outputSubpacket{true, issuerFingerprintSubpacket, sig.Version >= 5, contents})
1487 }
1488 // Intended Recipient Fingerprint
1489 for _, recipient := range sig.IntendedRecipients {
1490 subpackets = append(
1491 subpackets,
1492 outputSubpacket{
1493 true,
1494 intendedRecipientSubpacket,
1495 false,
1496 recipient.Serialize(),
1497 })
1498 }
1499 // Preferred AEAD Ciphersuites
1500 if len(sig.PreferredCipherSuites) > 0 {
1501 serialized := make([]byte, len(sig.PreferredCipherSuites)*2)
1502 for i, cipherSuite := range sig.PreferredCipherSuites {
1503 serialized[2*i] = cipherSuite[0]
1504 serialized[2*i+1] = cipherSuite[1]
1505 }
1506 subpackets = append(subpackets, outputSubpacket{true, prefCipherSuitesSubpacket, false, serialized})
1507 }
1508 return
1509 }
1510
1511 // AddMetadataToHashSuffix modifies the current hash suffix to include metadata
1512 // (format, filename, and time). Version 5 keys protect this data including it
1513 // in the hash computation. See section 5.2.4.
1514 func (sig *Signature) AddMetadataToHashSuffix() {
1515 if sig == nil || sig.Version != 5 {
1516 return
1517 }
1518 if sig.SigType != 0x00 && sig.SigType != 0x01 {
1519 return
1520 }
1521 lit := sig.Metadata
1522 if lit == nil {
1523 // This will translate into six 0x00 bytes.
1524 lit = &LiteralData{}
1525 }
1526
1527 // Extract the current byte count
1528 n := sig.HashSuffix[len(sig.HashSuffix)-8:]
1529 l := uint64(
1530 uint64(n[0])<<56 | uint64(n[1])<<48 | uint64(n[2])<<40 | uint64(n[3])<<32 |
1531 uint64(n[4])<<24 | uint64(n[5])<<16 | uint64(n[6])<<8 | uint64(n[7]))
1532
1533 suffix := bytes.NewBuffer(nil)
1534 suffix.Write(sig.HashSuffix[:l])
1535
1536 // Add the metadata
1537 var buf [4]byte
1538 buf[0] = lit.Format
1539 fileName := lit.FileName
1540 if len(lit.FileName) > 255 {
1541 fileName = fileName[:255]
1542 }
1543 buf[1] = byte(len(fileName))
1544 suffix.Write(buf[:2])
1545 suffix.Write([]byte(lit.FileName))
1546 binary.BigEndian.PutUint32(buf[:], lit.Time)
1547 suffix.Write(buf[:])
1548
1549 suffix.Write([]byte{0x05, 0xff})
1550 suffix.Write([]byte{
1551 uint8(l >> 56), uint8(l >> 48), uint8(l >> 40), uint8(l >> 32),
1552 uint8(l >> 24), uint8(l >> 16), uint8(l >> 8), uint8(l),
1553 })
1554 sig.HashSuffix = suffix.Bytes()
1555 }
1556
1557 // SaltLengthForHash selects the required salt length for the given hash algorithm,
1558 // as per Table 23 (Hash algorithm registry) of the crypto refresh.
1559 // See RFC 9580 Section 9.5.
1560 func SaltLengthForHash(hash crypto.Hash) (int, error) {
1561 switch hash {
1562 case crypto.SHA256, crypto.SHA224, crypto.SHA3_256:
1563 return 16, nil
1564 case crypto.SHA384:
1565 return 24, nil
1566 case crypto.SHA512, crypto.SHA3_512:
1567 return 32, nil
1568 default:
1569 return 0, errors.UnsupportedError("hash function not supported for V6 signatures")
1570 }
1571 }
1572
1573 // SignatureSaltForHash generates a random signature salt
1574 // with the length for the given hash algorithm.
1575 // See RFC 9580 Section 9.5.
1576 func SignatureSaltForHash(hash crypto.Hash, randReader io.Reader) ([]byte, error) {
1577 saltLength, err := SaltLengthForHash(hash)
1578 if err != nil {
1579 return nil, err
1580 }
1581 salt := make([]byte, saltLength)
1582 _, err = io.ReadFull(randReader, salt)
1583 if err != nil {
1584 return nil, err
1585 }
1586 return salt, nil
1587 }
1588
1589 // removeNotationsWithName removes all notations in this signature with the given name.
1590 func (sig *Signature) removeNotationsWithName(name string) {
1591 if sig == nil || sig.Notations == nil {
1592 return
1593 }
1594 updatedNotations := make([]*Notation, 0, len(sig.Notations))
1595 for _, notation := range sig.Notations {
1596 if notation.Name != name {
1597 updatedNotations = append(updatedNotations, notation)
1598 }
1599 }
1600 sig.Notations = updatedNotations
1601 }