Hungming Chen | ed7b460 | 2021-12-17 15:03:47 +0800 | [diff] [blame] | 1 | // Copyright (C) 2022 The Android Open Source Project |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | #include "libclat/clatutils.h" |
| 16 | |
| 17 | #include <stdlib.h> |
| 18 | |
| 19 | extern "C" { |
| 20 | #include "checksum.h" |
| 21 | } |
| 22 | |
| 23 | namespace android { |
| 24 | namespace net { |
| 25 | namespace clat { |
| 26 | |
| 27 | // Alters the bits in the IPv6 address to make them checksum neutral with v4 and nat64Prefix. |
| 28 | void makeChecksumNeutral(in6_addr* v6, const in_addr v4, const in6_addr& nat64Prefix) { |
| 29 | // Fill last 8 bytes of IPv6 address with random bits. |
| 30 | arc4random_buf(&v6->s6_addr[8], 8); |
| 31 | |
| 32 | // Make the IID checksum-neutral. That is, make it so that: |
| 33 | // checksum(Local IPv4 | Remote IPv4) = checksum(Local IPv6 | Remote IPv6) |
| 34 | // in other words (because remote IPv6 = NAT64 prefix | Remote IPv4): |
| 35 | // checksum(Local IPv4) = checksum(Local IPv6 | NAT64 prefix) |
| 36 | // Do this by adjusting the two bytes in the middle of the IID. |
| 37 | |
| 38 | uint16_t middlebytes = (v6->s6_addr[11] << 8) + v6->s6_addr[12]; |
| 39 | |
| 40 | uint32_t c1 = ip_checksum_add(0, &v4, sizeof(v4)); |
| 41 | uint32_t c2 = ip_checksum_add(0, &nat64Prefix, sizeof(nat64Prefix)) + |
| 42 | ip_checksum_add(0, v6, sizeof(*v6)); |
| 43 | |
| 44 | uint16_t delta = ip_checksum_adjust(middlebytes, c1, c2); |
| 45 | v6->s6_addr[11] = delta >> 8; |
| 46 | v6->s6_addr[12] = delta & 0xff; |
| 47 | } |
| 48 | |
| 49 | } // namespace clat |
| 50 | } // namespace net |
| 51 | } // namespace android |