Add some missing carries to the SSE2 poly1305 implementation

In investigating https://crbug.com/590064899, we found that there were
some missing carries here too:

- When precomputing r^2 and r^4, the second carry chain stopped too
  early. It then needs a third reduce+carry to be fully tight. This
  seems to be unnecessary, but the performance difference seems to be
  negligible, so target the simpler bounds. (Also for the AEAD, we have
  a faster stitched SSE4.1 implementation anyway.)

  The robot also believes the carry chain cannot actually reach r21 in
  the final loop around due to where the quadratic residues mod p are
  and Poly1305's clamping, which is why there is no test case for it,
  but I did not confirm this.

- When combining even/odd blocks, the carry chain again stopped too
  early.

The final reduction also had a similar missing carry to
https://crbug.com/590064899, but this seems to have been benign. g and
thus the select mask are computed correctly, and the final addition
tolerates a slightly loose input. Still, target simpler bounds since
it's just a handful of cycles at the end.

Some of these test vectors could be applied at the AEAD level, while
others cannot because they depend on cooking r and s, but those are
derived on the fly per AEAD call.

We don't believe this has security consequences. The first requires a
vanishingly small set of keys, which aren't under attacker control. The
second issue is like https://crbug.com/590064899 in that it impacts a
vanishingly small set of cases, randomized by a key outside attacker
control, and even when we hit those cases, we effectively only lose some
bits of the MAC.

Bug: 590064899
Change-Id: I9ca4d654a8dd0339875b0cfb697952000661d3e6
Reviewed-on: https://boringssl-review.googlesource.com/c/boringssl/+/106768
Presubmit-BoringSSL-Verified: boringssl-scoped@luci-project-accounts.iam.gserviceaccount.com <boringssl-scoped@luci-project-accounts.iam.gserviceaccount.com>
Commit-Queue: Lily Chen <chlily@google.com>
Auto-Submit: David Benjamin <davidben@google.com>
Reviewed-by: Lily Chen <chlily@google.com>
diff --git a/crypto/cipher/test/chacha20_poly1305_tests.txt b/crypto/cipher/test/chacha20_poly1305_tests.txt
index 0529f7d..578a726 100644
--- a/crypto/cipher/test/chacha20_poly1305_tests.txt
+++ b/crypto/cipher/test/chacha20_poly1305_tests.txt
@@ -574,10 +574,45 @@
 CT: b5cc754f6dd19ef2d66f90e6bc9a322ddf216ef248cbe76b5ab6dd53bc36
 TAG: d3f7b9c295f374651a84138648a591
 
-# Regression test for https://crbug.com/590064899
+# An input that needs a longer final carry chain in a 26-bit representation.
+# This is a regression test for https://crbug.com/590064899
 KEY: 0000000000000000000000000000000000000000000000000000000000000000
 NONCE: 000000000000000000000000
 IN: 03052a6a2cb1347e6872c8b9481459fd
 AD: ""
 CT: 9c02cdd479e00c04f0c85fc53b3951f0
 TAG: bdd219c0a08ded1aa836efcc8b770dc7
+
+# Same carry case for a 44-bit representation.
+KEY: 0000000000000000000000000000000000000000000000000000000000000000
+NONCE: 000000000000000000000000
+IN: 1144f543bb2460ede7c8c5758a380e20
+AD: ""
+CT: 8e4312fdee7558977f725209f915062d
+TAG: c1d219b8a0aded1aa836efcc8b770dc7
+
+# If separating even/odd blocks, a 26-bit carry from t1 into t2 when combining.
+KEY: 0000000000000000000000000000000000000000000000000000000000000000
+NONCE: 000000000000000000000000
+IN: f44405ff6cac5003a40afb1dd4674947d63a48624317e998bcb9e3128510c03d
+AD: ""
+CT: 6b43e24139fd68793cb06c61a74a414a1d3561c20bf48cf1ae7fb02cb7febad0
+TAG: c50515d6461c9188106b76d96fb4aea4
+
+# If separating even/odd blocks, a 26-bit carry cascade from t1 through t4 when
+# combining.
+KEY: 0000000000000000000000000000000000000000000000000000000000000000
+NONCE: 000000000000000000000000
+IN: d6a4327106265fe1553e67862098e57551b107e9c1ac43b75b9d72a5e7f2fd63
+AD: ""
+CT: 49a3d5cf5377679bcd84f0fa53b5ed789abe2e49894f26de495b219bd51c878e
+TAG: 715bed3c2a18c10207029b69877f299b
+
+# If separating even/odd blocks, a 26-bit carry cascade from t1 through t4 back
+# to t0 when combining.
+KEY: 0000000000000000000000000000000000000000000000000000000000000000
+NONCE: 000000000000000000000000
+IN: baf9efa55cc99c8fb44996cab70d71f697523e2252e900fdf3796ea2b23e4e4c
+AD: ""
+CT: 25fe081b0998a4f52cf301b6c42079fb5c5d17821a0a6594e1bf3d9c80d034a1
+TAG: 885636038a93897ab9c6b3b5a13fe716
diff --git a/crypto/poly1305/poly1305_tests.txt b/crypto/poly1305/poly1305_tests.txt
index 311cb23..fb02ce5 100644
--- a/crypto/poly1305/poly1305_tests.txt
+++ b/crypto/poly1305/poly1305_tests.txt
@@ -163,3 +163,55 @@
 Key = feffff0300000000000000000000000000000000000000000000000000000000
 Input = af97d05e2fa1bd5e427bbd84f67a09ed
 MAC = 04000008000000000000000000000000
+
+# Same carry case with a pad wrapping across 128-bit boundaries.
+Key = feffff03000000000000000000000000ffffffffffffffffffffffffffffffff
+Input = af97d05e2fa1bd5e427bbd84f67a09ed
+MAC = 03000008000000000000000000000000
+
+# Same carry case for a 44-bit representation.
+Key = ffffff0ffc0f0000000000000000000000000000000000000000000000000000
+Input = 37209c082eba1c8074c331136756a340
+MAC = 04000000001000000000000000000000
+
+# If separating even/odd blocks, a 26-bit carry from t1 into t2 when combining.
+Key = 010f0e0d0c0b0a09080706050403020100000000000000000000000000000000
+Input = 02103173cb30555af54e8999bb8757e45cddd9957041fc3ac71d0484e4439c8700
+MAC = f405e8ba8d60530eebc5a07b56310ce7
+
+# If separating even/odd blocks, a 26-bit carry cascade from t1 through t4 when
+# combining.
+Key = 0200000000000000000000000000000000000000000000000000000000000000
+Input = 00000000000000000000000000010000fdffffffffffffffffffffffffffffff00
+MAC = 08020000000000000000000000080000
+
+# If separating even/odd blocks, a 26-bit carry cascade from t1 through t4 back
+# to t0 when combining.
+Key = 0200000000000000000000000000000000000000000000000000000000000000
+Input = ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00
+MAC = 12020000000000000000000000000000
+
+# r^2 precomputation with 44-bit radix carries up to t2 (33-byte and 97-byte
+# inputs).
+Key = 450000000030d70eccb583000000000000000000000000000000000000000000
+Input = 000000000000000000000000000000000000000000000000000000000000000000
+MAC = b1c885a2ae6a5edad5bd7c61fa221f71
+
+Key = 450000000030d70eccb583000000000000000000000000000000000000000000
+Input = 00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
+MAC = 6576de330b1ef0eeadb8651971b4c2f5
+
+# r^2 precomputation with 44-bit radix cascades carries up to t2 and back into
+# t0 (33-byte and 97-byte inputs).
+Key = aacff5008ceb1106f8e478081cbaa40d00000000000000000000000000000000
+Input = 000000000000000000000000000000000000000000000000000000000000000000
+MAC = 69532dc9a5882b42a391fba871efa427
+
+Key = aacff5008ceb1106f8e478081cbaa40d00000000000000000000000000000000
+Input = 00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
+MAC = fe5c04d09c863b11f5a556d1d9cc8427
+
+# Empty input.
+Key = 85d6be7857556d337f4452fe42d506a80103808afb0db2fd4abff6af4149f51b
+Input = ""
+MAC = 0103808afb0db2fd4abff6af4149f51b
diff --git a/crypto/poly1305/poly1305_vec.cc b/crypto/poly1305/poly1305_vec.cc
index c0a5852..8b67f3b 100644
--- a/crypto/poly1305/poly1305_vec.cc
+++ b/crypto/poly1305/poly1305_vec.cc
@@ -20,8 +20,6 @@
 
 #include <openssl/poly1305.h>
 
-#include <assert.h>
-
 #include "../internal.h"
 
 
@@ -29,6 +27,8 @@
 
 #include <emmintrin.h>
 
+#include <algorithm>
+
 
 using namespace bssl;
 
@@ -56,23 +56,48 @@
   return (uint64_t)((((uint128_t)hi << 64) | lo) >> shift);
 }
 
-typedef struct poly1305_power_t {
+// A poly1305_power stores some r^i in a form suitable for vector operations.
+//
+// `R20` through `R24` store r^i with unsaturated radix 2^26 limbs. Each limb is
+// less than 2^26. There are two copies of the value, in each of the two 64-bit
+// lanes, but only the bottom half of each lane is used. (`_mm_mul_epu32`
+// ignores the upper half, so that space is borrowed for other storage below.)
+//
+// `S21` through `S24` cache `5 * R21` through `5 * R24` with no carrying.
+struct poly1305_power {
   union {
     xmmi v;
     uint64_t u[2];
     uint32_t d[4];
   } R20, R21, R22, R23, R24, S21, S22, S23, S24;
-} poly1305_power;
+};
 
 typedef struct poly1305_state_internal_t {
-  poly1305_power P[2]; /* 288 bytes, top 32 bit halves unused = 144
-                          bytes of free storage */
+  // `P`, if `started` is one, stores, in order, r⁴ and r². If `started` is
+  // zero, it is not yet initialized, except for unused space described below.
+  poly1305_power P[2];  // 288 bytes
+  // Before `poly1305_combine`, `H` stores the running total in two halves. Lane
+  // 0 is even blocks and lane 1 is odd blocks. Each half uses unsaturated radix
+  // 2^26 limbs. They are not fully reduced, but each limb is less than 2^27.
+  //
+  // After `poly1305_combine`, `HH[0]` to `HH[2]` store the running total with
+  // unsaturated radix-2^44 limbs. Limbs are tight (44, 44, and 42 bits).
   union {
     xmmi H[5];  //  80 bytes
     uint64_t HH[10];
   };
-  // uint64_t r0,r1,r2;       [24 bytes]
-  // uint64_t pad0,pad1;      [16 bytes]
+  // Conceptually, r and s are stored in the following fields. However, they are
+  // instead stored in the unused bytes of `P` above.
+  //
+  //   uint64_t r0, r1, r2;       [24 bytes]
+  //   uint64_t pad0, pad1;       [16 bytes]
+  //
+  // `r0`'s lower and upper halves are stashed into `P[1].R20.d[1]` and
+  // `P[1].R20.d[3]`. `r1` is stashed into `R21` and so on in order.
+  //
+  // `r0`, `r1`, and `r2` store r with unsaturated radix-2^44 limbs. Limbs are
+  // tight (44, 44, and 42 bits). `pad0` and `pad1` store s with saturated
+  // 64-bit limbs.
   uint64_t started;        //   8 bytes
   uint64_t leftover;       //   8 bytes
   uint8_t buffer[64];      //  64 bytes
@@ -88,8 +113,6 @@
   return reinterpret_cast<poly1305_state_internal *>(align_pointer(state, 64));
 }
 
-size_t poly1305_min(size_t a, size_t b) { return (a < b) ? a : b; }
-
 }  // namespace
 
 void CRYPTO_poly1305_init(poly1305_state *state, const uint8_t key[32]) {
@@ -166,10 +189,13 @@
   for (i = 0; i < 2; i++) {
     s22 = r22 * (5 << 2);
 
+    // Square the previous value.
     d[0] = add128(mul64x64_128(r20, r20), mul64x64_128(r21 * 2, s22));
     d[1] = add128(mul64x64_128(r22, s22), mul64x64_128(r20 * 2, r21));
     d[2] = add128(mul64x64_128(r21, r21), mul64x64_128(r22 * 2, r20));
 
+    // Each term of `d` can be much larger than 2^44. Carry the extra bits to
+    // get back to 44-bit limbs.
     r20 = lo128(d[0]) & 0xfffffffffff;
     c = shr128(d[0], 44);
     d[1] = add128_64(d[1], c);
@@ -178,10 +204,29 @@
     d[2] = add128_64(d[2], c);
     r22 = lo128(d[2]) & 0x3ffffffffff;
     c = shr128(d[2], 42);
+
+    // Reduce down to 130 bits. `r20` may then exceed 44 bits, so carry again.
     r20 += c * 5;
     c = (r20 >> 44);
     r20 = r20 & 0xfffffffffff;
     r21 += c;
+    c = (r21 >> 44);
+    r21 = r21 & 0xfffffffffff;
+    r22 += c;
+
+    // `r22` may be too big, so reduce and carry again. This may be unnecessary.
+    // We seem to accept a looser `r22` (and thus a looser `R24`). Still, target
+    // tight bounds for simplicity.
+    c = (r22 >> 42);
+    r22 = r22 & 0x3ffffffffff;
+    r20 += c * 5;
+    c = (r20 >> 44);
+    r20 = r20 & 0xfffffffffff;
+    r21 += c;
+    // This carry chain can stop at `r21`. If `c` is non-zero, `r21` must have
+    // overflowed in the previous carry chain, making it less than the old `c`,
+    // which is small.
+    declassify_assert(r21 <= 0xfffffffffff);
 
     p->R20.v = _mm_shuffle_epi32(_mm_cvtsi32_si128((uint32_t)(r20) & 0x3ffffff),
                                  _MM_SHUFFLE(1, 0, 1, 0));
@@ -637,6 +682,7 @@
   H3 = _mm_add_epi64(T3, _mm_srli_si128(T3, 8));
   H4 = _mm_add_epi64(T4, _mm_srli_si128(T4, 8));
 
+  // We need minimal limbs, so carry excess bits across each limb.
   t0 = _mm_cvtsi128_si32(H0);
   c = (t0 >> 26);
   t0 &= 0x3ffffff;
@@ -652,10 +698,30 @@
   t4 = _mm_cvtsi128_si32(H4) + c;
   c = (t4 >> 26);
   t4 &= 0x3ffffff;
+
+  // Reduce final carry back into the first limb. t0 may get out of bounds, so
+  // carry again.
   t0 = t0 + (c * 5);
   c = (t0 >> 26);
   t0 &= 0x3ffffff;
   t1 = t1 + c;
+  c = (t1 >> 26);
+  t1 &= 0x3ffffff;
+  t2 += c;
+  c = (t2 >> 26);
+  t2 &= 0x3ffffff;
+  t3 += c;
+  c = (t3 >> 26);
+  t3 &= 0x3ffffff;
+  t4 += c;
+  c = (t4 >> 26);
+  t4 &= 0x3ffffff;
+
+  // Reduce again. This time, `t0` remains in bounds: if `c` is non-zero, `t0`
+  // must have overflowed above, leaving it less than the previous `c * 5`, and
+  // thus unable to overflow here.
+  t0 += c * 5;
+  declassify_assert(t0 <= 0x3ffffff);
 
   st->HH[0] = ((t0) | (t1 << 26)) & UINT64_C(0xfffffffffff);
   st->HH[1] = ((t1 >> 18) | (t2 << 8) | (t3 << 34)) & UINT64_C(0xfffffffffff);
@@ -683,7 +749,7 @@
       m += 32;
       bytes -= 32;
     } else {
-      want = poly1305_min(32 - st->leftover, bytes);
+      want = std::min(32 - st->leftover, uint64_t{bytes});
       OPENSSL_memcpy(st->buffer + st->leftover, m, want);
       bytes -= want;
       m += want;
@@ -699,7 +765,7 @@
 
   // handle leftover
   if (st->leftover) {
-    want = poly1305_min(64 - st->leftover, bytes);
+    want = std::min(64 - st->leftover, uint64_t{bytes});
     OPENSSL_memcpy(st->buffer + st->leftover, m, want);
     bytes -= want;
     m += want;
@@ -809,6 +875,10 @@
   goto poly1305_donna_mul;
 
 poly1305_donna_finish:
+  // At this point, `h1` and `h2` are 44 and 42 bits, but `h0` may be over 44
+  // bits. Carry those bits.
+  declassify_assert(h1 <= 0xfffffffffff);
+  declassify_assert(h2 <= 0x3ffffffffff);
   c = (h0 >> 44);
   h0 &= 0xfffffffffff;
   h1 += c;
@@ -818,6 +888,14 @@
   c = (h2 >> 42);
   h2 &= 0x3ffffffffff;
   h0 += c * 5;
+  // This function still works if `h0` is just above 2^44-1, but target tighter
+  // bounds for simplicity.
+  c = (h0 >> 44);
+  h0 &= 0xfffffffffff;
+  h1 += c;
+  // `h1` must be 44 bits. If `c` is non-zero, `h1` must have overflowed in the
+  // previous carry chain, making it less than the old `c`, which is small.
+  declassify_assert(h1 <= 0xfffffffffff);
 
   g0 = h0 + 5;
   c = (g0 >> 44);