blob: 8eb1fe453c3967a65cb68e24908de85485e30277 [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
65using ::testing::DoAll;
Jonathan Basserifc3b35f2017-09-14 15:58:16 -070066using ::testing::Invoke;
ludi5c81c762017-05-19 13:47:53 -070067using ::testing::Return;
68using ::testing::SaveArg;
69using ::testing::SetArgPointee;
Jonathan Basserifc3b35f2017-09-14 15:58:16 -070070using ::testing::WithArg;
ludi5c81c762017-05-19 13:47:53 -070071using ::testing::_;
72
73/**
Jonathan Basseric6128662017-09-14 17:32:59 -070074 * This gMock action works like SetArgPointee, but for netdutils::Slice.
75 * It sets the memory which is pointed to by the N-th argument with the supplied value.
ludi5c81c762017-05-19 13:47:53 -070076 */
Jonathan Basseric6128662017-09-14 17:32:59 -070077ACTION_TEMPLATE(SetArgSlice, HAS_1_TEMPLATE_PARAMS(int, N), AND_1_VALUE_PARAMS(value)) {
78 Slice orig = ::testing::get<N>(args);
ludi5c81c762017-05-19 13:47:53 -070079 android::netdutils::copy(orig, value);
80}
81
Jonathan Basseric6128662017-09-14 17:32:59 -070082/**
83 * This gMock action works like SaveArg, but is specialized for vector<iovec>.
84 * It copies the memory pointed to by each of the iovecs into a single vector<uint8_t>.
85 *
86 * Flattening the iovec objects cannot be done later, since there is no guarantee that the memory
87 * they point to will still be valid after the mock method returns.
88 */
89ACTION_TEMPLATE(SaveFlattenedIovecs, HAS_1_TEMPLATE_PARAMS(int, N), AND_1_VALUE_PARAMS(resVec)) {
90 const std::vector<iovec>& iovs = ::testing::get<N>(args);
ludi5c81c762017-05-19 13:47:53 -070091
92 for (const iovec& iov : iovs) {
93 resVec->insert(resVec->end(), reinterpret_cast<uint8_t*>(iov.iov_base),
94 reinterpret_cast<uint8_t*>(iov.iov_base) + iov.iov_len);
95 }
96}
97
98namespace android {
99namespace net {
100
101static constexpr int DROID_SPI = 0xD1201D;
102static constexpr size_t KEY_LENGTH = 32;
103static constexpr int NLMSG_DEFAULTSIZE = 8192;
104
105struct Policy {
106 xfrm_userpolicy_info info;
107 xfrm_user_tmpl tmpl;
108};
109
110struct NetlinkResponse {
111 nlmsghdr hdr;
112 char buf[NLMSG_DEFAULTSIZE];
113};
114
Jonathan Basserid6c08582017-09-14 16:10:56 -0700115void expectAddressEquals(int family, const std::string& expected, const xfrm_address_t& actual) {
116 char actualStr[INET6_ADDRSTRLEN];
117 const char* ret =
118 inet_ntop(family, reinterpret_cast<const void*>(&actual), actualStr, INET6_ADDRSTRLEN);
119 EXPECT_NE(nullptr, ret) << "Unable to convert xfrm_address_t to string";
120 EXPECT_EQ(expected, actualStr);
121}
122
ludi5c81c762017-05-19 13:47:53 -0700123class XfrmControllerTest : public ::testing::Test {
124public:
125 MockSyscalls mockSyscalls;
126
127 void SetUp() override { netdutils::sSyscalls.swap(mockSyscalls); }
128};
129
130TEST_F(XfrmControllerTest, TestIpSecAllocateSpi) {
131 int outSpi = 0;
132 XfrmController ctrl;
133
134 NetlinkResponse response = {};
135 response.hdr.nlmsg_type = XFRM_MSG_ALLOCSPI;
136
137 /** It's an injected return result for the sendMessage function to go through */
138 StatusOr<Slice> readStatus(netdutils::makeSlice(response));
139
140 size_t expectMsgLength = NLMSG_HDRLEN + NLMSG_ALIGN(sizeof(xfrm_userspi_info));
141
142 // Set the return to allow the program go through
143 StatusOr<size_t> expectRet(expectMsgLength);
144
145 // A vector to hold the flattened netlink message for nlMsgSlice
146 std::vector<uint8_t> nlMsgBuf;
147 EXPECT_CALL(mockSyscalls, writev(_, _))
148 .WillOnce(DoAll(SaveFlattenedIovecs<1>(&nlMsgBuf), Return(expectRet)));
149 EXPECT_CALL(mockSyscalls, read(_, _))
150 .WillOnce(DoAll(SetArgSlice<1>(netdutils::makeSlice(response)), Return(readStatus)));
151
152 Status res = ctrl.ipSecAllocateSpi(
153 1 /* resourceId */, static_cast<int>(XfrmDirection::OUT), "127.0.0.1" /* local address */,
154 "8.8.8.8" /* remote address */, DROID_SPI /* request spi */, &outSpi);
155
Jonathan Basserid6c08582017-09-14 16:10:56 -0700156 EXPECT_TRUE(isOk(res)) << res;
ludi5c81c762017-05-19 13:47:53 -0700157 EXPECT_EQ(DROID_SPI, outSpi);
158 EXPECT_EQ(expectMsgLength, nlMsgBuf.size());
159
160 Slice nlMsgSlice = netdutils::makeSlice(nlMsgBuf);
161 nlMsgSlice = drop(nlMsgSlice, NLMSG_HDRLEN);
162
163 xfrm_userspi_info userspi{};
164 netdutils::extract(nlMsgSlice, userspi);
165
166 EXPECT_EQ(AF_INET, userspi.info.sel.family);
167
Jonathan Basserid6c08582017-09-14 16:10:56 -0700168 expectAddressEquals(AF_INET, "127.0.0.1", userspi.info.saddr);
169 expectAddressEquals(AF_INET, "8.8.8.8", userspi.info.id.daddr);
ludi5c81c762017-05-19 13:47:53 -0700170
171 EXPECT_EQ(DROID_SPI, static_cast<int>(userspi.min));
172 EXPECT_EQ(DROID_SPI, static_cast<int>(userspi.max));
173}
174
175TEST_F(XfrmControllerTest, TestIpSecAllocateSpiIpv6) {
176 int outSpi = 0;
177 XfrmController ctrl;
178
179 NetlinkResponse response = {};
180 response.hdr.nlmsg_type = XFRM_MSG_ALLOCSPI;
181
182 /** It's an injected return result for the sendMessage function to go through */
183 StatusOr<Slice> readStatus(netdutils::makeSlice(response));
184
185 size_t expectMsgLength = NLMSG_HDRLEN + NLMSG_ALIGN(sizeof(xfrm_userspi_info));
186 // Set the return to allow the program go through
187 StatusOr<size_t> expectRet(expectMsgLength);
188
189 // A vector to hold the flattened netlink message for nlMsgSlice
190 std::vector<uint8_t> nlMsgBuf;
191 EXPECT_CALL(mockSyscalls, writev(_, _))
192 .WillOnce(DoAll(SaveFlattenedIovecs<1>(&nlMsgBuf), Return(expectRet)));
193 EXPECT_CALL(mockSyscalls, read(_, _))
194 .WillOnce(DoAll(SetArgSlice<1>(netdutils::makeSlice(response)), Return(readStatus)));
195
196 Status res = ctrl.ipSecAllocateSpi(
197 1 /* resourceId */, static_cast<int>(XfrmDirection::OUT), "::1" /* local address */,
198 "2001:4860:4860::8888" /* remote address */, DROID_SPI /* request spi */, &outSpi);
199
Jonathan Basserid6c08582017-09-14 16:10:56 -0700200 EXPECT_TRUE(isOk(res)) << res;
ludi5c81c762017-05-19 13:47:53 -0700201 EXPECT_EQ(DROID_SPI, outSpi);
202 EXPECT_EQ(expectMsgLength, nlMsgBuf.size());
203
204 Slice nlMsgSlice = netdutils::makeSlice(nlMsgBuf);
205 nlMsgSlice = drop(nlMsgSlice, NLMSG_HDRLEN);
206
207 xfrm_userspi_info userspi{};
208 netdutils::extract(nlMsgSlice, userspi);
209
210 EXPECT_EQ(AF_INET6, userspi.info.sel.family);
211
Jonathan Basserid6c08582017-09-14 16:10:56 -0700212 expectAddressEquals(AF_INET6, "::1", userspi.info.saddr);
213 expectAddressEquals(AF_INET6, "2001:4860:4860::8888", userspi.info.id.daddr);
ludi5c81c762017-05-19 13:47:53 -0700214
215 EXPECT_EQ(DROID_SPI, static_cast<int>(userspi.min));
216 EXPECT_EQ(DROID_SPI, static_cast<int>(userspi.max));
217}
218
219TEST_F(XfrmControllerTest, TestIpSecAddSecurityAssociation) {
220
221 int reqSpi = DROID_SPI;
222 XfrmController ctrl;
223
224 NetlinkResponse response = {};
225 response.hdr.nlmsg_type = XFRM_MSG_ALLOCSPI;
226
227 /** It's an injected return result for the sendMessage function to go through */
228 StatusOr<Slice> readStatus(netdutils::makeSlice(response));
229
230 std::vector<uint8_t> authKey(KEY_LENGTH, 0);
231 std::vector<uint8_t> cryptKey(KEY_LENGTH, 1);
232
233 // Calculate the length of the expected netlink message.
Jonathan Basserid6c08582017-09-14 16:10:56 -0700234 size_t expectMsgLength =
235 NLMSG_HDRLEN + NLMSG_ALIGN(sizeof(xfrm_usersa_info)) +
236 NLA_ALIGN(offsetof(XfrmController::nlattr_algo_crypt, key) + KEY_LENGTH) +
237 NLA_ALIGN(offsetof(XfrmController::nlattr_algo_auth, key) + KEY_LENGTH) +
238 NLA_ALIGN(sizeof(XfrmController::nlattr_encap_tmpl));
ludi5c81c762017-05-19 13:47:53 -0700239 StatusOr<size_t> expectRet(expectMsgLength);
240
241 std::vector<uint8_t> nlMsgBuf;
242 EXPECT_CALL(mockSyscalls, writev(_, _))
243 .WillOnce(DoAll(SaveFlattenedIovecs<1>(&nlMsgBuf), Return(expectRet)));
244 EXPECT_CALL(mockSyscalls, read(_, _))
245 .WillOnce(DoAll(SetArgSlice<1>(netdutils::makeSlice(response)), Return(readStatus)));
246
247 Status res = ctrl.ipSecAddSecurityAssociation(
248 1 /* resourceId */, static_cast<int>(XfrmMode::TUNNEL),
249 static_cast<int>(XfrmDirection::OUT), "127.0.0.1" /* local address */,
250 "8.8.8.8" /* remote address */, 0 /* network handle */, reqSpi,
251 "hmac(sha256)" /* auth algo */, authKey, 0, "cbc(aes)" /* encryption algo */, cryptKey, 0,
252 UDP_ENCAP_ESPINUDP_NON_IKE /* encapType */, 34567 /* local port */,
253 34567 /* remote port */);
254
Jonathan Basserid6c08582017-09-14 16:10:56 -0700255 EXPECT_TRUE(isOk(res)) << res;
ludi5c81c762017-05-19 13:47:53 -0700256 EXPECT_EQ(expectMsgLength, nlMsgBuf.size());
257
258 Slice nlMsgSlice = netdutils::makeSlice(nlMsgBuf);
259 nlMsgSlice = drop(nlMsgSlice, NLMSG_HDRLEN);
260
261 xfrm_usersa_info usersa{};
262 netdutils::extract(nlMsgSlice, usersa);
263
264 EXPECT_EQ(AF_INET, usersa.family);
265 EXPECT_EQ(1 /* Transform Id*/, static_cast<int>(usersa.reqid));
266 EXPECT_EQ(XFRM_MODE_TUNNEL, usersa.mode);
267 EXPECT_EQ(htonl(DROID_SPI), usersa.id.spi);
268 EXPECT_EQ(IPPROTO_ESP, usersa.id.proto);
269
Jonathan Basserid6c08582017-09-14 16:10:56 -0700270 expectAddressEquals(AF_INET, "127.0.0.1", usersa.saddr);
271 expectAddressEquals(AF_INET, "8.8.8.8", usersa.id.daddr);
ludi5c81c762017-05-19 13:47:53 -0700272
273 Slice attr_buf = drop(nlMsgSlice, NLA_ALIGN(sizeof(xfrm_usersa_info)));
274
275 // Extract and check the encryption/authentication algorithm
276 XfrmController::nlattr_algo_crypt encryptAlgo{};
277 XfrmController::nlattr_algo_auth authAlgo{};
278 auto attrHandler = [&encryptAlgo, &authAlgo](const nlattr& attr, const Slice& attr_payload) {
279 Slice buf = attr_payload;
280 if (attr.nla_type == XFRMA_ALG_CRYPT) {
281 encryptAlgo.hdr = attr;
282 netdutils::extract(buf, encryptAlgo.crypt);
283 buf = drop(buf, sizeof(xfrm_algo));
284 netdutils::extract(buf, encryptAlgo.key);
285 } else if (attr.nla_type == XFRMA_ALG_AUTH_TRUNC) {
286 authAlgo.hdr = attr;
287 netdutils::extract(buf, authAlgo.auth);
288 buf = drop(buf, sizeof(xfrm_algo_auth));
289 netdutils::extract(buf, authAlgo.key);
290 }
291 };
292 forEachNetlinkAttribute(attr_buf, attrHandler);
293
Jonathan Basserid6c08582017-09-14 16:10:56 -0700294 // TODO: Use ContainerEq or ElementsAreArray to get better test failure messages.
ludi5c81c762017-05-19 13:47:53 -0700295 EXPECT_EQ(0, memcmp(reinterpret_cast<void*>(cryptKey.data()),
296 reinterpret_cast<void*>(&encryptAlgo.key), KEY_LENGTH));
297 EXPECT_EQ(0, memcmp(reinterpret_cast<void*>(authKey.data()),
298 reinterpret_cast<void*>(&authAlgo.key), KEY_LENGTH));
299}
300
301TEST_F(XfrmControllerTest, TestIpSecApplyTransportModeTransform) {
302
303 int optlen = 0;
Jonathan Basserifc3b35f2017-09-14 15:58:16 -0700304 Policy policy{};
305 // Need to cast from void* in order to "SaveArg" policy. Easier to invoke a
306 // lambda than to write a gMock action.
307 auto SavePolicy = [&policy](const void* value) {
308 policy = *reinterpret_cast<const Policy*>(value);
309 };
310
ludi5c81c762017-05-19 13:47:53 -0700311 XfrmController ctrl;
312
313 struct sockaddr socketaddr;
314 socketaddr.sa_family = AF_INET;
315
316 unique_fd sock(socket(AF_INET, SOCK_STREAM, 0));
317
318 EXPECT_CALL(mockSyscalls, getsockname(_, _, _))
319 .WillOnce(DoAll(SetArgPointee<1>(socketaddr), Return(netdutils::status::ok)));
320
321 EXPECT_CALL(mockSyscalls, setsockopt(_, _, _, _, _))
Jonathan Basserifc3b35f2017-09-14 15:58:16 -0700322 .WillOnce(DoAll(WithArg<3>(Invoke(SavePolicy)), SaveArg<4>(&optlen),
323 Return(netdutils::status::ok)));
ludi5c81c762017-05-19 13:47:53 -0700324
325 Status res = ctrl.ipSecApplyTransportModeTransform(
326 sock, 1 /* resourceId */, static_cast<int>(XfrmDirection::OUT),
327 "127.0.0.1" /* local address */, "8.8.8.8" /* remote address */, DROID_SPI);
328
Jonathan Basserid6c08582017-09-14 16:10:56 -0700329 EXPECT_TRUE(isOk(res)) << res;
ludi5c81c762017-05-19 13:47:53 -0700330 EXPECT_EQ(static_cast<int>(sizeof(Policy)), optlen);
331
Jonathan Basserifc3b35f2017-09-14 15:58:16 -0700332 EXPECT_EQ(1 /* resourceId */, static_cast<int>(policy.tmpl.reqid));
333 EXPECT_EQ(htonl(DROID_SPI), policy.tmpl.id.spi);
ludi5c81c762017-05-19 13:47:53 -0700334
Jonathan Basserid6c08582017-09-14 16:10:56 -0700335 expectAddressEquals(AF_INET, "127.0.0.1", policy.tmpl.saddr);
336 expectAddressEquals(AF_INET, "8.8.8.8", policy.tmpl.id.daddr);
ludi5c81c762017-05-19 13:47:53 -0700337}
338
339TEST_F(XfrmControllerTest, TestIpSecDeleteSecurityAssociation) {
340 XfrmController ctrl;
341 NetlinkResponse response = {};
342 response.hdr.nlmsg_type = XFRM_MSG_ALLOCSPI;
343
344 /** It's an injected return result for the sendMessage function to go through */
345 StatusOr<Slice> readStatus(netdutils::makeSlice(response));
346
347 size_t expectMsgLength = NLMSG_HDRLEN + NLMSG_ALIGN(sizeof(xfrm_usersa_id));
348 // Set the return to allow the program run through
349 StatusOr<size_t> expectRet(expectMsgLength);
350
351 std::vector<uint8_t> nlMsgBuf;
352 EXPECT_CALL(mockSyscalls, writev(_, _))
353 .WillOnce(DoAll(SaveFlattenedIovecs<1>(&nlMsgBuf), Return(expectRet)));
354 EXPECT_CALL(mockSyscalls, read(_, _))
355 .WillOnce(DoAll(SetArgSlice<1>(netdutils::makeSlice(response)), Return(readStatus)));
356
357 Status res = ctrl.ipSecDeleteSecurityAssociation(
358 1 /* resourceId */, static_cast<int>(XfrmDirection::OUT), "127.0.0.1" /* local address */,
359 "8.8.8.8" /* remote address */, DROID_SPI);
360
Jonathan Basserid6c08582017-09-14 16:10:56 -0700361 EXPECT_TRUE(isOk(res)) << res;
ludi5c81c762017-05-19 13:47:53 -0700362 EXPECT_EQ(expectMsgLength, nlMsgBuf.size());
363
364 Slice nlMsgSlice = netdutils::makeSlice(nlMsgBuf);
365 nlMsgSlice = netdutils::drop(nlMsgSlice, NLMSG_HDRLEN);
366
367 xfrm_usersa_id said{};
368 netdutils::extract(nlMsgSlice, said);
369
370 EXPECT_EQ(htonl(DROID_SPI), said.spi);
ludi5c81c762017-05-19 13:47:53 -0700371
Jonathan Basserid6c08582017-09-14 16:10:56 -0700372 expectAddressEquals(AF_INET, "8.8.8.8", said.daddr);
ludi5c81c762017-05-19 13:47:53 -0700373}
374
375} // namespace net
376} // namespace android