git » chasquid » next » tree

[next] / internal / dkim / verify_test.go

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
package dkim

import (
	"context"
	"crypto"
	"encoding/base64"
	"errors"
	"fmt"
	"net"
	"strings"
	"testing"

	"github.com/google/go-cmp/cmp"
)

func toCRLF(s string) string {
	return strings.ReplaceAll(s, "\n", "\r\n")
}

func makeLookupTXT(results map[string][]string) lookupTXTFunc {
	return func(ctx context.Context, domain string) ([]string, error) {
		return results[domain], nil
	}
}

func TestVerifyRF6376CExample(t *testing.T) {
	ctx := t.Context()
	ctx = WithTraceFunc(ctx, t.Logf)

	// Use the public key from the example in RFC 6376 appendix C.
	// https://datatracker.ietf.org/doc/html/rfc6376#appendix-C
	ctx = WithLookupTXTFunc(ctx, makeLookupTXT(map[string][]string{
		"brisbane._domainkey.example.com": {
			"v=DKIM1; p=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQ" +
				"KBgQDwIRP/UC3SBsEmGqZ9ZJW3/DkMoGeLnQg1fWn7/zYt" +
				"IxN2SnFCjxOCKG9v3b4jYfcTNh5ijSsq631uBItLa7od+v" +
				"/RtdC2UzJ1lWT947qR+Rcac2gbto/NMqJ0fzfVjH4OuKhi" +
				"tdY9tf6mcwGjaNBcWToIMmPSPDdQPNUYckcQ2QIDAQAB",
		},
	}))

	// Note that the examples in the RFC text have multiple issues:
	// - The double space in "game.  Are" should be a single
	//   space. Otherwise, the body hash does not match.
	//   https://www.rfc-editor.org/errata/eid3192
	// - The header indentation is incorrect. This causes
	//   signature validation failure (because the example uses simple
	//   canonicalization, which leaves the indentation untouched).
	//   https://www.rfc-editor.org/errata/eid4926
	message := toCRLF(
		`DKIM-Signature: v=1; a=rsa-sha256; s=brisbane; d=example.com;
      c=simple/simple; q=dns/txt; i=joe@football.example.com;
      h=Received : From : To : Subject : Date : Message-ID;
      bh=2jUSOH9NhtVGCQWNr9BrIAPreKQjO6Sn7XIkfJVOzv8=;
      b=AuUoFEfDxTDkHlLXSZEpZj79LICEps6eda7W3deTVFOk4yAUoqOB
      4nujc7YopdG5dWLSdNg6xNAZpOPr+kHxt1IrE+NahM6L/LbvaHut
      KVdkLLkpVaVVQPzeRDI009SO2Il5Lu7rDNH6mZckBdrIx0orEtZV
      4bmp/YzhwvcubU4=;
Received: from client1.football.example.com  [192.0.2.1]
      by submitserver.example.com with SUBMISSION;
      Fri, 11 Jul 2003 21:01:54 -0700 (PDT)
From: Joe SixPack <joe@football.example.com>
To: Suzie Q <suzie@shopping.example.net>
Subject: Is dinner ready?
Date: Fri, 11 Jul 2003 21:00:37 -0700 (PDT)
Message-ID: <20030712040037.46341.5F8J@football.example.com>

Hi.

We lost the game. Are you hungry yet?

Joe.
`)

	res, err := VerifyMessage(ctx, message)
	if res.Valid != 1 || err != nil {
		t.Errorf("VerifyMessage: wanted 1 valid / nil; got %v / %v", res, err)
	}

	// Extend the message, check it does not pass validation.
	res, err = VerifyMessage(ctx, message+"Extra line.\r\n")
	if res.Valid != 0 || err != nil {
		t.Errorf("VerifyMessage: wanted 0 valid / nil; got %v / %v", res, err)
	}

	// Alter a header, check it does not pass validation.
	res, err = VerifyMessage(ctx,
		strings.Replace(message, "Subject", "X-Subject", 1))
	if res.Valid != 0 || err != nil {
		t.Errorf("VerifyMessage: wanted 0 valid / nil; got %v / %v", res, err)
	}
}

func TestVerifyRFC8463Example(t *testing.T) {
	ctx := t.Context()
	ctx = WithTraceFunc(ctx, t.Logf)

	// Use the public keys from the example in RFC 8463 appendix A.2.
	// https://datatracker.ietf.org/doc/html/rfc6376#appendix-C
	ctx = WithLookupTXTFunc(ctx, makeLookupTXT(map[string][]string{
		"brisbane._domainkey.football.example.com": {
			"v=DKIM1; k=ed25519; " +
				"p=11qYAYKxCrfVS/7TyWQHOg7hcvPapiMlrwIaaPcHURo="},

		"test._domainkey.football.example.com": {
			"v=DKIM1; k=rsa; " +
				"p=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDkHlOQoBTzWR" +
				"iGs5V6NpP3idY6Wk08a5qhdR6wy5bdOKb2jLQiY/J16JYi0Qvx/b" +
				"yYzCNb3W91y3FutACDfzwQ/BC/e/8uBsCR+yz1Lxj+PL6lHvqMKr" +
				"M3rG4hstT5QjvHO9PzoxZyVYLzBfO2EeC3Ip3G+2kryOTIKT+l/K" +
				"4w3QIDAQAB"},
	}))

	message := toCRLF(
		`DKIM-Signature: v=1; a=ed25519-sha256; c=relaxed/relaxed;
 d=football.example.com; i=@football.example.com;
 q=dns/txt; s=brisbane; t=1528637909; h=from : to :
 subject : date : message-id : from : subject : date;
 bh=2jUSOH9NhtVGCQWNr9BrIAPreKQjO6Sn7XIkfJVOzv8=;
 b=/gCrinpcQOoIfuHNQIbq4pgh9kyIK3AQUdt9OdqQehSwhEIug4D11Bus
 Fa3bT3FY5OsU7ZbnKELq+eXdp1Q1Dw==
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed;
 d=football.example.com; i=@football.example.com;
 q=dns/txt; s=test; t=1528637909; h=from : to : subject :
 date : message-id : from : subject : date;
 bh=2jUSOH9NhtVGCQWNr9BrIAPreKQjO6Sn7XIkfJVOzv8=;
 b=F45dVWDfMbQDGHJFlXUNB2HKfbCeLRyhDXgFpEL8GwpsRe0IeIixNTe3
 DhCVlUrSjV4BwcVcOF6+FF3Zo9Rpo1tFOeS9mPYQTnGdaSGsgeefOsk2Jz
 dA+L10TeYt9BgDfQNZtKdN1WO//KgIqXP7OdEFE4LjFYNcUxZQ4FADY+8=
From: Joe SixPack <joe@football.example.com>
To: Suzie Q <suzie@shopping.example.net>
Subject: Is dinner ready?
Date: Fri, 11 Jul 2003 21:00:37 -0700 (PDT)
Message-ID: <20030712040037.46341.5F8J@football.example.com>

Hi.

We lost the game.  Are you hungry yet?

Joe.
`)

	expected := &VerifyResult{
		Found: 2,
		Valid: 2,
		Results: []*OneResult{
			{
				SignatureHeader: toCRLF(
					` v=1; a=ed25519-sha256; c=relaxed/relaxed;
 d=football.example.com; i=@football.example.com;
 q=dns/txt; s=brisbane; t=1528637909; h=from : to :
 subject : date : message-id : from : subject : date;
 bh=2jUSOH9NhtVGCQWNr9BrIAPreKQjO6Sn7XIkfJVOzv8=;
 b=/gCrinpcQOoIfuHNQIbq4pgh9kyIK3AQUdt9OdqQehSwhEIug4D11Bus
 Fa3bT3FY5OsU7ZbnKELq+eXdp1Q1Dw==`),
				Domain:   "football.example.com",
				Selector: "brisbane",
				B: "/gCrinpcQOoIfuHNQIbq4pgh9kyIK3AQUdt9OdqQehSwhEIug4D11" +
					"BusFa3bT3FY5OsU7ZbnKELq+eXdp1Q1Dw==",
				State: SUCCESS,
				Error: nil,
			},
			{
				SignatureHeader: toCRLF(
					` v=1; a=rsa-sha256; c=relaxed/relaxed;
 d=football.example.com; i=@football.example.com;
 q=dns/txt; s=test; t=1528637909; h=from : to : subject :
 date : message-id : from : subject : date;
 bh=2jUSOH9NhtVGCQWNr9BrIAPreKQjO6Sn7XIkfJVOzv8=;
 b=F45dVWDfMbQDGHJFlXUNB2HKfbCeLRyhDXgFpEL8GwpsRe0IeIixNTe3
 DhCVlUrSjV4BwcVcOF6+FF3Zo9Rpo1tFOeS9mPYQTnGdaSGsgeefOsk2Jz
 dA+L10TeYt9BgDfQNZtKdN1WO//KgIqXP7OdEFE4LjFYNcUxZQ4FADY+8=`),
				Domain:   "football.example.com",
				Selector: "test",
				B: "F45dVWDfMbQDGHJFlXUNB2HKfbCeLRyhDXgFpEL8GwpsRe0IeIixNTe" +
					"3DhCVlUrSjV4BwcVcOF6+FF3Zo9Rpo1tFOeS9mPYQTnGdaSGsgeefO" +
					"sk2JzdA+L10TeYt9BgDfQNZtKdN1WO//KgIqXP7OdEFE4LjFYNcUxZ" +
					"Q4FADY+8=",
				State: SUCCESS,
				Error: nil,
			},
		},
	}

	res, err := VerifyMessage(ctx, message)
	if err != nil {
		t.Fatalf("VerifyMessage returned error: %v", err)
	}
	if diff := cmp.Diff(expected, res); diff != "" {
		t.Errorf("VerifyMessage diff (-want +got):\n%s", diff)
	}

	// Extend the message, check it does not pass validation.
	res, err = VerifyMessage(ctx, message+"Extra line.\r\n")
	if res.Found != 2 || res.Valid != 0 || err != nil {
		t.Errorf("VerifyMessage: wanted 2 found, 0 valid / nil; got %v / %v",
			res, err)
	}

	// Alter a header, check it does not pass validation.
	res, err = VerifyMessage(ctx,
		strings.Replace(message, "Subject", "X-Subject", 1))
	if res.Found != 2 || res.Valid != 0 || err != nil {
		t.Errorf("VerifyMessage: wanted 2 found, 0 valid / nil; got %v / %v",
			res, err)
	}
}

func TestVerifyBodyLength(t *testing.T) {
	ctx := t.Context()
	ctx = WithTraceFunc(ctx, t.Logf)

	// Any valid key works, since none of the signatures here are valid. We
	// use the one from the example in RFC 8463 appendix A.2.
	ctx = WithLookupTXTFunc(ctx, makeLookupTXT(map[string][]string{
		"brisbane._domainkey.example.com": {
			"v=DKIM1; k=ed25519; " +
				"p=11qYAYKxCrfVS/7TyWQHOg7hcvPapiMlrwIaaPcHURo="},
	}))

	// Use a valid body hash (of the "signed" part of the body), so we can
	// tell the l= cases apart: when l= covers exactly the signed part, the
	// body hash matches and we fail later on (because b= is bogus).
	body := "Hi.\r\n"

	cases := []struct {
		l      string
		signed string
		want   error
	}{
		{"0", "", ErrVerificationFailed},
		{"0", body, ErrBodyHashMismatch},
		{"4", body, ErrBodyHashMismatch},
		{"5", body, ErrVerificationFailed},
		{"6", body, errInvalidTag},
		{"18446744073709551615", body, errInvalidTag},
	}
	for _, c := range cases {
		bh := base64.StdEncoding.EncodeToString(
			hashWith(crypto.SHA256, []byte(c.signed)))
		message := toCRLF(
			"DKIM-Signature: v=1; a=ed25519-sha256; c=simple/simple;\n"+
				" d=example.com; s=brisbane; h=from; l="+c.l+";\n"+
				" bh="+bh+"; b=AAAA\n"+
				"From: Joe SixPack <joe@example.com>\n"+
				"\n") + body

		res, err := VerifyMessage(ctx, message)
		if err != nil {
			t.Fatalf("l=%s signed=%q: VerifyMessage returned error: %v",
				c.l, c.signed, err)
		}
		if res.Found != 1 || res.Valid != 0 {
			t.Fatalf("l=%s signed=%q: wanted 1 found, 0 valid; got %v",
				c.l, c.signed, res)
		}
		r := res.Results[0]
		if r.State != PERMFAIL || !errors.Is(r.Error, c.want) {
			t.Errorf("l=%s signed=%q: wanted PERMFAIL / %v; got %v / %v",
				c.l, c.signed, c.want, r.State, r.Error)
		}
	}
}

func TestVerifyInvalidDomain(t *testing.T) {
	ctx := t.Context()
	ctx = WithTraceFunc(ctx, t.Logf)
	ctx = WithLookupTXTFunc(ctx, makeLookupTXT(map[string][]string{}))

	// A d= tag that is not a valid domain must be rejected, and must not
	// make it to the Authentication-Results header, where it could inject
	// content.
	message := toCRLF(
		"DKIM-Signature: v=1; a=ed25519-sha256; c=simple/simple;\n" +
			" d=example.com dkim=pass header.d=example.net; s=sel;\n" +
			" h=from; bh=AAAA; b=AAAA\n" +
			"From: Joe SixPack <joe@example.com>\n" +
			"\n" +
			"Hi.\n")

	res, err := VerifyMessage(ctx, message)
	if err != nil {
		t.Fatalf("VerifyMessage returned error: %v", err)
	}
	if res.Found != 1 || res.Valid != 0 {
		t.Fatalf("wanted 1 found, 0 valid; got %v", res)
	}
	r := res.Results[0]
	if r.State != PERMFAIL || !errors.Is(r.Error, errInvalidTag) {
		t.Errorf("wanted PERMFAIL / %v; got %v / %v",
			errInvalidTag, r.State, r.Error)
	}

	ar := res.AuthenticationResults()
	if strings.Contains(ar, "example.net") {
		t.Errorf("Authentication-Results contains the invalid d=: %q", ar)
	}
}

func TestBTag(t *testing.T) {
	// Test that we remove the value of the b= tag (and only that) from the
	// canonicalized DKIM-Signature header.
	// The expected values match what Mail::DKIM does (except for the cases
	// without a b= tag, where it appends one).
	cases := []struct {
		in, want string
	}{
		// Relaxed canonicalization, b= in different positions.
		{"dkim-signature:v=1; bh=AAAA; b=SIG",
			"dkim-signature:v=1; bh=AAAA; b="},
		{"dkim-signature:v=1; bh=AAAA; b=SIG;",
			"dkim-signature:v=1; bh=AAAA; b=;"},
		{"dkim-signature:b=SIG; v=1",
			"dkim-signature:b=; v=1"},
		{"dkim-signature:v=1; b=SIG; bh=AAAA; a=ed25519-sha256",
			"dkim-signature:v=1; b=; bh=AAAA; a=ed25519-sha256"},

		// Simple canonicalization: the header name is unchanged, and
		// whitespace (including folding) is preserved.
		{"DKIM-Signature: b=SIG; v=1",
			"DKIM-Signature: b=; v=1"},
		{"DKIM-Signature: v=1;\r\n\tb=SIG1\r\n\t SIG2;\r\n\tbh=AAAA",
			"DKIM-Signature: v=1;\r\n\tb=;\r\n\tbh=AAAA"},
		{"DKIM-Signature: v=1;\r\n\t b=SIG",
			"DKIM-Signature: v=1;\r\n\t b="},
		{"DKIM-Signature: v=1;\r\n b\r\n =\r\n SIG\r\n ;",
			"DKIM-Signature: v=1;\r\n b\r\n =;"},

		// Whitespace around and inside the value is removed.
		{"dkim-signature:v=1; b = SI G ;",
			"dkim-signature:v=1; b =;"},

		// Empty b= tag.
		{"dkim-signature:v=1; b=; bh=AAAA",
			"dkim-signature:v=1; b=; bh=AAAA"},
		{"dkim-signature:v=1; b=",
			"dkim-signature:v=1; b="},

		// The whole value is removed, even if it's not valid base64.
		{"dkim-signature:v=1; b=SI!G; x=1",
			"dkim-signature:v=1; b=; x=1"},

		// Degenerate folding, with a ':' at the beginning of a continuation
		// line.
		{"DKIM-Signature: v=1; h=from:to\r\n\t:subject;\r\n\tb=SIG",
			"DKIM-Signature: v=1; h=from:to\r\n\t:subject;\r\n\tb="},

		// Tags and values that contain "b=" but are not the b= tag must be
		// left alone.
		{"dkim-signature:v=1; bh=AAAA",
			"dkim-signature:v=1; bh=AAAA"},
		{"dkim-signature:v=1; bh=AAb=; b=SIG",
			"dkim-signature:v=1; bh=AAb=; b="},
		{"dkim-signature:v=1; xb=1; b=SIG",
			"dkim-signature:v=1; xb=1; b="},
		{"dkim-signature:v=1; x=b=1; b=SIG",
			"dkim-signature:v=1; x=b=1; b="},
		{"dkim-signature:v=1; x=y b=1; b=SIG",
			"dkim-signature:v=1; x=y b=1; b="},
		{"dkim-signature:v=1; z=Subject:Is=20the=20club=20open?; b=SIG",
			"dkim-signature:v=1; z=Subject:Is=20the=20club=20open?; b="},
		{"dkim-signature:z=Subject:b=20x; b=SIG",
			"dkim-signature:z=Subject:b=20x; b="},
		{"dkim-signature:v=1; i=bob=2B@example.com; b=SIG",
			"dkim-signature:v=1; i=bob=2B@example.com; b="},
		{"dkim-signature:v=1; xb=1; z=a:b=20",
			"dkim-signature:v=1; xb=1; z=a:b=20"},

		// Tag names are case-sensitive.
		{"dkim-signature:v=1; B=SIG; b=SIG",
			"dkim-signature:v=1; B=SIG; b="},
	}

	for _, c := range cases {
		got := bTag.ReplaceAllString(c.in, "$1$2")
		if got != c.want {
			t.Errorf("bTag replace on %q:", c.in)
			t.Errorf("      want %q", c.want)
			t.Errorf("      got  %q", got)
		}

		// Cross-check against the tag parser: the result must have the
		// same tags as the input, with only b= (if present) emptied.
		_, inV, _ := strings.Cut(c.in, ":")
		_, gotV, _ := strings.Cut(got, ":")
		inTags, err := parseTags(inV)
		if err != nil {
			t.Fatalf("parseTags(%q) error: %v", inV, err)
		}
		gotTags, err := parseTags(gotV)
		if err != nil {
			t.Fatalf("parseTags(%q) error: %v", gotV, err)
		}
		if _, ok := inTags["b"]; ok {
			inTags["b"] = ""
		}
		if diff := cmp.Diff(inTags, gotTags); diff != "" {
			t.Errorf("bTag replace on %q: tags diff (-want +got):\n%s",
				c.in, diff)
		}
	}
}

func TestHeadersToInclude(t *testing.T) {
	// Test that headersToInclude returns the expected headers.
	cases := []struct {
		sigH    header
		hTag    []string
		headers headers
		want    []header
	}{
		// Check that if a header appears more than once, we pick the latest
		// first.
		{
			sigH: header{
				Name:  "DKIM-Signature",
				Value: "v=1; a=rsa-sha256; s=brisbane; d=example.com;",
			},
			hTag: []string{"From", "To", "Subject"},
			headers: headers{
				{Name: "From", Value: "from1"},
				{Name: "To", Value: "to1"},
				{Name: "Subject", Value: "subject1"},
				{Name: "From", Value: "from2"},
			},
			want: []header{
				{Name: "From", Value: "from2"},
				{Name: "To", Value: "to1"},
				{Name: "Subject", Value: "subject1"},
			},
		},

		// Check that if a header is requested twice but only appears once, we
		// only return it once.
		// This is a common technique suggested by the RFC to make signatures
		// fail if a header is added.
		{
			sigH: header{
				Name:  "DKIM-Signature",
				Value: "v=1; a=rsa-sha256; s=brisbane; d=example.com;",
			},
			hTag: []string{"From", "From", "To", "Subject"},
			headers: headers{
				{Name: "From", Value: "from1"},
				{Name: "To", Value: "to1"},
				{Name: "Subject", Value: "subject1"},
			},
			want: []header{
				{Name: "From", Value: "from1"},
				{Name: "To", Value: "to1"},
				{Name: "Subject", Value: "subject1"},
			},
		},

		// Check that if DKIM-Signature is included, we do *not* include the
		// one we're currently verifying in the headers to include.
		// https://datatracker.ietf.org/doc/html/rfc6376#section-3.7
		{
			sigH: header{
				Name:  "DKIM-Signature",
				Value: "v=1; a=rsa-sha256; s=brisbane; d=example.com;",
			},
			hTag: []string{"From", "From", "DKIM-Signature", "DKIM-Signature"},
			headers: headers{
				{Name: "From", Value: "from1"},
				{Name: "To", Value: "to1"},
				{
					Name:  "DKIM-Signature",
					Value: "v=1; a=rsa-sha256; s=sidney; d=example.com;",
				},
				{
					Name:  "DKIM-Signature",
					Value: "v=1; a=rsa-sha256; s=brisbane; d=example.com;",
				},
			},
			want: []header{
				{Name: "From", Value: "from1"},
				{
					Name:  "DKIM-Signature",
					Value: "v=1; a=rsa-sha256; s=sidney; d=example.com;",
				},
			},
		},

		// Check that header names are compared case-insensitively, and that
		// headers that are not present are skipped.
		{
			sigH: header{
				Name:  "DKIM-Signature",
				Value: "v=1; a=rsa-sha256; s=brisbane; d=example.com;",
			},
			hTag: []string{"from", "X-Missing", "FROM", "subject"},
			headers: headers{
				{Name: "FROM", Value: "from1"},
				{Name: "Subject", Value: "subject1"},
				{Name: "From", Value: "from2"},
			},
			want: []header{
				{Name: "From", Value: "from2"},
				{Name: "FROM", Value: "from1"},
				{Name: "Subject", Value: "subject1"},
			},
		},
	}

	for _, c := range cases {
		got := headersToInclude(c.sigH, c.hTag, c.headers)
		if diff := cmp.Diff(c.want, got); diff != "" {
			t.Errorf("headersToInclude(%q, %v, %v) diff (-want +got):\n%s",
				c.sigH, c.hTag, c.headers, diff)
		}
	}
}

func TestHeadersToIncludeLarge(t *testing.T) {
	// Regression test for a DoS where headersToInclude was O(len(h=) *
	// len(headers)), which with large (attacker-controlled) inputs could take
	// hours. This takes milliseconds, while the quadratic implementation
	// took minutes with this input. We don't check the timing, so a
	// regression will show up as this test being very slow.
	const n = 100_000

	sigH := header{Name: "DKIM-Signature", Value: "v=1;"}
	hTag := make([]string, n)
	hdrs := make(headers, n)
	for i := range n {
		hTag[i] = "a"
		hdrs[i] = header{Name: "a", Value: fmt.Sprint(i)}
	}

	got := headersToInclude(sigH, hTag, hdrs)
	if len(got) != n {
		t.Fatalf("wanted %d headers, got %d", n, len(got))
	}
	// Last instance first.
	if got[0].Value != fmt.Sprint(n-1) || got[n-1].Value != "0" {
		t.Errorf("unexpected order: first %q, last %q",
			got[0].Value, got[n-1].Value)
	}
}

func TestAuthenticationResults(t *testing.T) {
	resBrisbane := &OneResult{
		Domain:   "football.example.com",
		Selector: "brisbane",
		B: "/gCrinpcQOoIfuHNQIbq4pgh9kyIK3AQUdt9OdqQehSwhEIug4D11" +
			"BusFa3bT3FY5OsU7ZbnKELq+eXdp1Q1Dw==",
		State: SUCCESS,
		Error: nil,
	}
	resTest := &OneResult{
		Domain:   "football.example.com",
		Selector: "test",
		B: "F45dVWDfMbQDGHJFlXUNB2HKfbCeLRyhDXgFpEL8GwpsRe0IeIixNTe" +
			"3DhCVlUrSjV4BwcVcOF6+FF3Zo9Rpo1tFOeS9mPYQTnGdaSGsgeefO" +
			"sk2JzdA+L10TeYt9BgDfQNZtKdN1WO//KgIqXP7OdEFE4LjFYNcUxZ" +
			"Q4FADY+8=",
		State: SUCCESS,
		Error: nil,
	}
	resFail := &OneResult{
		Domain:   "football.example.com",
		Selector: "paris",
		B:        "slfkdMSDFeslif39seFfjl93sljisdsdlif923l",
		State:    PERMFAIL,
		Error:    ErrVerificationFailed,
	}
	resPermFail := &OneResult{
		Domain:   "football.example.com",
		Selector: "paris",
		// No B tag on purpose.
		State: PERMFAIL,
		Error: errMissingRequiredTag,
	}
	resTempFail := &OneResult{
		Domain:   "football.example.com",
		Selector: "paris",
		B:        "shorty", // Less than 12 characters to check we include it well.
		State:    TEMPFAIL,
		Error: &net.DNSError{
			Err:         "dns temp error (for testing)",
			IsTemporary: true,
		},
	}

	cases := []struct {
		results *VerifyResult
		want    string
	}{
		{
			results: &VerifyResult{},
			want:    ";dkim=none\r\n",
		},
		{
			results: &VerifyResult{
				Found:   1,
				Valid:   1,
				Results: []*OneResult{resBrisbane},
			},
			want: ";dkim=pass" +
				"  header.b=/gCrinpcQOoI  header.d=football.example.com\r\n",
		},
		{
			results: &VerifyResult{
				Found:   2,
				Valid:   2,
				Results: []*OneResult{resBrisbane, resTest},
			},
			want: ";dkim=pass" +
				"  header.b=/gCrinpcQOoI  header.d=football.example.com\r\n" +
				";dkim=pass" +
				"  header.b=F45dVWDfMbQD  header.d=football.example.com\r\n",
		},
		{
			results: &VerifyResult{
				Found:   2,
				Valid:   2,
				Results: []*OneResult{resBrisbane, resTest},
			},
			want: ";dkim=pass" +
				"  header.b=/gCrinpcQOoI  header.d=football.example.com\r\n" +
				";dkim=pass" +
				"  header.b=F45dVWDfMbQD  header.d=football.example.com\r\n",
		},
		{
			results: &VerifyResult{
				Found:   2,
				Valid:   1,
				Results: []*OneResult{resFail, resTest},
			},
			want: ";dkim=fail  reason=\"verification failed\"\r\n" +
				"  header.b=slfkdMSDFesl  header.d=football.example.com\r\n" +
				";dkim=pass" +
				"  header.b=F45dVWDfMbQD  header.d=football.example.com\r\n",
		},
		{
			results: &VerifyResult{
				Found:   1,
				Results: []*OneResult{resPermFail},
			},
			want: ";dkim=permerror  reason=\"missing required tag\"\r\n" +
				"  header.d=football.example.com\r\n",
		},
		{
			results: &VerifyResult{
				Found:   1,
				Results: []*OneResult{resTempFail},
			},
			want: ";dkim=temperror  reason=\"lookup : dns temp error (for testing)\"\r\n" +
				"  header.b=shorty  header.d=football.example.com\r\n",
		},
	}

	for i, c := range cases {
		got := c.results.AuthenticationResults()
		if diff := cmp.Diff(c.want, got); diff != "" {
			t.Errorf("case %d: AuthenticationResults() diff (-want +got):\n%s",
				i, diff)
		}
	}
}

func FuzzVerifyMessage(f *testing.F) {
	addTestdataCorpus(f)

	// Return valid keys for every domain, so we can get past the key lookup
	// and exercise the rest of the verification. The ed25519 key is the one
	// used by testdata/01-rfc8463.
	ctx := WithLookupTXTFunc(context.Background(),
		func(ctx context.Context, domain string) ([]string, error) {
			return []string{
				"v=DKIM1; k=ed25519; p=" + exampleEd25519KeyB64,
				"v=DKIM1; k=rsa; p=" + exampleRSAKeyB64,
			}, nil
		})

	f.Fuzz(func(t *testing.T, msg string) {
		res, err := VerifyMessage(ctx, msg)
		if err != nil {
			return
		}

		if res.Found != uint(len(res.Results)) {
			t.Errorf("found %d signatures, but got %d results",
				res.Found, len(res.Results))
		}
		if res.Valid > res.Found {
			t.Errorf("%d valid signatures, but only %d found",
				res.Valid, res.Found)
		}

		// This is always called on the result when receiving a message, so
		// exercise it too.
		res.AuthenticationResults()
	})
}