Debian Codegraph @

openpgp/clearsign/clearsign.go

raw
1 // Copyright 2012 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 clearsign generates and processes OpenPGP, clear-signed data. See
6 // RFC 4880, section 7.
7 //
8 // Clearsigned messages are cryptographically signed, but the contents of the
9 // message are kept in plaintext so that it can be read without special tools.
10 package clearsign // import "github.com/ProtonMail/go-crypto/openpgp/clearsign"
11
12 import (
13 "bufio"
14 "bytes"
15 "crypto"
16 "fmt"
17 "hash"
18 "io"
19 "net/textproto"
20 "slices"
21 "strconv"
22 "strings"
23
24 "github.com/ProtonMail/go-crypto/openpgp"
25 "github.com/ProtonMail/go-crypto/openpgp/armor"
26 "github.com/ProtonMail/go-crypto/openpgp/errors"
27 "github.com/ProtonMail/go-crypto/openpgp/packet"
28 )
29
30 // A Block represents a clearsigned message. A signature on a Block can
31 // be checked by calling Block.VerifySignature.
32 type Block struct {
33 Headers textproto.MIMEHeader // Optional unverified Hash headers
34 Plaintext []byte // The original message text
35 Bytes []byte // The signed message
36 ArmoredSignature *armor.Block // The signature block
37 }
38
39 // start is the marker which denotes the beginning of a clearsigned message.
40 var start = []byte("\n-----BEGIN PGP SIGNED MESSAGE-----")
41
42 // dashEscape is prefixed to any lines that begin with a hyphen so that they
43 // can't be confused with endText.
44 var dashEscape = []byte("- ")
45
46 // endText is a marker which denotes the end of the message and the start of
47 // an armored signature.
48 var endText = []byte("-----BEGIN PGP SIGNATURE-----")
49
50 // end is a marker which denotes the end of the armored signature.
51 var end = []byte("\n-----END PGP SIGNATURE-----")
52
53 var allowedHashHeaderValues = []string{"MD5", "SHA1", "RIPEMD160", "SHA224", "SHA256", "SHA384", "SHA512", "SHA3-256", "SHA3-512"}
54
55 var crlf = []byte("\r\n")
56 var lf = byte('\n')
57
58 const hashHeader string = "Hash"
59
60 // getLine returns the first \r\n or \n delineated line from the given byte
61 // array. The line does not include the \r\n or \n. The remainder of the byte
62 // array (also not including the new line bytes) is also returned and this will
63 // always be smaller than the original argument.
64 func getLine(data []byte) (line, rest []byte) {
65 i := bytes.Index(data, []byte{'\n'})
66 var j int
67 if i < 0 {
68 i = len(data)
69 j = i
70 } else {
71 j = i + 1
72 if i > 0 && data[i-1] == '\r' {
73 i--
74 }
75 }
76 return data[0:i], data[j:]
77 }
78
79 // Decode finds the first clearsigned message in data and returns it, as well as
80 // the suffix of data which remains after the message. Any prefix data is
81 // discarded.
82 //
83 // If no message is found, or if the message is invalid, Decode returns nil and
84 // the whole data slice. The only allowed header type is Hash, and it is not
85 // verified against the signature hash.
86 func Decode(data []byte) (b *Block, rest []byte) {
87 // start begins with a newline. However, at the very beginning of
88 // the byte array, we'll accept the start string without it.
89 rest = data
90 if bytes.HasPrefix(data, start[1:]) {
91 rest = rest[len(start)-1:]
92 } else if i := bytes.Index(data, start); i >= 0 {
93 rest = rest[i+len(start):]
94 } else {
95 return nil, data
96 }
97
98 // Consume the start line and check it does not have a suffix.
99 suffix, rest := getLine(rest)
100 if len(suffix) != 0 {
101 return nil, data
102 }
103
104 var line []byte
105 b = &Block{
106 Headers: make(textproto.MIMEHeader),
107 }
108
109 // Next come a series of header lines.
110 for {
111 // This loop terminates because getLine's second result is
112 // always smaller than its argument.
113 if len(rest) == 0 {
114 return nil, data
115 }
116 // An empty line marks the end of the headers.
117 if line, rest = getLine(rest); len(strings.TrimSpace(string(line))) == 0 {
118 break
119 }
120
121 // Reject headers with control or Unicode characters.
122 if i := bytes.IndexFunc(line, func(r rune) bool {
123 return r < 0x20 || r > 0x7e
124 }); i != -1 {
125 return nil, data
126 }
127
128 i := bytes.Index(line, []byte{':'})
129 if i == -1 {
130 return nil, data
131 }
132
133 key, val := string(line[0:i]), string(line[i+1:])
134 key = strings.TrimSpace(key)
135 if key == hashHeader {
136 for _, val := range strings.Split(val, ",") {
137 val = strings.ToUpper(strings.TrimSpace(val))
138 if !slices.Contains(allowedHashHeaderValues, val) {
139 return nil, data
140 }
141 b.Headers.Add(key, val)
142 }
143 } else {
144 // Only "Hash" headers are allowed.
145 return nil, data
146 }
147 }
148
149 firstLine := true
150 for {
151 start := rest
152
153 line, rest = getLine(rest)
154 if len(line) == 0 && len(rest) == 0 {
155 // No armored data was found, so this isn't a complete message.
156 return nil, data
157 }
158 if bytes.Equal(line, endText) {
159 // Back up to the start of the line because armor expects to see the
160 // header line.
161 rest = start
162 break
163 }
164
165 // The final CRLF isn't included in the hash so we don't write it until
166 // we've seen the next line.
167 if firstLine {
168 firstLine = false
169 } else {
170 b.Bytes = append(b.Bytes, crlf...)
171 }
172
173 if bytes.HasPrefix(line, dashEscape) {
174 line = line[2:]
175 }
176 line = bytes.TrimRight(line, " \t")
177 b.Bytes = append(b.Bytes, line...)
178
179 b.Plaintext = append(b.Plaintext, line...)
180 b.Plaintext = append(b.Plaintext, lf)
181 }
182 if len(b.Plaintext) > 0 {
183 b.Plaintext = b.Plaintext[:len(b.Plaintext)-1]
184 }
185
186 // We want to find the extent of the armored data (including any newlines at
187 // the end).
188 i := bytes.Index(rest, end)
189 if i == -1 {
190 return nil, data
191 }
192 i += len(end)
193 for i < len(rest) && (rest[i] == '\r' || rest[i] == '\n') {
194 i++
195 }
196 armored := rest[:i]
197 rest = rest[i:]
198
199 var err error
200 b.ArmoredSignature, err = armor.Decode(bytes.NewBuffer(armored))
201 if err != nil {
202 return nil, data
203 }
204
205 return b, rest
206 }
207
208 // A dashEscaper is an io.WriteCloser which processes the body of a clear-signed
209 // message. The clear-signed message is written to buffered and a hash, suitable
210 // for signing, is maintained in h.
211 //
212 // When closed, an armored signature is created and written to complete the
213 // message.
214 type dashEscaper struct {
215 buffered *bufio.Writer
216 hashers []hash.Hash // one per key in privateKeys
217 hashTypes []crypto.Hash
218 toHash io.Writer // writes to all the hashes in hashers
219 salts [][]byte // salts for the signatures if v6
220 armorHeader map[string]string // Armor headers
221
222 atBeginningOfLine bool
223 isFirstLine bool
224
225 whitespace []byte
226 byteBuf []byte // a one byte buffer to save allocations
227
228 privateKeys []*packet.PrivateKey
229 config *packet.Config
230 }
231
232 func (d *dashEscaper) Write(data []byte) (n int, err error) {
233 for _, b := range data {
234 d.byteBuf[0] = b
235
236 if d.atBeginningOfLine {
237 // The final CRLF isn't included in the hash so we have to wait
238 // until this point (the start of the next line) before writing it.
239 if !d.isFirstLine {
240 if _, err = d.toHash.Write(crlf); err != nil {
241 return
242 }
243 }
244 d.isFirstLine = false
245 }
246
247 // Any whitespace at the end of the line has to be removed so we
248 // buffer it until we find out whether there's more on this line.
249 if b == ' ' || b == '\t' || b == '\r' {
250 d.whitespace = append(d.whitespace, b)
251 d.atBeginningOfLine = false
252 continue
253 }
254
255 if d.atBeginningOfLine {
256 // At the beginning of a line, hyphens have to be escaped.
257 if b == '-' {
258 // The signature isn't calculated over the dash-escaped text so
259 // the escape is only written to buffered.
260 if _, err = d.buffered.Write(dashEscape); err != nil {
261 return
262 }
263 if _, err = d.toHash.Write(d.byteBuf); err != nil {
264 return
265 }
266 d.atBeginningOfLine = false
267 } else if b == '\n' {
268 // Nothing to do because we delay writing CRLF to the hash.
269 } else {
270 if _, err = d.toHash.Write(d.byteBuf); err != nil {
271 return
272 }
273 d.atBeginningOfLine = false
274 }
275 if err = d.buffered.WriteByte(b); err != nil {
276 return
277 }
278 } else {
279 if b == '\n' {
280 // We got a raw \n. Drop any trailing whitespace and write a
281 // CRLF.
282 d.whitespace = d.whitespace[:0]
283 // We delay writing CRLF to the hash until the start of the
284 // next line.
285 if err = d.buffered.WriteByte(b); err != nil {
286 return
287 }
288 d.atBeginningOfLine = true
289 } else {
290 // Any buffered whitespace wasn't at the end of the line so
291 // we need to write it out.
292 if len(d.whitespace) > 0 {
293 if _, err = d.toHash.Write(d.whitespace); err != nil {
294 return
295 }
296 if _, err = d.buffered.Write(d.whitespace); err != nil {
297 return
298 }
299 d.whitespace = d.whitespace[:0]
300 }
301 if _, err = d.toHash.Write(d.byteBuf); err != nil {
302 return
303 }
304 if err = d.buffered.WriteByte(b); err != nil {
305 return
306 }
307 }
308 }
309 }
310
311 n = len(data)
312 return
313 }
314
315 func (d *dashEscaper) Close() (err error) {
316 if d.atBeginningOfLine {
317 if !d.isFirstLine {
318 if _, err := d.toHash.Write(crlf); err != nil {
319 return err
320 }
321 }
322 }
323 if err = d.buffered.WriteByte(lf); err != nil {
324 return
325 }
326
327 out, err := armor.EncodeWithChecksumOption(d.buffered, "PGP SIGNATURE", d.armorHeader, false)
328 if err != nil {
329 return
330 }
331
332 t := d.config.Now()
333 indexSalt := 0
334 for i, k := range d.privateKeys {
335 sig := new(packet.Signature)
336 sig.Version = k.Version
337 sig.SigType = packet.SigTypeText
338 sig.PubKeyAlgo = k.PubKeyAlgo
339 sig.Hash = d.hashTypes[i]
340 sig.CreationTime = t
341 sig.IssuerKeyId = &k.KeyId
342 sig.IssuerKeyVersion = uint8(k.Version)
343 sig.IssuerFingerprint = k.Fingerprint
344 sig.Notations = d.config.Notations()
345 sigLifetimeSecs := d.config.SigLifetime()
346 sig.SigLifetimeSecs = &sigLifetimeSecs
347 if k.Version == 6 {
348 if err = sig.SetSalt(d.salts[indexSalt]); err != nil {
349 return
350 }
351 indexSalt++
352 }
353 if err = sig.Sign(d.hashers[i], k, d.config); err != nil {
354 return
355 }
356 if err = sig.Serialize(out); err != nil {
357 return
358 }
359 }
360
361 if err = out.Close(); err != nil {
362 return
363 }
364 if err = d.buffered.Flush(); err != nil {
365 return
366 }
367 return
368 }
369
370 // Encode returns a WriteCloser which will clear-sign a message with privateKey
371 // and write it to w. If config is nil, sensible defaults are used.
372 func Encode(w io.Writer, privateKey *packet.PrivateKey, config *packet.Config) (plaintext io.WriteCloser, err error) {
373 return EncodeMulti(w, []*packet.PrivateKey{privateKey}, config)
374 }
375
376 // EncodeWithHeader returns a WriteCloser which will clear-sign a message with privateKey
377 // and write it to w. If config is nil, sensible defaults are used.
378 // Additionally provides a headers argument for custom headers.
379 func EncodeWithHeader(w io.Writer, privateKey *packet.PrivateKey, config *packet.Config, headers map[string]string) (plaintext io.WriteCloser, err error) {
380 return EncodeMultiWithHeader(w, []*packet.PrivateKey{privateKey}, config, headers)
381 }
382
383 // EncodeMulti returns a WriteCloser which will clear-sign a message with all the
384 // private keys indicated and write it to w. If config is nil, sensible defaults
385 // are used.
386 func EncodeMulti(w io.Writer, privateKeys []*packet.PrivateKey, config *packet.Config) (plaintext io.WriteCloser, err error) {
387 return EncodeMultiWithHeader(w, privateKeys, config, nil)
388 }
389
390 // EncodeMultiWithHeader returns a WriteCloser which will clear-sign a message with all the
391 // private keys indicated and write it to w. If config is nil, sensible defaults
392 // are used.
393 // Additionally provides a headers argument for custom headers.
394 func EncodeMultiWithHeader(w io.Writer, privateKeys []*packet.PrivateKey, config *packet.Config, headers map[string]string) (plaintext io.WriteCloser, err error) {
395 for _, k := range privateKeys {
396 if k.Encrypted {
397 return nil, errors.InvalidArgumentError(fmt.Sprintf("signing key %s is encrypted", k.KeyIdString()))
398 }
399 }
400
401 hashType := config.Hash()
402
403 var hashers []hash.Hash
404 var hashTypes []crypto.Hash
405 var ws []io.Writer
406 var salts [][]byte
407 for _, sk := range privateKeys {
408 acceptedHashes := acceptableHashesToWrite(&sk.PublicKey)
409 // acceptedHashes contains at least one hash
410 selectedHashType := acceptedHashes[0]
411 for _, acceptedHash := range acceptedHashes {
412 if hashType == acceptedHash {
413 selectedHashType = hashType
414 break
415 }
416 }
417 h := selectedHashType.New()
418 if sk.Version == 6 {
419 // generate salt
420 var salt []byte
421 salt, err = packet.SignatureSaltForHash(selectedHashType, config.Random())
422 if err != nil {
423 return
424 }
425 if _, err = h.Write(salt); err != nil {
426 return
427 }
428 salts = append(salts, salt)
429 }
430 hashers = append(hashers, h)
431 hashTypes = append(hashTypes, selectedHashType)
432 ws = append(ws, h)
433 }
434 toHash := io.MultiWriter(ws...)
435
436 buffered := bufio.NewWriter(w)
437 // start has a \n at the beginning that we don't want here.
438 if _, err = buffered.Write(start[1:]); err != nil {
439 return
440 }
441 if err = buffered.WriteByte(lf); err != nil {
442 return
443 }
444 // write headers
445 nonV6 := len(salts) < len(hashers)
446 // Crypto refresh: Headers SHOULD NOT be emitted
447 if nonV6 { // Emit header if non v6 signatures are present for compatibility
448 if err := writeHashHeader(buffered, hashTypes); err != nil {
449 return nil, err
450 }
451 }
452 if err = buffered.WriteByte(lf); err != nil {
453 return
454 }
455
456 plaintext = &dashEscaper{
457 buffered: buffered,
458 hashers: hashers,
459 hashTypes: hashTypes,
460 toHash: toHash,
461 salts: salts,
462 armorHeader: headers,
463
464 atBeginningOfLine: true,
465 isFirstLine: true,
466
467 byteBuf: make([]byte, 1),
468
469 privateKeys: privateKeys,
470 config: config,
471 }
472
473 return
474 }
475
476 // VerifySignature checks a clearsigned message signature, and checks that the
477 // hash algorithm in the header matches the hash algorithm in the signature.
478 func (b *Block) VerifySignature(keyring openpgp.KeyRing, config *packet.Config) (signer *openpgp.Entity, err error) {
479 _, signer, err = openpgp.VerifyDetachedSignature(keyring, bytes.NewBuffer(b.Bytes), b.ArmoredSignature.Body, config)
480 return
481 }
482
483 // writeHashHeader writes the legacy cleartext hash header to buffered.
484 func writeHashHeader(buffered *bufio.Writer, hashTypes []crypto.Hash) error {
485 seen := make(map[string]bool, len(hashTypes))
486 if _, err := buffered.WriteString(fmt.Sprintf("%s: ", hashHeader)); err != nil {
487 return err
488 }
489
490 for index, sigHashType := range hashTypes {
491 first := index == 0
492 name := nameOfHash(sigHashType)
493 if len(name) == 0 {
494 return errors.UnsupportedError("unknown hash type: " + strconv.Itoa(int(sigHashType)))
495 }
496
497 switch {
498 case !seen[name] && first:
499 if _, err := buffered.WriteString(name); err != nil {
500 return err
501 }
502 case !seen[name]:
503 if _, err := buffered.WriteString(fmt.Sprintf(",%s", name)); err != nil {
504 return err
505 }
506 }
507 seen[name] = true
508 }
509
510 if err := buffered.WriteByte(lf); err != nil {
511 return err
512 }
513
514 return nil
515 }
516
517 // nameOfHash returns the OpenPGP name for the given hash, or the empty string
518 // if the name isn't known. See RFC 4880, section 9.4.
519 func nameOfHash(h crypto.Hash) string {
520 switch h {
521 case crypto.SHA224:
522 return "SHA224"
523 case crypto.SHA256:
524 return "SHA256"
525 case crypto.SHA384:
526 return "SHA384"
527 case crypto.SHA512:
528 return "SHA512"
529 case crypto.SHA3_256:
530 return "SHA3-256"
531 case crypto.SHA3_512:
532 return "SHA3-512"
533 }
534 return ""
535 }
536
537 func acceptableHashesToWrite(singingKey *packet.PublicKey) []crypto.Hash {
538 switch singingKey.PubKeyAlgo {
539 case packet.PubKeyAlgoEd448, packet.PubKeyAlgoMldsa87Ed448:
540 return []crypto.Hash{
541 crypto.SHA512,
542 crypto.SHA3_512,
543 }
544 case packet.PubKeyAlgoECDSA, packet.PubKeyAlgoEdDSA:
545 if curve, err := singingKey.Curve(); err == nil {
546 if curve == packet.Curve448 ||
547 curve == packet.CurveNistP521 ||
548 curve == packet.CurveBrainpoolP512 {
549 return []crypto.Hash{
550 crypto.SHA512,
551 crypto.SHA3_512,
552 }
553 } else if curve == packet.CurveBrainpoolP384 ||
554 curve == packet.CurveNistP384 {
555 return []crypto.Hash{
556 crypto.SHA384,
557 crypto.SHA512,
558 crypto.SHA3_512,
559 }
560 }
561 }
562 }
563 return []crypto.Hash{
564 crypto.SHA256,
565 crypto.SHA384,
566 crypto.SHA512,
567 crypto.SHA3_256,
568 crypto.SHA3_512,
569 }
570 }