diff --git a/internal/subtle/xor.go b/internal/subtle/xor.go index a8805ac..93f1e7a 100644 --- a/internal/subtle/xor.go +++ b/internal/subtle/xor.go @@ -4,10 +4,15 @@ package subtle +import "github.com/emmansun/gmsm/internal/alias" + // XORBytes sets dst[i] = x[i] ^ y[i] for all i < n = min(len(x), len(y)), // returning n, the number of bytes written to dst. // If dst does not have length at least n, // XORBytes panics without writing anything to dst. +// +// dst and x or y may overlap exactly or not at all, +// otherwise XORBytes may panic. func XORBytes(dst, x, y []byte) int { n := len(x) if len(y) < n { @@ -19,6 +24,9 @@ func XORBytes(dst, x, y []byte) int { if n > len(dst) { panic("subtle.XORBytes: dst too short") } + if alias.InexactOverlap(dst[:n], x[:n]) || alias.InexactOverlap(dst[:n], y[:n]) { + panic("subtle.XORBytes: invalid overlap") + } xorBytes(&dst[0], &x[0], &y[0], n) // arch-specific return n } diff --git a/internal/subtle/xor_test.go b/internal/subtle/xor_test.go index aa98c88..b98b3a4 100644 --- a/internal/subtle/xor_test.go +++ b/internal/subtle/xor_test.go @@ -58,6 +58,14 @@ func TestXorBytesPanic(t *testing.T) { mustPanic(t, "subtle.XORBytes: dst too short", func() { subtle.XORBytes(make([]byte, 1), make([]byte, 2), make([]byte, 3)) }) + mustPanic(t, "subtle.XORBytes: invalid overlap", func() { + x := make([]byte, 3) + subtle.XORBytes(x, x[1:], make([]byte, 2)) + }) + mustPanic(t, "subtle.XORBytes: invalid overlap", func() { + x := make([]byte, 3) + subtle.XORBytes(x, make([]byte, 2), x[1:]) + }) } func BenchmarkXORBytes(b *testing.B) {