blob: dea1584bcaaadb1d8fec62adf2d326b15c7fedb8 [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
115class XfrmControllerTest : public ::testing::Test {
116public:
117 MockSyscalls mockSyscalls;
118
119 void SetUp() override { netdutils::sSyscalls.swap(mockSyscalls); }
120};
121
122TEST_F(XfrmControllerTest, TestIpSecAllocateSpi) {
123 int outSpi = 0;
124 XfrmController ctrl;
125
126 NetlinkResponse response = {};
127 response.hdr.nlmsg_type = XFRM_MSG_ALLOCSPI;
128
129 /** It's an injected return result for the sendMessage function to go through */
130 StatusOr<Slice> readStatus(netdutils::makeSlice(response));
131
132 size_t expectMsgLength = NLMSG_HDRLEN + NLMSG_ALIGN(sizeof(xfrm_userspi_info));
133
134 // Set the return to allow the program go through
135 StatusOr<size_t> expectRet(expectMsgLength);
136
137 // A vector to hold the flattened netlink message for nlMsgSlice
138 std::vector<uint8_t> nlMsgBuf;
139 EXPECT_CALL(mockSyscalls, writev(_, _))
140 .WillOnce(DoAll(SaveFlattenedIovecs<1>(&nlMsgBuf), Return(expectRet)));
141 EXPECT_CALL(mockSyscalls, read(_, _))
142 .WillOnce(DoAll(SetArgSlice<1>(netdutils::makeSlice(response)), Return(readStatus)));
143
144 Status res = ctrl.ipSecAllocateSpi(
145 1 /* resourceId */, static_cast<int>(XfrmDirection::OUT), "127.0.0.1" /* local address */,
146 "8.8.8.8" /* remote address */, DROID_SPI /* request spi */, &outSpi);
147
148 EXPECT_EQ(0, res.code());
149 EXPECT_EQ(DROID_SPI, outSpi);
150 EXPECT_EQ(expectMsgLength, nlMsgBuf.size());
151
152 Slice nlMsgSlice = netdutils::makeSlice(nlMsgBuf);
153 nlMsgSlice = drop(nlMsgSlice, NLMSG_HDRLEN);
154
155 xfrm_userspi_info userspi{};
156 netdutils::extract(nlMsgSlice, userspi);
157
158 EXPECT_EQ(AF_INET, userspi.info.sel.family);
159
Jonathan Basseri8fc43f52017-09-14 16:40:47 -0700160 xfrm_address_t saddr{};
ludi5c81c762017-05-19 13:47:53 -0700161 inet_pton(AF_INET, "127.0.0.1", reinterpret_cast<void*>(&saddr));
162 EXPECT_EQ(0, memcmp(&saddr, &userspi.info.saddr, sizeof(xfrm_address_t)));
163
Jonathan Basseri8fc43f52017-09-14 16:40:47 -0700164 xfrm_address_t daddr{};
ludi5c81c762017-05-19 13:47:53 -0700165 inet_pton(AF_INET, "8.8.8.8", reinterpret_cast<void*>(&daddr));
166 EXPECT_EQ(0, memcmp(&daddr, &userspi.info.id.daddr, sizeof(xfrm_address_t)));
167
168 EXPECT_EQ(DROID_SPI, static_cast<int>(userspi.min));
169 EXPECT_EQ(DROID_SPI, static_cast<int>(userspi.max));
170}
171
172TEST_F(XfrmControllerTest, TestIpSecAllocateSpiIpv6) {
173 int outSpi = 0;
174 XfrmController ctrl;
175
176 NetlinkResponse response = {};
177 response.hdr.nlmsg_type = XFRM_MSG_ALLOCSPI;
178
179 /** It's an injected return result for the sendMessage function to go through */
180 StatusOr<Slice> readStatus(netdutils::makeSlice(response));
181
182 size_t expectMsgLength = NLMSG_HDRLEN + NLMSG_ALIGN(sizeof(xfrm_userspi_info));
183 // Set the return to allow the program go through
184 StatusOr<size_t> expectRet(expectMsgLength);
185
186 // A vector to hold the flattened netlink message for nlMsgSlice
187 std::vector<uint8_t> nlMsgBuf;
188 EXPECT_CALL(mockSyscalls, writev(_, _))
189 .WillOnce(DoAll(SaveFlattenedIovecs<1>(&nlMsgBuf), Return(expectRet)));
190 EXPECT_CALL(mockSyscalls, read(_, _))
191 .WillOnce(DoAll(SetArgSlice<1>(netdutils::makeSlice(response)), Return(readStatus)));
192
193 Status res = ctrl.ipSecAllocateSpi(
194 1 /* resourceId */, static_cast<int>(XfrmDirection::OUT), "::1" /* local address */,
195 "2001:4860:4860::8888" /* remote address */, DROID_SPI /* request spi */, &outSpi);
196
197 EXPECT_EQ(0, res.code());
198 EXPECT_EQ(DROID_SPI, outSpi);
199 EXPECT_EQ(expectMsgLength, nlMsgBuf.size());
200
201 Slice nlMsgSlice = netdutils::makeSlice(nlMsgBuf);
202 nlMsgSlice = drop(nlMsgSlice, NLMSG_HDRLEN);
203
204 xfrm_userspi_info userspi{};
205 netdutils::extract(nlMsgSlice, userspi);
206
207 EXPECT_EQ(AF_INET6, userspi.info.sel.family);
208
Jonathan Basseri8fc43f52017-09-14 16:40:47 -0700209 xfrm_address_t saddr{};
ludi5c81c762017-05-19 13:47:53 -0700210 inet_pton(AF_INET6, "::1", reinterpret_cast<void*>(&saddr));
211 EXPECT_EQ(0, memcmp(&saddr, &userspi.info.saddr, sizeof(xfrm_address_t)));
212
Jonathan Basseri8fc43f52017-09-14 16:40:47 -0700213 xfrm_address_t daddr{};
ludi5c81c762017-05-19 13:47:53 -0700214 inet_pton(AF_INET6, "2001:4860:4860::8888", reinterpret_cast<void*>(&daddr));
215 EXPECT_EQ(0, memcmp(&daddr, &userspi.info.id.daddr, sizeof(xfrm_address_t)));
216
217 EXPECT_EQ(DROID_SPI, static_cast<int>(userspi.min));
218 EXPECT_EQ(DROID_SPI, static_cast<int>(userspi.max));
219}
220
221TEST_F(XfrmControllerTest, TestIpSecAddSecurityAssociation) {
222
223 int reqSpi = DROID_SPI;
224 XfrmController ctrl;
225
226 NetlinkResponse response = {};
227 response.hdr.nlmsg_type = XFRM_MSG_ALLOCSPI;
228
229 /** It's an injected return result for the sendMessage function to go through */
230 StatusOr<Slice> readStatus(netdutils::makeSlice(response));
231
232 std::vector<uint8_t> authKey(KEY_LENGTH, 0);
233 std::vector<uint8_t> cryptKey(KEY_LENGTH, 1);
234
235 // Calculate the length of the expected netlink message.
236 size_t expectMsgLength = NLMSG_HDRLEN + NLMSG_ALIGN(sizeof(xfrm_usersa_info)) +
237 NLA_ALIGN(offsetof(XfrmController::nlattr_algo_crypt, key) + KEY_LENGTH) +
238 NLA_ALIGN(offsetof(XfrmController::nlattr_algo_auth, key) + KEY_LENGTH) +
239 NLA_ALIGN(sizeof(XfrmController::nlattr_encap_tmpl));
240 StatusOr<size_t> expectRet(expectMsgLength);
241
242 std::vector<uint8_t> nlMsgBuf;
243 EXPECT_CALL(mockSyscalls, writev(_, _))
244 .WillOnce(DoAll(SaveFlattenedIovecs<1>(&nlMsgBuf), Return(expectRet)));
245 EXPECT_CALL(mockSyscalls, read(_, _))
246 .WillOnce(DoAll(SetArgSlice<1>(netdutils::makeSlice(response)), Return(readStatus)));
247
248 Status res = ctrl.ipSecAddSecurityAssociation(
249 1 /* resourceId */, static_cast<int>(XfrmMode::TUNNEL),
250 static_cast<int>(XfrmDirection::OUT), "127.0.0.1" /* local address */,
251 "8.8.8.8" /* remote address */, 0 /* network handle */, reqSpi,
252 "hmac(sha256)" /* auth algo */, authKey, 0, "cbc(aes)" /* encryption algo */, cryptKey, 0,
253 UDP_ENCAP_ESPINUDP_NON_IKE /* encapType */, 34567 /* local port */,
254 34567 /* remote port */);
255
256 EXPECT_EQ(0, res.code());
257 EXPECT_EQ(expectMsgLength, nlMsgBuf.size());
258
259 Slice nlMsgSlice = netdutils::makeSlice(nlMsgBuf);
260 nlMsgSlice = drop(nlMsgSlice, NLMSG_HDRLEN);
261
262 xfrm_usersa_info usersa{};
263 netdutils::extract(nlMsgSlice, usersa);
264
265 EXPECT_EQ(AF_INET, usersa.family);
266 EXPECT_EQ(1 /* Transform Id*/, static_cast<int>(usersa.reqid));
267 EXPECT_EQ(XFRM_MODE_TUNNEL, usersa.mode);
268 EXPECT_EQ(htonl(DROID_SPI), usersa.id.spi);
269 EXPECT_EQ(IPPROTO_ESP, usersa.id.proto);
270
271 xfrm_address_t saddr{};
272 inet_pton(AF_INET, "127.0.0.1", reinterpret_cast<void*>(&saddr));
273 EXPECT_EQ(0, memcmp(&saddr, &usersa.saddr, sizeof(xfrm_address_t)));
274
275 xfrm_address_t daddr{};
276 inet_pton(AF_INET, "8.8.8.8", reinterpret_cast<void*>(&daddr));
277 EXPECT_EQ(0, memcmp(&daddr, &usersa.id.daddr, sizeof(xfrm_address_t)));
278
279 Slice attr_buf = drop(nlMsgSlice, NLA_ALIGN(sizeof(xfrm_usersa_info)));
280
281 // Extract and check the encryption/authentication algorithm
282 XfrmController::nlattr_algo_crypt encryptAlgo{};
283 XfrmController::nlattr_algo_auth authAlgo{};
284 auto attrHandler = [&encryptAlgo, &authAlgo](const nlattr& attr, const Slice& attr_payload) {
285 Slice buf = attr_payload;
286 if (attr.nla_type == XFRMA_ALG_CRYPT) {
287 encryptAlgo.hdr = attr;
288 netdutils::extract(buf, encryptAlgo.crypt);
289 buf = drop(buf, sizeof(xfrm_algo));
290 netdutils::extract(buf, encryptAlgo.key);
291 } else if (attr.nla_type == XFRMA_ALG_AUTH_TRUNC) {
292 authAlgo.hdr = attr;
293 netdutils::extract(buf, authAlgo.auth);
294 buf = drop(buf, sizeof(xfrm_algo_auth));
295 netdutils::extract(buf, authAlgo.key);
296 }
297 };
298 forEachNetlinkAttribute(attr_buf, attrHandler);
299
300 EXPECT_EQ(0, memcmp(reinterpret_cast<void*>(cryptKey.data()),
301 reinterpret_cast<void*>(&encryptAlgo.key), KEY_LENGTH));
302 EXPECT_EQ(0, memcmp(reinterpret_cast<void*>(authKey.data()),
303 reinterpret_cast<void*>(&authAlgo.key), KEY_LENGTH));
304}
305
306TEST_F(XfrmControllerTest, TestIpSecApplyTransportModeTransform) {
307
308 int optlen = 0;
Jonathan Basserifc3b35f2017-09-14 15:58:16 -0700309 Policy policy{};
310 // Need to cast from void* in order to "SaveArg" policy. Easier to invoke a
311 // lambda than to write a gMock action.
312 auto SavePolicy = [&policy](const void* value) {
313 policy = *reinterpret_cast<const Policy*>(value);
314 };
315
ludi5c81c762017-05-19 13:47:53 -0700316 XfrmController ctrl;
317
318 struct sockaddr socketaddr;
319 socketaddr.sa_family = AF_INET;
320
321 unique_fd sock(socket(AF_INET, SOCK_STREAM, 0));
322
323 EXPECT_CALL(mockSyscalls, getsockname(_, _, _))
324 .WillOnce(DoAll(SetArgPointee<1>(socketaddr), Return(netdutils::status::ok)));
325
326 EXPECT_CALL(mockSyscalls, setsockopt(_, _, _, _, _))
Jonathan Basserifc3b35f2017-09-14 15:58:16 -0700327 .WillOnce(DoAll(WithArg<3>(Invoke(SavePolicy)), SaveArg<4>(&optlen),
328 Return(netdutils::status::ok)));
ludi5c81c762017-05-19 13:47:53 -0700329
330 Status res = ctrl.ipSecApplyTransportModeTransform(
331 sock, 1 /* resourceId */, static_cast<int>(XfrmDirection::OUT),
332 "127.0.0.1" /* local address */, "8.8.8.8" /* remote address */, DROID_SPI);
333
334 EXPECT_EQ(0, res.code());
335 EXPECT_EQ(static_cast<int>(sizeof(Policy)), optlen);
336
Jonathan Basserifc3b35f2017-09-14 15:58:16 -0700337 EXPECT_EQ(1 /* resourceId */, static_cast<int>(policy.tmpl.reqid));
338 EXPECT_EQ(htonl(DROID_SPI), policy.tmpl.id.spi);
ludi5c81c762017-05-19 13:47:53 -0700339
340 xfrm_address_t saddr{};
341 inet_pton(AF_INET, "127.0.0.1", reinterpret_cast<void*>(&saddr));
Jonathan Basserifc3b35f2017-09-14 15:58:16 -0700342 EXPECT_EQ(0, memcmp(&saddr, &policy.tmpl.saddr, sizeof(xfrm_address_t)));
ludi5c81c762017-05-19 13:47:53 -0700343
344 xfrm_address_t daddr{};
345 inet_pton(AF_INET, "8.8.8.8", reinterpret_cast<void*>(&daddr));
Jonathan Basserifc3b35f2017-09-14 15:58:16 -0700346 EXPECT_EQ(0, memcmp(&daddr, &policy.tmpl.id.daddr, sizeof(xfrm_address_t)));
ludi5c81c762017-05-19 13:47:53 -0700347}
348
349TEST_F(XfrmControllerTest, TestIpSecDeleteSecurityAssociation) {
350 XfrmController ctrl;
351 NetlinkResponse response = {};
352 response.hdr.nlmsg_type = XFRM_MSG_ALLOCSPI;
353
354 /** It's an injected return result for the sendMessage function to go through */
355 StatusOr<Slice> readStatus(netdutils::makeSlice(response));
356
357 size_t expectMsgLength = NLMSG_HDRLEN + NLMSG_ALIGN(sizeof(xfrm_usersa_id));
358 // Set the return to allow the program run through
359 StatusOr<size_t> expectRet(expectMsgLength);
360
361 std::vector<uint8_t> nlMsgBuf;
362 EXPECT_CALL(mockSyscalls, writev(_, _))
363 .WillOnce(DoAll(SaveFlattenedIovecs<1>(&nlMsgBuf), Return(expectRet)));
364 EXPECT_CALL(mockSyscalls, read(_, _))
365 .WillOnce(DoAll(SetArgSlice<1>(netdutils::makeSlice(response)), Return(readStatus)));
366
367 Status res = ctrl.ipSecDeleteSecurityAssociation(
368 1 /* resourceId */, static_cast<int>(XfrmDirection::OUT), "127.0.0.1" /* local address */,
369 "8.8.8.8" /* remote address */, DROID_SPI);
370
371 EXPECT_EQ(0, res.code());
372 EXPECT_EQ(expectMsgLength, nlMsgBuf.size());
373
374 Slice nlMsgSlice = netdutils::makeSlice(nlMsgBuf);
375 nlMsgSlice = netdutils::drop(nlMsgSlice, NLMSG_HDRLEN);
376
377 xfrm_usersa_id said{};
378 netdutils::extract(nlMsgSlice, said);
379
380 EXPECT_EQ(htonl(DROID_SPI), said.spi);
Jonathan Basseri8fc43f52017-09-14 16:40:47 -0700381 xfrm_address_t daddr{};
ludi5c81c762017-05-19 13:47:53 -0700382 inet_pton(AF_INET, "8.8.8.8", reinterpret_cast<void*>(&daddr));
383
384 EXPECT_EQ(0, memcmp(&daddr, &said.daddr, sizeof(xfrm_address_t)));
385}
386
387} // namespace net
388} // namespace android