blob: 37d096321ee0834a8b81f56d5f1a40e04585fea4 [file] [log] [blame]
ludi5c81c762017-05-19 13:47:53 -07001/*
2 * Copyright 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 *
16 * xfrm_ctrl_test.cpp - unit tests for xfrm controllers.
17 */
18
19#include <cerrno>
20#include <cinttypes>
21#include <cstdint>
22#include <cstdio>
23#include <cstdlib>
24#include <set>
25#include <vector>
26
27#include <arpa/inet.h>
28#include <fcntl.h>
29#include <gmock/gmock.h>
30#include <ifaddrs.h>
31#include <linux/if.h>
32#include <linux/if_tun.h>
33#include <linux/netfilter/nfnetlink.h>
34#include <linux/netlink.h>
35#include <netdb.h>
36#include <netinet/in.h>
37#include <sys/socket.h>
38#include <sys/types.h>
39
40#include <android-base/macros.h>
41#include <android-base/stringprintf.h>
42#include <android-base/strings.h>
43#include <android-base/unique_fd.h>
44#include <gtest/gtest.h>
45
46#include "NetdConstants.h"
47#include "NetlinkCommands.h"
48#include "Stopwatch.h"
49#include "XfrmController.h"
50#include "android/net/INetd.h"
51#include "android/net/UidRange.h"
52#include "binder/IServiceManager.h"
53#include "netdutils/MockSyscalls.h"
54#include "netdutils/Netlink.h"
55#include "tun_interface.h"
56
57using android::base::unique_fd;
58using android::netdutils::Fd;
59using android::netdutils::MockSyscalls;
60using android::netdutils::Slice;
61using android::netdutils::Status;
62using android::netdutils::StatusOr;
63using android::netdutils::Syscalls;
64
Jonathan Basseri20a17c32017-09-14 17:42:40 -070065using ::testing::_;
ludi5c81c762017-05-19 13:47:53 -070066using ::testing::DoAll;
Jonathan Basserifc3b35f2017-09-14 15:58:16 -070067using ::testing::Invoke;
ludi5c81c762017-05-19 13:47:53 -070068using ::testing::Return;
69using ::testing::SaveArg;
70using ::testing::SetArgPointee;
Jonathan Basseri20a17c32017-09-14 17:42:40 -070071using ::testing::Values;
Jonathan Basserifc3b35f2017-09-14 15:58:16 -070072using ::testing::WithArg;
ludi5c81c762017-05-19 13:47:53 -070073
74/**
Jonathan Basseric6128662017-09-14 17:32:59 -070075 * This gMock action works like SetArgPointee, but for netdutils::Slice.
76 * It sets the memory which is pointed to by the N-th argument with the supplied value.
ludi5c81c762017-05-19 13:47:53 -070077 */
Jonathan Basseric6128662017-09-14 17:32:59 -070078ACTION_TEMPLATE(SetArgSlice, HAS_1_TEMPLATE_PARAMS(int, N), AND_1_VALUE_PARAMS(value)) {
79 Slice orig = ::testing::get<N>(args);
ludi5c81c762017-05-19 13:47:53 -070080 android::netdutils::copy(orig, value);
81}
82
Jonathan Basseric6128662017-09-14 17:32:59 -070083/**
84 * This gMock action works like SaveArg, but is specialized for vector<iovec>.
85 * It copies the memory pointed to by each of the iovecs into a single vector<uint8_t>.
86 *
87 * Flattening the iovec objects cannot be done later, since there is no guarantee that the memory
88 * they point to will still be valid after the mock method returns.
89 */
90ACTION_TEMPLATE(SaveFlattenedIovecs, HAS_1_TEMPLATE_PARAMS(int, N), AND_1_VALUE_PARAMS(resVec)) {
91 const std::vector<iovec>& iovs = ::testing::get<N>(args);
ludi5c81c762017-05-19 13:47:53 -070092
93 for (const iovec& iov : iovs) {
94 resVec->insert(resVec->end(), reinterpret_cast<uint8_t*>(iov.iov_base),
95 reinterpret_cast<uint8_t*>(iov.iov_base) + iov.iov_len);
96 }
97}
98
99namespace android {
100namespace net {
101
102static constexpr int DROID_SPI = 0xD1201D;
103static constexpr size_t KEY_LENGTH = 32;
104static constexpr int NLMSG_DEFAULTSIZE = 8192;
105
Jonathan Basseri20a17c32017-09-14 17:42:40 -0700106static constexpr char LOCALHOST_V4[] = "127.0.0.1";
107static constexpr char LOCALHOST_V6[] = "::1";
108static constexpr char TEST_ADDR_V4[] = "8.8.8.8";
109static constexpr char TEST_ADDR_V6[] = "2001:4860:4860::8888";
110
ludi5c81c762017-05-19 13:47:53 -0700111struct Policy {
112 xfrm_userpolicy_info info;
113 xfrm_user_tmpl tmpl;
114};
115
116struct NetlinkResponse {
117 nlmsghdr hdr;
118 char buf[NLMSG_DEFAULTSIZE];
119};
120
Jonathan Basserid6c08582017-09-14 16:10:56 -0700121void expectAddressEquals(int family, const std::string& expected, const xfrm_address_t& actual) {
122 char actualStr[INET6_ADDRSTRLEN];
123 const char* ret =
124 inet_ntop(family, reinterpret_cast<const void*>(&actual), actualStr, INET6_ADDRSTRLEN);
125 EXPECT_NE(nullptr, ret) << "Unable to convert xfrm_address_t to string";
126 EXPECT_EQ(expected, actualStr);
127}
128
ludi5c81c762017-05-19 13:47:53 -0700129class XfrmControllerTest : public ::testing::Test {
130public:
131 MockSyscalls mockSyscalls;
132
133 void SetUp() override { netdutils::sSyscalls.swap(mockSyscalls); }
134};
135
Jonathan Basseri20a17c32017-09-14 17:42:40 -0700136// Test class allowing IPv4/IPv6 parameterized tests.
137class XfrmControllerParameterizedTest : public XfrmControllerTest,
138 public ::testing::WithParamInterface<int> {};
ludi5c81c762017-05-19 13:47:53 -0700139
Jonathan Basseri20a17c32017-09-14 17:42:40 -0700140// Helper to make generated test names readable.
141std::string FamilyName(::testing::TestParamInfo<int> info) {
142 return (info.param == AF_INET) ? "AF_INET" : "AF_INET6";
ludi5c81c762017-05-19 13:47:53 -0700143}
144
Jonathan Basseri20a17c32017-09-14 17:42:40 -0700145// The TEST_P cases below will run with each of the following value parameters.
146INSTANTIATE_TEST_CASE_P(ByFamily, XfrmControllerParameterizedTest, Values(AF_INET, AF_INET6),
147 FamilyName);
148
149TEST_P(XfrmControllerParameterizedTest, TestIpSecAllocateSpi) {
150 const int family = GetParam();
151 const std::string localAddr = (family == AF_INET6) ? LOCALHOST_V6 : LOCALHOST_V4;
152 const std::string remoteAddr = (family == AF_INET6) ? TEST_ADDR_V6 : TEST_ADDR_V4;
ludi5c81c762017-05-19 13:47:53 -0700153 int outSpi = 0;
154 XfrmController ctrl;
155
156 NetlinkResponse response = {};
157 response.hdr.nlmsg_type = XFRM_MSG_ALLOCSPI;
158
159 /** It's an injected return result for the sendMessage function to go through */
160 StatusOr<Slice> readStatus(netdutils::makeSlice(response));
161
162 size_t expectMsgLength = NLMSG_HDRLEN + NLMSG_ALIGN(sizeof(xfrm_userspi_info));
163 // Set the return to allow the program go through
164 StatusOr<size_t> expectRet(expectMsgLength);
165
166 // A vector to hold the flattened netlink message for nlMsgSlice
167 std::vector<uint8_t> nlMsgBuf;
168 EXPECT_CALL(mockSyscalls, writev(_, _))
169 .WillOnce(DoAll(SaveFlattenedIovecs<1>(&nlMsgBuf), Return(expectRet)));
170 EXPECT_CALL(mockSyscalls, read(_, _))
171 .WillOnce(DoAll(SetArgSlice<1>(netdutils::makeSlice(response)), Return(readStatus)));
172
Jonathan Basseri20a17c32017-09-14 17:42:40 -0700173 Status res = ctrl.ipSecAllocateSpi(1 /* resourceId */, static_cast<int>(XfrmDirection::OUT),
174 localAddr, remoteAddr, DROID_SPI, &outSpi);
ludi5c81c762017-05-19 13:47:53 -0700175
Jonathan Basserid6c08582017-09-14 16:10:56 -0700176 EXPECT_TRUE(isOk(res)) << res;
ludi5c81c762017-05-19 13:47:53 -0700177 EXPECT_EQ(DROID_SPI, outSpi);
178 EXPECT_EQ(expectMsgLength, nlMsgBuf.size());
179
180 Slice nlMsgSlice = netdutils::makeSlice(nlMsgBuf);
181 nlMsgSlice = drop(nlMsgSlice, NLMSG_HDRLEN);
182
183 xfrm_userspi_info userspi{};
184 netdutils::extract(nlMsgSlice, userspi);
185
Jonathan Basseri20a17c32017-09-14 17:42:40 -0700186 EXPECT_EQ(family, userspi.info.sel.family);
187 expectAddressEquals(family, localAddr, userspi.info.saddr);
188 expectAddressEquals(family, remoteAddr, userspi.info.id.daddr);
ludi5c81c762017-05-19 13:47:53 -0700189
190 EXPECT_EQ(DROID_SPI, static_cast<int>(userspi.min));
191 EXPECT_EQ(DROID_SPI, static_cast<int>(userspi.max));
192}
193
Jonathan Basseri20a17c32017-09-14 17:42:40 -0700194TEST_P(XfrmControllerParameterizedTest, TestIpSecAddSecurityAssociation) {
195 const int family = GetParam();
196 const std::string localAddr = (family == AF_INET6) ? LOCALHOST_V6 : LOCALHOST_V4;
197 const std::string remoteAddr = (family == AF_INET6) ? TEST_ADDR_V6 : TEST_ADDR_V4;
ludi5c81c762017-05-19 13:47:53 -0700198 XfrmController ctrl;
199
200 NetlinkResponse response = {};
201 response.hdr.nlmsg_type = XFRM_MSG_ALLOCSPI;
202
203 /** It's an injected return result for the sendMessage function to go through */
204 StatusOr<Slice> readStatus(netdutils::makeSlice(response));
205
206 std::vector<uint8_t> authKey(KEY_LENGTH, 0);
207 std::vector<uint8_t> cryptKey(KEY_LENGTH, 1);
208
209 // Calculate the length of the expected netlink message.
Jonathan Basserid6c08582017-09-14 16:10:56 -0700210 size_t expectMsgLength =
211 NLMSG_HDRLEN + NLMSG_ALIGN(sizeof(xfrm_usersa_info)) +
212 NLA_ALIGN(offsetof(XfrmController::nlattr_algo_crypt, key) + KEY_LENGTH) +
Jonathan Basseri20a17c32017-09-14 17:42:40 -0700213 NLA_ALIGN(offsetof(XfrmController::nlattr_algo_auth, key) + KEY_LENGTH);
ludi5c81c762017-05-19 13:47:53 -0700214 StatusOr<size_t> expectRet(expectMsgLength);
215
216 std::vector<uint8_t> nlMsgBuf;
217 EXPECT_CALL(mockSyscalls, writev(_, _))
218 .WillOnce(DoAll(SaveFlattenedIovecs<1>(&nlMsgBuf), Return(expectRet)));
219 EXPECT_CALL(mockSyscalls, read(_, _))
220 .WillOnce(DoAll(SetArgSlice<1>(netdutils::makeSlice(response)), Return(readStatus)));
221
222 Status res = ctrl.ipSecAddSecurityAssociation(
223 1 /* resourceId */, static_cast<int>(XfrmMode::TUNNEL),
Jonathan Basseri20a17c32017-09-14 17:42:40 -0700224 static_cast<int>(XfrmDirection::OUT), localAddr, remoteAddr, 0 /* underlying network */,
225 DROID_SPI, "hmac(sha256)" /* auth algo */, authKey, 128 /* auth trunc length */,
226 "cbc(aes)" /* encryption algo */, cryptKey, 0 /* crypt trunc length? */, "" /* AEAD algo */,
227 {}, 0, static_cast<int>(XfrmEncapType::NONE), 0 /* local port */, 0 /* remote port */);
ludi5c81c762017-05-19 13:47:53 -0700228
Jonathan Basserid6c08582017-09-14 16:10:56 -0700229 EXPECT_TRUE(isOk(res)) << res;
ludi5c81c762017-05-19 13:47:53 -0700230 EXPECT_EQ(expectMsgLength, nlMsgBuf.size());
231
232 Slice nlMsgSlice = netdutils::makeSlice(nlMsgBuf);
233 nlMsgSlice = drop(nlMsgSlice, NLMSG_HDRLEN);
234
235 xfrm_usersa_info usersa{};
236 netdutils::extract(nlMsgSlice, usersa);
237
Jonathan Basseri20a17c32017-09-14 17:42:40 -0700238 EXPECT_EQ(family, usersa.family);
ludi5c81c762017-05-19 13:47:53 -0700239 EXPECT_EQ(1 /* Transform Id*/, static_cast<int>(usersa.reqid));
240 EXPECT_EQ(XFRM_MODE_TUNNEL, usersa.mode);
241 EXPECT_EQ(htonl(DROID_SPI), usersa.id.spi);
242 EXPECT_EQ(IPPROTO_ESP, usersa.id.proto);
243
Jonathan Basseri20a17c32017-09-14 17:42:40 -0700244 expectAddressEquals(family, localAddr, usersa.saddr);
245 expectAddressEquals(family, remoteAddr, usersa.id.daddr);
ludi5c81c762017-05-19 13:47:53 -0700246
247 Slice attr_buf = drop(nlMsgSlice, NLA_ALIGN(sizeof(xfrm_usersa_info)));
248
249 // Extract and check the encryption/authentication algorithm
250 XfrmController::nlattr_algo_crypt encryptAlgo{};
251 XfrmController::nlattr_algo_auth authAlgo{};
252 auto attrHandler = [&encryptAlgo, &authAlgo](const nlattr& attr, const Slice& attr_payload) {
253 Slice buf = attr_payload;
254 if (attr.nla_type == XFRMA_ALG_CRYPT) {
255 encryptAlgo.hdr = attr;
256 netdutils::extract(buf, encryptAlgo.crypt);
257 buf = drop(buf, sizeof(xfrm_algo));
258 netdutils::extract(buf, encryptAlgo.key);
259 } else if (attr.nla_type == XFRMA_ALG_AUTH_TRUNC) {
260 authAlgo.hdr = attr;
261 netdutils::extract(buf, authAlgo.auth);
262 buf = drop(buf, sizeof(xfrm_algo_auth));
263 netdutils::extract(buf, authAlgo.key);
Jonathan Basseri20a17c32017-09-14 17:42:40 -0700264 } else {
265 FAIL() << "Unexpected nlattr type: " << attr.nla_type;
ludi5c81c762017-05-19 13:47:53 -0700266 }
267 };
268 forEachNetlinkAttribute(attr_buf, attrHandler);
269
Jonathan Basserid6c08582017-09-14 16:10:56 -0700270 // TODO: Use ContainerEq or ElementsAreArray to get better test failure messages.
ludi5c81c762017-05-19 13:47:53 -0700271 EXPECT_EQ(0, memcmp(reinterpret_cast<void*>(cryptKey.data()),
272 reinterpret_cast<void*>(&encryptAlgo.key), KEY_LENGTH));
273 EXPECT_EQ(0, memcmp(reinterpret_cast<void*>(authKey.data()),
274 reinterpret_cast<void*>(&authAlgo.key), KEY_LENGTH));
275}
276
Jonathan Basseri20a17c32017-09-14 17:42:40 -0700277TEST_F(XfrmControllerTest, TestIpSecAddSecurityAssociationIPv4Encap) {
278 // TODO: Implement this test, which is nearly identical to
279 // TestIpSecAddSecurityAssociation.
280}
ludi5c81c762017-05-19 13:47:53 -0700281
Jonathan Basseri20a17c32017-09-14 17:42:40 -0700282// Test that input validation rejects IPv6 UDP encap.
283TEST_F(XfrmControllerTest, TestIpSecAddSecurityAssociationIPv6Encap) {
284 EXPECT_CALL(mockSyscalls, writev(_, _)).Times(0);
285
286 XfrmController ctrl;
287 Status res = ctrl.ipSecAddSecurityAssociation(
288 1, static_cast<int>(XfrmMode::TUNNEL), static_cast<int>(XfrmDirection::OUT), LOCALHOST_V6,
289 TEST_ADDR_V6, 0, DROID_SPI, "hmac(sha256)", {}, 128, "cbc(aes)", {}, 0, "", {}, 0,
290 static_cast<int>(XfrmEncapType::ESPINUDP_NON_IKE), 0, 0);
291
292 EXPECT_FALSE(isOk(res)) << "IPv6 UDP encap not rejected";
293}
294
295TEST_P(XfrmControllerParameterizedTest, TestIpSecApplyTransportModeTransform) {
296 const int family = GetParam();
297 const std::string localAddr = (family == AF_INET6) ? LOCALHOST_V6 : LOCALHOST_V4;
298 const std::string remoteAddr = (family == AF_INET6) ? TEST_ADDR_V6 : TEST_ADDR_V4;
299 size_t optlen = 0;
Jonathan Basserifc3b35f2017-09-14 15:58:16 -0700300 Policy policy{};
301 // Need to cast from void* in order to "SaveArg" policy. Easier to invoke a
302 // lambda than to write a gMock action.
303 auto SavePolicy = [&policy](const void* value) {
304 policy = *reinterpret_cast<const Policy*>(value);
305 };
306
ludi5c81c762017-05-19 13:47:53 -0700307 XfrmController ctrl;
308
309 struct sockaddr socketaddr;
Jonathan Basseri20a17c32017-09-14 17:42:40 -0700310 socketaddr.sa_family = family;
ludi5c81c762017-05-19 13:47:53 -0700311
Jonathan Basseri20a17c32017-09-14 17:42:40 -0700312 unique_fd sock(socket(family, SOCK_STREAM, 0));
ludi5c81c762017-05-19 13:47:53 -0700313
314 EXPECT_CALL(mockSyscalls, getsockname(_, _, _))
315 .WillOnce(DoAll(SetArgPointee<1>(socketaddr), Return(netdutils::status::ok)));
316
317 EXPECT_CALL(mockSyscalls, setsockopt(_, _, _, _, _))
Jonathan Basserifc3b35f2017-09-14 15:58:16 -0700318 .WillOnce(DoAll(WithArg<3>(Invoke(SavePolicy)), SaveArg<4>(&optlen),
319 Return(netdutils::status::ok)));
ludi5c81c762017-05-19 13:47:53 -0700320
Jonathan Basseri20a17c32017-09-14 17:42:40 -0700321 Status res = ctrl.ipSecApplyTransportModeTransform(sock, 1 /* resourceId */,
322 static_cast<int>(XfrmDirection::OUT),
323 localAddr, remoteAddr, DROID_SPI);
ludi5c81c762017-05-19 13:47:53 -0700324
Jonathan Basserid6c08582017-09-14 16:10:56 -0700325 EXPECT_TRUE(isOk(res)) << res;
Jonathan Basseri20a17c32017-09-14 17:42:40 -0700326 EXPECT_EQ(sizeof(Policy), optlen);
ludi5c81c762017-05-19 13:47:53 -0700327
Jonathan Basserifc3b35f2017-09-14 15:58:16 -0700328 EXPECT_EQ(1 /* resourceId */, static_cast<int>(policy.tmpl.reqid));
329 EXPECT_EQ(htonl(DROID_SPI), policy.tmpl.id.spi);
ludi5c81c762017-05-19 13:47:53 -0700330
Jonathan Basseri20a17c32017-09-14 17:42:40 -0700331 expectAddressEquals(family, localAddr, policy.tmpl.saddr);
332 expectAddressEquals(family, remoteAddr, policy.tmpl.id.daddr);
ludi5c81c762017-05-19 13:47:53 -0700333}
334
Jonathan Basseri20a17c32017-09-14 17:42:40 -0700335TEST_P(XfrmControllerParameterizedTest, TestIpSecDeleteSecurityAssociation) {
336 const int family = GetParam();
337 const std::string localAddr = (family == AF_INET6) ? LOCALHOST_V6 : LOCALHOST_V4;
338 const std::string remoteAddr = (family == AF_INET6) ? TEST_ADDR_V6 : TEST_ADDR_V4;
ludi5c81c762017-05-19 13:47:53 -0700339 XfrmController ctrl;
340 NetlinkResponse response = {};
341 response.hdr.nlmsg_type = XFRM_MSG_ALLOCSPI;
342
343 /** It's an injected return result for the sendMessage function to go through */
344 StatusOr<Slice> readStatus(netdutils::makeSlice(response));
345
346 size_t expectMsgLength = NLMSG_HDRLEN + NLMSG_ALIGN(sizeof(xfrm_usersa_id));
347 // Set the return to allow the program run through
348 StatusOr<size_t> expectRet(expectMsgLength);
349
350 std::vector<uint8_t> nlMsgBuf;
351 EXPECT_CALL(mockSyscalls, writev(_, _))
352 .WillOnce(DoAll(SaveFlattenedIovecs<1>(&nlMsgBuf), Return(expectRet)));
353 EXPECT_CALL(mockSyscalls, read(_, _))
354 .WillOnce(DoAll(SetArgSlice<1>(netdutils::makeSlice(response)), Return(readStatus)));
355
356 Status res = ctrl.ipSecDeleteSecurityAssociation(
Jonathan Basseri20a17c32017-09-14 17:42:40 -0700357 1 /* resourceId */, static_cast<int>(XfrmDirection::OUT), localAddr, remoteAddr, DROID_SPI);
ludi5c81c762017-05-19 13:47:53 -0700358
Jonathan Basserid6c08582017-09-14 16:10:56 -0700359 EXPECT_TRUE(isOk(res)) << res;
ludi5c81c762017-05-19 13:47:53 -0700360 EXPECT_EQ(expectMsgLength, nlMsgBuf.size());
361
362 Slice nlMsgSlice = netdutils::makeSlice(nlMsgBuf);
363 nlMsgSlice = netdutils::drop(nlMsgSlice, NLMSG_HDRLEN);
364
365 xfrm_usersa_id said{};
366 netdutils::extract(nlMsgSlice, said);
367
368 EXPECT_EQ(htonl(DROID_SPI), said.spi);
Jonathan Basseri20a17c32017-09-14 17:42:40 -0700369 expectAddressEquals(family, remoteAddr, said.daddr);
ludi5c81c762017-05-19 13:47:53 -0700370}
371
372} // namespace net
373} // namespace android