Skip to content

Commit

Permalink
fixed bodyhash missmatch issue in relax mode described in issue emers…
Browse files Browse the repository at this point in the history
  • Loading branch information
mschneider82 committed Nov 20, 2020
1 parent 7247d5f commit 82b7147
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 3 deletions.
9 changes: 6 additions & 3 deletions dkim/canonical.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,15 @@ var canonicalizers = map[Canonicalization]canonicalizer{
}

// Fix any \n without a matching \r
func fixCRLF(b []byte) []byte {
func fixCRLF(b []byte, isRelaxed bool) []byte {
res := make([]byte, 0, len(b))
for i := range b {
if b[i] == '\n' && (i == 0 || b[i-1] != '\r') {
res = append(res, '\r')
}
if isRelaxed && i == len(b)-1 && b[i] == '\r' {
break
}
res = append(res, b[i])
}
return res
Expand All @@ -53,7 +56,7 @@ func (c *simpleBodyCanonicalizer) Write(b []byte) (int, error) {
written := len(b)
b = append(c.crlfBuf, b...)

b = fixCRLF(b)
b = fixCRLF(b, false)

end := len(b)
// If it ends with \r, maybe the next write will begin with \n
Expand Down Expand Up @@ -125,7 +128,7 @@ type relaxedBodyCanonicalizer struct {
func (c *relaxedBodyCanonicalizer) Write(b []byte) (int, error) {
written := len(b)

b = fixCRLF(b)
b = fixCRLF(b, true)

canonical := make([]byte, 0, len(b))
for _, ch := range b {
Expand Down
31 changes: 31 additions & 0 deletions dkim/canonical_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package dkim

import (
"bytes"
"reflect"
"testing"
)

Expand Down Expand Up @@ -168,3 +169,33 @@ func TestRelaxedCanonicalizer_CanonicalBody(t *testing.T) {
}
}
}

func Test_fixCRLF(t *testing.T) {

tests := []struct {
name string
got string
want string
isRelaxed bool
}{
{
name: "t1",
got: "test\r\ntest\r\ntest\r\ntest\r\ntest\r\ntest\r\ntest\r\ntest\r\ntest\r",
want: "test\r\ntest\r\ntest\r\ntest\r\ntest\r\ntest\r\ntest\r\ntest\r\ntest",
isRelaxed: true,
},
{
name: "t2",
got: "test\r\ntest\r\ntest\r\ntest\r\ntest\r\ntest\r\ntest\r\ntest\r\ntest\r",
want: "test\r\ntest\r\ntest\r\ntest\r\ntest\r\ntest\r\ntest\r\ntest\r\ntest\r",
isRelaxed: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := fixCRLF([]byte(tt.got), tt.isRelaxed); !reflect.DeepEqual(got, []byte(tt.want)) {
t.Errorf("Expected fixCRLF for body %q to be %q, but got %q", []byte(tt.got), []byte(tt.want), got)
}
})
}
}

0 comments on commit 82b7147

Please sign in to comment.