blob: 076707a5c922db21c0f690743d1a9e495690fa85 [file] [log] [blame]
Nathan Harold1a371532017-01-30 12:30:48 -08001/*
2 *
3 * Copyright (C) 2017 The Android Open Source Project
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18#include <string>
19#include <vector>
20
21#include <ctype.h>
22#include <errno.h>
23#include <fcntl.h>
24#include <getopt.h>
25#include <stdio.h>
26#include <stdlib.h>
27#include <string.h>
Nathan Harold420ceac2017-04-05 19:36:59 -070028
29#define __STDC_FORMAT_MACROS
Nathan Harold1a371532017-01-30 12:30:48 -080030#include <inttypes.h>
31
32#include <arpa/inet.h>
33#include <netinet/in.h>
34
35#include <sys/socket.h>
36#include <sys/stat.h>
37#include <sys/types.h>
38#include <sys/wait.h>
39
40#include <linux/in.h>
41#include <linux/netlink.h>
42#include <linux/xfrm.h>
43
44#include "android-base/stringprintf.h"
45#include "android-base/strings.h"
46#include "android-base/unique_fd.h"
47#define LOG_TAG "XfrmController"
48#include "NetdConstants.h"
49#include "NetlinkCommands.h"
50#include "ResponseCode.h"
51#include "XfrmController.h"
ludi4072ff22017-06-15 08:56:52 -070052#include "netdutils/Fd.h"
53#include "netdutils/Slice.h"
54#include "netdutils/Syscalls.h"
Nathan Harold1a371532017-01-30 12:30:48 -080055#include <cutils/log.h>
56#include <cutils/properties.h>
57#include <logwrap/logwrap.h>
58
59#define VDBG 1 // STOPSHIP if true
60
ludi4072ff22017-06-15 08:56:52 -070061using android::netdutils::Fd;
62using android::netdutils::Slice;
63using android::netdutils::Status;
64using android::netdutils::StatusOr;
65using android::netdutils::Syscalls;
66
Nathan Harold1a371532017-01-30 12:30:48 -080067namespace android {
68namespace net {
69
Nathan Harold39b5df42017-08-02 18:45:25 -070070// Exposed for testing
Nathan Harold1a371532017-01-30 12:30:48 -080071constexpr uint32_t ALGO_MASK_AUTH_ALL = ~0;
Nathan Harold39b5df42017-08-02 18:45:25 -070072// Exposed for testing
Nathan Harold1a371532017-01-30 12:30:48 -080073constexpr uint32_t ALGO_MASK_CRYPT_ALL = ~0;
Nathan Harold39b5df42017-08-02 18:45:25 -070074// Exposed for testing
Benedict Wongbe65b432017-08-22 21:43:14 -070075constexpr uint32_t ALGO_MASK_AEAD_ALL = ~0;
76// Exposed for testing
Nathan Harold1a371532017-01-30 12:30:48 -080077constexpr uint8_t REPLAY_WINDOW_SIZE = 4;
78
Nathan Harold39b5df42017-08-02 18:45:25 -070079namespace {
80
Nathan Harold1a371532017-01-30 12:30:48 -080081constexpr uint32_t RAND_SPI_MIN = 1;
82constexpr uint32_t RAND_SPI_MAX = 0xFFFFFFFE;
83
84constexpr uint32_t INVALID_SPI = 0;
85
86#define XFRM_MSG_TRANS(x) \
87 case x: \
88 return #x;
89
90const char* xfrmMsgTypeToString(uint16_t msg) {
91 switch (msg) {
92 XFRM_MSG_TRANS(XFRM_MSG_NEWSA)
93 XFRM_MSG_TRANS(XFRM_MSG_DELSA)
94 XFRM_MSG_TRANS(XFRM_MSG_GETSA)
95 XFRM_MSG_TRANS(XFRM_MSG_NEWPOLICY)
96 XFRM_MSG_TRANS(XFRM_MSG_DELPOLICY)
97 XFRM_MSG_TRANS(XFRM_MSG_GETPOLICY)
98 XFRM_MSG_TRANS(XFRM_MSG_ALLOCSPI)
99 XFRM_MSG_TRANS(XFRM_MSG_ACQUIRE)
100 XFRM_MSG_TRANS(XFRM_MSG_EXPIRE)
101 XFRM_MSG_TRANS(XFRM_MSG_UPDPOLICY)
102 XFRM_MSG_TRANS(XFRM_MSG_UPDSA)
103 XFRM_MSG_TRANS(XFRM_MSG_POLEXPIRE)
104 XFRM_MSG_TRANS(XFRM_MSG_FLUSHSA)
105 XFRM_MSG_TRANS(XFRM_MSG_FLUSHPOLICY)
106 XFRM_MSG_TRANS(XFRM_MSG_NEWAE)
107 XFRM_MSG_TRANS(XFRM_MSG_GETAE)
108 XFRM_MSG_TRANS(XFRM_MSG_REPORT)
109 XFRM_MSG_TRANS(XFRM_MSG_MIGRATE)
110 XFRM_MSG_TRANS(XFRM_MSG_NEWSADINFO)
111 XFRM_MSG_TRANS(XFRM_MSG_GETSADINFO)
112 XFRM_MSG_TRANS(XFRM_MSG_GETSPDINFO)
113 XFRM_MSG_TRANS(XFRM_MSG_NEWSPDINFO)
114 XFRM_MSG_TRANS(XFRM_MSG_MAPPING)
115 default:
116 return "XFRM_MSG UNKNOWN";
117 }
118}
119
120// actually const but cannot be declared as such for reasons
121uint8_t kPadBytesArray[] = {0, 0, 0};
122void* kPadBytes = static_cast<void*>(kPadBytesArray);
123
124#if VDBG
Nathan Harold420ceac2017-04-05 19:36:59 -0700125#define LOG_HEX(__desc16__, __buf__, __len__) \
126 do { \
127 logHex(__desc16__, __buf__, __len__); \
128 } while (0)
ludie51e3862017-08-15 19:28:12 -0700129#define LOG_IOV(__iov__) \
Nathan Harold420ceac2017-04-05 19:36:59 -0700130 do { \
ludie51e3862017-08-15 19:28:12 -0700131 logIov(__iov__); \
Nathan Harold420ceac2017-04-05 19:36:59 -0700132 } while (0)
Nathan Harold1a371532017-01-30 12:30:48 -0800133
134void logHex(const char* desc16, const char* buf, size_t len) {
135 char* printBuf = new char[len * 2 + 1 + 26]; // len->ascii, +newline, +prefix strlen
136 int offset = 0;
137 if (desc16) {
138 sprintf(printBuf, "{%-16s}", desc16);
139 offset += 18; // prefix string length
140 }
141 sprintf(printBuf + offset, "[%4.4u]: ", (len > 9999) ? 9999 : (unsigned)len);
142 offset += 8;
143
144 for (uint32_t j = 0; j < (uint32_t)len; j++) {
145 sprintf(&printBuf[j * 2 + offset], "%0.2x", buf[j]);
146 }
147 ALOGD("%s", printBuf);
148 delete[] printBuf;
149}
150
ludie51e3862017-08-15 19:28:12 -0700151void logIov(const std::vector<iovec>& iov) {
152 for (const iovec& row : iov) {
153 logHex(0, reinterpret_cast<char*>(row.iov_base), row.iov_len);
Nathan Harold1a371532017-01-30 12:30:48 -0800154 }
155}
156
ludi6e8eccd2017-08-14 14:40:37 -0700157// TODO: Need to consider a way to refer to the sSycalls instance
ludi4072ff22017-06-15 08:56:52 -0700158inline Syscalls& getSyscallInstance() { return netdutils::sSyscalls.get(); }
159
Nathan Harold1a371532017-01-30 12:30:48 -0800160#else
161#define LOG_HEX(__desc16__, __buf__, __len__)
162#define LOG_IOV(__iov__, __iov_len__)
163#endif
164
165class XfrmSocketImpl : public XfrmSocket {
166private:
167 static constexpr int NLMSG_DEFAULTSIZE = 8192;
168
169 union NetlinkResponse {
170 nlmsghdr hdr;
171 struct _err_ {
172 nlmsghdr hdr;
173 nlmsgerr err;
174 } err;
175
176 struct _buf_ {
177 nlmsghdr hdr;
178 char buf[NLMSG_DEFAULTSIZE];
179 } buf;
180 };
181
182public:
ludi6e8eccd2017-08-14 14:40:37 -0700183 netdutils::Status open() override {
Nathan Harold1a371532017-01-30 12:30:48 -0800184 mSock = openNetlinkSocket(NETLINK_XFRM);
ludi6e8eccd2017-08-14 14:40:37 -0700185 if (mSock < 0) {
Nathan Harold1a371532017-01-30 12:30:48 -0800186 ALOGW("Could not get a new socket, line=%d", __LINE__);
ludi6e8eccd2017-08-14 14:40:37 -0700187 return netdutils::statusFromErrno(-mSock, "Could not open netlink socket");
Nathan Harold1a371532017-01-30 12:30:48 -0800188 }
189
ludi6e8eccd2017-08-14 14:40:37 -0700190 return netdutils::status::ok;
Nathan Harold1a371532017-01-30 12:30:48 -0800191 }
192
ludi6e8eccd2017-08-14 14:40:37 -0700193 static netdutils::Status validateResponse(NetlinkResponse response, size_t len) {
Nathan Harold1a371532017-01-30 12:30:48 -0800194 if (len < sizeof(nlmsghdr)) {
195 ALOGW("Invalid response message received over netlink");
ludi6e8eccd2017-08-14 14:40:37 -0700196 return netdutils::statusFromErrno(EBADMSG, "Invalid message");
Nathan Harold1a371532017-01-30 12:30:48 -0800197 }
198
199 switch (response.hdr.nlmsg_type) {
200 case NLMSG_NOOP:
201 case NLMSG_DONE:
ludi6e8eccd2017-08-14 14:40:37 -0700202 return netdutils::status::ok;
Nathan Harold1a371532017-01-30 12:30:48 -0800203 case NLMSG_OVERRUN:
204 ALOGD("Netlink request overran kernel buffer");
ludi6e8eccd2017-08-14 14:40:37 -0700205 return netdutils::statusFromErrno(EBADMSG, "Kernel buffer overrun");
Nathan Harold1a371532017-01-30 12:30:48 -0800206 case NLMSG_ERROR:
207 if (len < sizeof(NetlinkResponse::_err_)) {
208 ALOGD("Netlink message received malformed error response");
ludi6e8eccd2017-08-14 14:40:37 -0700209 return netdutils::statusFromErrno(EBADMSG, "Malformed error response");
Nathan Harold1a371532017-01-30 12:30:48 -0800210 }
ludi6e8eccd2017-08-14 14:40:37 -0700211 return netdutils::statusFromErrno(
212 -response.err.err.error,
213 "Error netlink message"); // Netlink errors are negative errno.
Nathan Harold1a371532017-01-30 12:30:48 -0800214 case XFRM_MSG_NEWSA:
215 break;
216 }
217
218 if (response.hdr.nlmsg_type < XFRM_MSG_BASE /*== NLMSG_MIN_TYPE*/ ||
219 response.hdr.nlmsg_type > XFRM_MSG_MAX) {
220 ALOGD("Netlink message responded with an out-of-range message ID");
ludi6e8eccd2017-08-14 14:40:37 -0700221 return netdutils::statusFromErrno(EBADMSG, "Invalid message ID");
Nathan Harold1a371532017-01-30 12:30:48 -0800222 }
223
224 // TODO Add more message validation here
ludi6e8eccd2017-08-14 14:40:37 -0700225 return netdutils::status::ok;
Nathan Harold1a371532017-01-30 12:30:48 -0800226 }
227
ludi6e8eccd2017-08-14 14:40:37 -0700228 netdutils::Status sendMessage(uint16_t nlMsgType, uint16_t nlMsgFlags, uint16_t nlMsgSeqNum,
229 std::vector<iovec>* iovecs) const override {
Nathan Harold1a371532017-01-30 12:30:48 -0800230 nlmsghdr nlMsg = {
231 .nlmsg_type = nlMsgType, .nlmsg_flags = nlMsgFlags, .nlmsg_seq = nlMsgSeqNum,
232 };
233
ludie51e3862017-08-15 19:28:12 -0700234 (*iovecs)[0].iov_base = &nlMsg;
235 (*iovecs)[0].iov_len = NLMSG_HDRLEN;
236 for (const iovec& iov : *iovecs) {
237 nlMsg.nlmsg_len += iov.iov_len;
Nathan Harold1a371532017-01-30 12:30:48 -0800238 }
239
240 ALOGD("Sending Netlink XFRM Message: %s", xfrmMsgTypeToString(nlMsgType));
241 if (VDBG)
ludie51e3862017-08-15 19:28:12 -0700242 LOG_IOV(*iovecs);
Nathan Harold1a371532017-01-30 12:30:48 -0800243
ludie51e3862017-08-15 19:28:12 -0700244 StatusOr<size_t> writeResult = getSyscallInstance().writev(mSock, *iovecs);
ludi4072ff22017-06-15 08:56:52 -0700245 if (!isOk(writeResult)) {
246 ALOGE("netlink socket writev failed (%s)", toString(writeResult).c_str());
ludi6e8eccd2017-08-14 14:40:37 -0700247 return writeResult;
Nathan Harold1a371532017-01-30 12:30:48 -0800248 }
249
ludi4072ff22017-06-15 08:56:52 -0700250 if (nlMsg.nlmsg_len != writeResult.value()) {
251 ALOGE("Invalid netlink message length sent %d", static_cast<int>(writeResult.value()));
ludi6e8eccd2017-08-14 14:40:37 -0700252 return netdutils::statusFromErrno(EBADMSG, "Invalid message length");
Nathan Harold1a371532017-01-30 12:30:48 -0800253 }
254
ludi4072ff22017-06-15 08:56:52 -0700255 NetlinkResponse response = {};
Nathan Harold1a371532017-01-30 12:30:48 -0800256
ludi4072ff22017-06-15 08:56:52 -0700257 StatusOr<Slice> readResult =
258 getSyscallInstance().read(Fd(mSock), netdutils::makeSlice(response));
259 if (!isOk(readResult)) {
260 ALOGE("netlink response error (%s)", toString(readResult).c_str());
ludi6e8eccd2017-08-14 14:40:37 -0700261 return readResult;
ludi4072ff22017-06-15 08:56:52 -0700262 }
263
264 LOG_HEX("netlink msg resp", reinterpret_cast<char*>(readResult.value().base()),
265 readResult.value().size());
266
ludi6e8eccd2017-08-14 14:40:37 -0700267 Status validateStatus = validateResponse(response, readResult.value().size());
268 if (!isOk(validateStatus)) {
269 ALOGE("netlink response contains error (%s)", toString(validateStatus).c_str());
270 }
271
272 return validateStatus;
Nathan Harold1a371532017-01-30 12:30:48 -0800273 }
274};
275
ludi6e8eccd2017-08-14 14:40:37 -0700276StatusOr<int> convertToXfrmAddr(const std::string& strAddr, xfrm_address_t* xfrmAddr) {
Nathan Harold1a371532017-01-30 12:30:48 -0800277 if (strAddr.length() == 0) {
278 memset(xfrmAddr, 0, sizeof(*xfrmAddr));
279 return AF_UNSPEC;
280 }
281
282 if (inet_pton(AF_INET6, strAddr.c_str(), reinterpret_cast<void*>(xfrmAddr))) {
283 return AF_INET6;
284 } else if (inet_pton(AF_INET, strAddr.c_str(), reinterpret_cast<void*>(xfrmAddr))) {
285 return AF_INET;
286 } else {
ludi6e8eccd2017-08-14 14:40:37 -0700287 return netdutils::statusFromErrno(EAFNOSUPPORT, "Invalid address family");
Nathan Harold1a371532017-01-30 12:30:48 -0800288 }
289}
290
291void fillXfrmNlaHdr(nlattr* hdr, uint16_t type, uint16_t len) {
292 hdr->nla_type = type;
293 hdr->nla_len = len;
294}
295
296void fillXfrmCurLifetimeDefaults(xfrm_lifetime_cur* cur) {
297 memset(reinterpret_cast<char*>(cur), 0, sizeof(*cur));
298}
299void fillXfrmLifetimeDefaults(xfrm_lifetime_cfg* cfg) {
300 cfg->soft_byte_limit = XFRM_INF;
301 cfg->hard_byte_limit = XFRM_INF;
302 cfg->soft_packet_limit = XFRM_INF;
303 cfg->hard_packet_limit = XFRM_INF;
304}
305
306/*
307 * Allocate SPIs within an (inclusive) range of min-max.
308 * returns 0 (INVALID_SPI) once the entire range has been parsed.
309 */
310class RandomSpi {
311public:
312 RandomSpi(int min, int max) : mMin(min) {
313 time_t t;
314 srand((unsigned int)time(&t));
315 // TODO: more random random
316 mNext = rand();
317 mSize = max - min + 1;
318 mCount = mSize;
319 }
320
321 uint32_t next() {
322 if (!mCount)
323 return 0;
324 mCount--;
325 return (mNext++ % mSize) + mMin;
326 }
327
328private:
329 uint32_t mNext;
330 uint32_t mSize;
331 uint32_t mMin;
332 uint32_t mCount;
333};
334
335} // namespace
336
337//
338// Begin XfrmController Impl
339//
340//
341XfrmController::XfrmController(void) {}
342
ludi6e8eccd2017-08-14 14:40:37 -0700343netdutils::Status XfrmController::ipSecAllocateSpi(int32_t transformId, int32_t direction,
344 const std::string& localAddress,
345 const std::string& remoteAddress, int32_t inSpi,
346 int32_t* outSpi) {
Nathan Harold1a371532017-01-30 12:30:48 -0800347 ALOGD("XfrmController:%s, line=%d", __FUNCTION__, __LINE__);
348 ALOGD("transformId=%d", transformId);
349 ALOGD("direction=%d", direction);
350 ALOGD("localAddress=%s", localAddress.c_str());
351 ALOGD("remoteAddress=%s", remoteAddress.c_str());
352 ALOGD("inSpi=%0.8x", inSpi);
353
354 XfrmSaInfo saInfo{};
Nathan Harold1a371532017-01-30 12:30:48 -0800355
ludi6e8eccd2017-08-14 14:40:37 -0700356 netdutils::Status ret =
357 fillXfrmSaId(direction, localAddress, remoteAddress, INVALID_SPI, &saInfo);
358 if (!isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800359 return ret;
360 }
361
362 XfrmSocketImpl sock;
ludi6e8eccd2017-08-14 14:40:37 -0700363 netdutils::Status socketStatus = sock.open();
364 if (!isOk(socketStatus)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800365 ALOGD("Sock open failed for XFRM, line=%d", __LINE__);
ludi6e8eccd2017-08-14 14:40:37 -0700366 return socketStatus;
Nathan Harold1a371532017-01-30 12:30:48 -0800367 }
368
369 int minSpi = RAND_SPI_MIN, maxSpi = RAND_SPI_MAX;
370
371 if (inSpi)
372 minSpi = maxSpi = inSpi;
ludi6e8eccd2017-08-14 14:40:37 -0700373
Nathan Harold1a371532017-01-30 12:30:48 -0800374 ret = allocateSpi(saInfo, minSpi, maxSpi, reinterpret_cast<uint32_t*>(outSpi), sock);
ludi6e8eccd2017-08-14 14:40:37 -0700375 if (!isOk(ret)) {
376 // TODO: May want to return a new Status with a modified status string
Nathan Harold1a371532017-01-30 12:30:48 -0800377 ALOGD("Failed to Allocate an SPI, line=%d", __LINE__);
378 *outSpi = INVALID_SPI;
379 }
380
381 return ret;
382}
383
ludi6e8eccd2017-08-14 14:40:37 -0700384netdutils::Status XfrmController::ipSecAddSecurityAssociation(
Nathan Harold1a371532017-01-30 12:30:48 -0800385 int32_t transformId, int32_t mode, int32_t direction, const std::string& localAddress,
Nathan Harold420ceac2017-04-05 19:36:59 -0700386 const std::string& remoteAddress, int64_t underlyingNetworkHandle, int32_t spi,
Nathan Harold1a371532017-01-30 12:30:48 -0800387 const std::string& authAlgo, const std::vector<uint8_t>& authKey, int32_t authTruncBits,
388 const std::string& cryptAlgo, const std::vector<uint8_t>& cryptKey, int32_t cryptTruncBits,
Benedict Wongbe65b432017-08-22 21:43:14 -0700389 const std::string& aeadAlgo, const std::vector<uint8_t>& aeadKey, int32_t aeadIcvBits,
ludiec836052017-05-20 14:17:05 -0700390 int32_t encapType, int32_t encapLocalPort, int32_t encapRemotePort) {
Nathan Harold1a371532017-01-30 12:30:48 -0800391 android::RWLock::AutoWLock lock(mLock);
392
393 ALOGD("XfrmController::%s, line=%d", __FUNCTION__, __LINE__);
394 ALOGD("transformId=%d", transformId);
395 ALOGD("mode=%d", mode);
396 ALOGD("direction=%d", direction);
397 ALOGD("localAddress=%s", localAddress.c_str());
398 ALOGD("remoteAddress=%s", remoteAddress.c_str());
Nathan Harold420ceac2017-04-05 19:36:59 -0700399 ALOGD("underlyingNetworkHandle=%" PRIx64, underlyingNetworkHandle);
Nathan Harold1a371532017-01-30 12:30:48 -0800400 ALOGD("spi=%0.8x", spi);
401 ALOGD("authAlgo=%s", authAlgo.c_str());
402 ALOGD("authTruncBits=%d", authTruncBits);
403 ALOGD("cryptAlgo=%s", cryptAlgo.c_str());
404 ALOGD("cryptTruncBits=%d,", cryptTruncBits);
Benedict Wongbe65b432017-08-22 21:43:14 -0700405 ALOGD("aeadAlgo=%s", aeadAlgo.c_str());
406 ALOGD("aeadIcvBits=%d,", aeadIcvBits);
Nathan Harold1a371532017-01-30 12:30:48 -0800407 ALOGD("encapType=%d", encapType);
408 ALOGD("encapLocalPort=%d", encapLocalPort);
409 ALOGD("encapRemotePort=%d", encapRemotePort);
410
411 XfrmSaInfo saInfo{};
ludi6e8eccd2017-08-14 14:40:37 -0700412 netdutils::Status ret = fillXfrmSaId(direction, localAddress, remoteAddress, spi, &saInfo);
413 if (!isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800414 return ret;
415 }
416
417 saInfo.transformId = transformId;
418
419 // STOPSHIP : range check the key lengths to prevent puncturing and overflow
420 saInfo.auth = XfrmAlgo{
421 .name = authAlgo, .key = authKey, .truncLenBits = static_cast<uint16_t>(authTruncBits)};
422
423 saInfo.crypt = XfrmAlgo{
424 .name = cryptAlgo, .key = cryptKey, .truncLenBits = static_cast<uint16_t>(cryptTruncBits)};
425
Benedict Wongbe65b432017-08-22 21:43:14 -0700426 saInfo.aead = XfrmAlgo{
427 .name = aeadAlgo, .key = aeadKey, .truncLenBits = static_cast<uint16_t>(aeadIcvBits)};
428
Nathan Harold1a371532017-01-30 12:30:48 -0800429 saInfo.direction = static_cast<XfrmDirection>(direction);
430
431 switch (static_cast<XfrmMode>(mode)) {
432 case XfrmMode::TRANSPORT:
433 case XfrmMode::TUNNEL:
434 saInfo.mode = static_cast<XfrmMode>(mode);
435 break;
436 default:
ludi6e8eccd2017-08-14 14:40:37 -0700437 return netdutils::statusFromErrno(EINVAL, "Invalid xfrm mode");
Nathan Harold1a371532017-01-30 12:30:48 -0800438 }
439
440 XfrmSocketImpl sock;
ludi6e8eccd2017-08-14 14:40:37 -0700441 netdutils::Status socketStatus = sock.open();
442 if (!isOk(socketStatus)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800443 ALOGD("Sock open failed for XFRM, line=%d", __LINE__);
ludi6e8eccd2017-08-14 14:40:37 -0700444 return socketStatus;
Nathan Harold1a371532017-01-30 12:30:48 -0800445 }
446
Nathan Harold420ceac2017-04-05 19:36:59 -0700447 switch (static_cast<XfrmEncapType>(encapType)) {
448 case XfrmEncapType::ESPINUDP:
449 case XfrmEncapType::ESPINUDP_NON_IKE:
450 if (saInfo.addrFamily != AF_INET) {
ludi6e8eccd2017-08-14 14:40:37 -0700451 return netdutils::statusFromErrno(EAFNOSUPPORT, "IPv6 encap not supported");
Nathan Harold420ceac2017-04-05 19:36:59 -0700452 }
453 switch (saInfo.direction) {
454 case XfrmDirection::IN:
455 saInfo.encap.srcPort = encapRemotePort;
456 saInfo.encap.dstPort = encapLocalPort;
457 break;
458 case XfrmDirection::OUT:
459 saInfo.encap.srcPort = encapLocalPort;
460 saInfo.encap.dstPort = encapRemotePort;
461 break;
462 default:
ludi6e8eccd2017-08-14 14:40:37 -0700463 return netdutils::statusFromErrno(EINVAL, "Invalid direction");
Nathan Harold420ceac2017-04-05 19:36:59 -0700464 }
465 // fall through
466 case XfrmEncapType::NONE:
467 saInfo.encap.type = static_cast<XfrmEncapType>(encapType);
468 break;
469 default:
ludi6e8eccd2017-08-14 14:40:37 -0700470 return netdutils::statusFromErrno(EINVAL, "Invalid encap type");
Nathan Harold420ceac2017-04-05 19:36:59 -0700471 }
472
Nathan Harold1a371532017-01-30 12:30:48 -0800473 ret = createTransportModeSecurityAssociation(saInfo, sock);
ludi6e8eccd2017-08-14 14:40:37 -0700474 if (!isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800475 ALOGD("Failed creating a Security Association, line=%d", __LINE__);
Nathan Harold1a371532017-01-30 12:30:48 -0800476 }
477
ludi6e8eccd2017-08-14 14:40:37 -0700478 return ret;
Nathan Harold1a371532017-01-30 12:30:48 -0800479}
480
ludi6e8eccd2017-08-14 14:40:37 -0700481netdutils::Status XfrmController::ipSecDeleteSecurityAssociation(int32_t transformId,
482 int32_t direction,
483 const std::string& localAddress,
484 const std::string& remoteAddress,
485 int32_t spi) {
Nathan Harold1a371532017-01-30 12:30:48 -0800486 ALOGD("XfrmController:%s, line=%d", __FUNCTION__, __LINE__);
487 ALOGD("transformId=%d", transformId);
488 ALOGD("direction=%d", direction);
489 ALOGD("localAddress=%s", localAddress.c_str());
490 ALOGD("remoteAddress=%s", remoteAddress.c_str());
491 ALOGD("spi=%0.8x", spi);
492
Jonathan Basseriebdaa682017-09-14 16:33:08 -0700493 XfrmSaId saId{};
ludi6e8eccd2017-08-14 14:40:37 -0700494 netdutils::Status ret = fillXfrmSaId(direction, localAddress, remoteAddress, spi, &saId);
495 if (!isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800496 return ret;
497 }
498
499 XfrmSocketImpl sock;
ludi6e8eccd2017-08-14 14:40:37 -0700500 netdutils::Status socketStatus = sock.open();
501 if (!isOk(socketStatus)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800502 ALOGD("Sock open failed for XFRM, line=%d", __LINE__);
ludi6e8eccd2017-08-14 14:40:37 -0700503 return socketStatus;
Nathan Harold1a371532017-01-30 12:30:48 -0800504 }
505
506 ret = deleteSecurityAssociation(saId, sock);
ludi6e8eccd2017-08-14 14:40:37 -0700507 if (!isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800508 ALOGD("Failed to delete Security Association, line=%d", __LINE__);
Nathan Harold1a371532017-01-30 12:30:48 -0800509 }
510
511 return ret;
512}
513
ludi6e8eccd2017-08-14 14:40:37 -0700514netdutils::Status XfrmController::fillXfrmSaId(int32_t direction, const std::string& localAddress,
515 const std::string& remoteAddress, int32_t spi,
516 XfrmSaId* xfrmId) {
Nathan Harold1a371532017-01-30 12:30:48 -0800517 xfrm_address_t localXfrmAddr{}, remoteXfrmAddr{};
518
ludi6e8eccd2017-08-14 14:40:37 -0700519 StatusOr<int> addrFamilyLocal, addrFamilyRemote;
Nathan Harold1a371532017-01-30 12:30:48 -0800520 addrFamilyRemote = convertToXfrmAddr(remoteAddress, &remoteXfrmAddr);
521 addrFamilyLocal = convertToXfrmAddr(localAddress, &localXfrmAddr);
ludi6e8eccd2017-08-14 14:40:37 -0700522 if (!isOk(addrFamilyRemote) || !isOk(addrFamilyLocal)) {
523 return netdutils::statusFromErrno(EINVAL,
524 "Invalid address " + localAddress + "/" + remoteAddress);
Nathan Harold1a371532017-01-30 12:30:48 -0800525 }
526
ludi6e8eccd2017-08-14 14:40:37 -0700527 if (addrFamilyRemote.value() == AF_UNSPEC ||
528 (addrFamilyLocal.value() != AF_UNSPEC &&
529 addrFamilyLocal.value() != addrFamilyRemote.value())) {
530 ALOGD("Invalid or Mismatched Address Families, %d != %d, line=%d", addrFamilyLocal.value(),
531 addrFamilyRemote.value(), __LINE__);
532 return netdutils::statusFromErrno(EINVAL, "Invalid or mismatched address families");
Nathan Harold1a371532017-01-30 12:30:48 -0800533 }
534
ludi6e8eccd2017-08-14 14:40:37 -0700535 xfrmId->addrFamily = addrFamilyRemote.value();
Nathan Harold1a371532017-01-30 12:30:48 -0800536
537 xfrmId->spi = htonl(spi);
538
539 switch (static_cast<XfrmDirection>(direction)) {
540 case XfrmDirection::IN:
541 xfrmId->dstAddr = localXfrmAddr;
542 xfrmId->srcAddr = remoteXfrmAddr;
543 break;
544
545 case XfrmDirection::OUT:
546 xfrmId->dstAddr = remoteXfrmAddr;
547 xfrmId->srcAddr = localXfrmAddr;
548 break;
549
550 default:
551 ALOGD("Invalid XFRM direction, line=%d", __LINE__);
552 // Invalid direction for Transport mode transform: time to bail
ludi6e8eccd2017-08-14 14:40:37 -0700553 return netdutils::statusFromErrno(EINVAL, "Invalid direction");
Nathan Harold1a371532017-01-30 12:30:48 -0800554 }
ludi6e8eccd2017-08-14 14:40:37 -0700555 return netdutils::status::ok;
Nathan Harold1a371532017-01-30 12:30:48 -0800556}
557
ludi6e8eccd2017-08-14 14:40:37 -0700558netdutils::Status XfrmController::ipSecApplyTransportModeTransform(
559 const android::base::unique_fd& socket, int32_t transformId, int32_t direction,
560 const std::string& localAddress, const std::string& remoteAddress, int32_t spi) {
Nathan Harold1a371532017-01-30 12:30:48 -0800561 ALOGD("XfrmController::%s, line=%d", __FUNCTION__, __LINE__);
562 ALOGD("transformId=%d", transformId);
563 ALOGD("direction=%d", direction);
564 ALOGD("localAddress=%s", localAddress.c_str());
565 ALOGD("remoteAddress=%s", remoteAddress.c_str());
566 ALOGD("spi=%0.8x", spi);
567
568 struct sockaddr_storage saddr;
569
ludi4072ff22017-06-15 08:56:52 -0700570 StatusOr<sockaddr_storage> ret = getSyscallInstance().getsockname<sockaddr_storage>(Fd(socket));
571 if (!isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800572 ALOGE("Failed to get socket info in %s", __FUNCTION__);
ludi6e8eccd2017-08-14 14:40:37 -0700573 return ret;
Nathan Harold1a371532017-01-30 12:30:48 -0800574 }
575
ludi4072ff22017-06-15 08:56:52 -0700576 saddr = ret.value();
577
Nathan Harold1a371532017-01-30 12:30:48 -0800578 XfrmSaInfo saInfo{};
579 saInfo.transformId = transformId;
580 saInfo.direction = static_cast<XfrmDirection>(direction);
581 saInfo.spi = spi;
582
ludi6e8eccd2017-08-14 14:40:37 -0700583 netdutils::Status status = fillXfrmSaId(direction, localAddress, remoteAddress, spi, &saInfo);
584 if (!isOk(status)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800585 ALOGE("Couldn't build SA ID %s", __FUNCTION__);
ludi6e8eccd2017-08-14 14:40:37 -0700586 return status;
Nathan Harold1a371532017-01-30 12:30:48 -0800587 }
588
589 if (saInfo.addrFamily != saddr.ss_family) {
590 ALOGE("Transform address family(%d) differs from socket address "
Nathan Harold420ceac2017-04-05 19:36:59 -0700591 "family(%d)!",
592 saInfo.addrFamily, saddr.ss_family);
ludi6e8eccd2017-08-14 14:40:37 -0700593 return netdutils::statusFromErrno(EINVAL, "Mismatched address family");
Nathan Harold1a371532017-01-30 12:30:48 -0800594 }
595
596 struct {
597 xfrm_userpolicy_info info;
598 xfrm_user_tmpl tmpl;
599 } policy{};
600
601 fillTransportModeUserSpInfo(saInfo, &policy.info);
602 fillUserTemplate(saInfo, &policy.tmpl);
603
604 LOG_HEX("XfrmUserPolicy", reinterpret_cast<char*>(&policy), sizeof(policy));
605
606 int sockOpt, sockLayer;
607 switch (saInfo.addrFamily) {
608 case AF_INET:
609 sockOpt = IP_XFRM_POLICY;
610 sockLayer = SOL_IP;
611 break;
612 case AF_INET6:
613 sockOpt = IPV6_XFRM_POLICY;
614 sockLayer = SOL_IPV6;
615 break;
616 default:
ludi6e8eccd2017-08-14 14:40:37 -0700617 return netdutils::statusFromErrno(EAFNOSUPPORT, "Invalid address family");
Nathan Harold1a371532017-01-30 12:30:48 -0800618 }
619
ludi6e8eccd2017-08-14 14:40:37 -0700620 status = getSyscallInstance().setsockopt(Fd(socket), sockLayer, sockOpt, policy);
ludi4072ff22017-06-15 08:56:52 -0700621 if (!isOk(status)) {
622 ALOGE("Error setting socket option for XFRM! (%s)", toString(status).c_str());
Nathan Harold1a371532017-01-30 12:30:48 -0800623 }
ludi6e8eccd2017-08-14 14:40:37 -0700624
625 return status;
Nathan Harold1a371532017-01-30 12:30:48 -0800626}
627
ludi6e8eccd2017-08-14 14:40:37 -0700628netdutils::Status
629XfrmController::ipSecRemoveTransportModeTransform(const android::base::unique_fd& socket) {
Nathan Harold1a371532017-01-30 12:30:48 -0800630 (void)socket;
ludi6e8eccd2017-08-14 14:40:37 -0700631 return netdutils::status::ok;
Nathan Harold1a371532017-01-30 12:30:48 -0800632}
633
634void XfrmController::fillTransportModeSelector(const XfrmSaInfo& record, xfrm_selector* selector) {
635 selector->family = record.addrFamily;
636 selector->proto = AF_UNSPEC; // TODO: do we need to match the protocol? it's
637 // possible via the socket
638 selector->ifindex = record.netId; // TODO : still need to sort this out
639}
640
ludi6e8eccd2017-08-14 14:40:37 -0700641netdutils::Status XfrmController::createTransportModeSecurityAssociation(const XfrmSaInfo& record,
642 const XfrmSocket& sock) {
Nathan Harold1a371532017-01-30 12:30:48 -0800643 xfrm_usersa_info usersa{};
644 nlattr_algo_crypt crypt{};
645 nlattr_algo_auth auth{};
Benedict Wongbe65b432017-08-22 21:43:14 -0700646 nlattr_algo_aead aead{};
Nathan Harold420ceac2017-04-05 19:36:59 -0700647 nlattr_encap_tmpl encap{};
Nathan Harold1a371532017-01-30 12:30:48 -0800648
Benedict Wongbe65b432017-08-22 21:43:14 -0700649 enum {
650 NLMSG_HDR,
651 USERSA,
652 USERSA_PAD,
653 CRYPT,
654 CRYPT_PAD,
655 AUTH,
656 AUTH_PAD,
657 AEAD,
658 AEAD_PAD,
659 ENCAP,
660 ENCAP_PAD
661 };
Nathan Harold1a371532017-01-30 12:30:48 -0800662
ludie51e3862017-08-15 19:28:12 -0700663 std::vector<iovec> iov = {
Nathan Harold1a371532017-01-30 12:30:48 -0800664 {NULL, 0}, // reserved for the eventual addition of a NLMSG_HDR
665 {&usersa, 0}, // main usersa_info struct
666 {kPadBytes, 0}, // up to NLMSG_ALIGNTO pad bytes of padding
667 {&crypt, 0}, // adjust size if crypt algo is present
668 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
669 {&auth, 0}, // adjust size if auth algo is present
670 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
Benedict Wongbe65b432017-08-22 21:43:14 -0700671 {&aead, 0}, // adjust size if aead algo is present
672 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
673 {&encap, 0}, // adjust size if encapsulating
Nathan Harold420ceac2017-04-05 19:36:59 -0700674 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
Nathan Harold1a371532017-01-30 12:30:48 -0800675 };
676
Benedict Wongbe65b432017-08-22 21:43:14 -0700677 if (!record.aead.name.empty() && (!record.auth.name.empty() || !record.crypt.name.empty())) {
678 return netdutils::statusFromErrno(EINVAL, "Invalid xfrm algo selection; AEAD is mutually "
679 "exclusive with both Authentication and "
680 "Encryption");
681 }
682
Benedict Wong4f60ee12017-10-10 12:27:25 -0700683 if (record.aead.key.size() > MAX_KEY_LENGTH || record.auth.key.size() > MAX_KEY_LENGTH ||
684 record.crypt.key.size() > MAX_KEY_LENGTH) {
685 return netdutils::statusFromErrno(EINVAL, "Key length invalid; exceeds MAX_KEY_LENGTH");
Benedict Wongbe65b432017-08-22 21:43:14 -0700686 }
687
Nathan Harold1a371532017-01-30 12:30:48 -0800688 int len;
689 len = iov[USERSA].iov_len = fillUserSaInfo(record, &usersa);
690 iov[USERSA_PAD].iov_len = NLMSG_ALIGN(len) - len;
691
692 len = iov[CRYPT].iov_len = fillNlAttrXfrmAlgoEnc(record.crypt, &crypt);
693 iov[CRYPT_PAD].iov_len = NLA_ALIGN(len) - len;
694
695 len = iov[AUTH].iov_len = fillNlAttrXfrmAlgoAuth(record.auth, &auth);
696 iov[AUTH_PAD].iov_len = NLA_ALIGN(len) - len;
697
Benedict Wongbe65b432017-08-22 21:43:14 -0700698 len = iov[AEAD].iov_len = fillNlAttrXfrmAlgoAead(record.aead, &aead);
699 iov[AEAD_PAD].iov_len = NLA_ALIGN(len) - len;
700
Nathan Harold420ceac2017-04-05 19:36:59 -0700701 len = iov[ENCAP].iov_len = fillNlAttrXfrmEncapTmpl(record, &encap);
702 iov[ENCAP_PAD].iov_len = NLA_ALIGN(len) - len;
ludie51e3862017-08-15 19:28:12 -0700703 return sock.sendMessage(XFRM_MSG_UPDSA, NETLINK_REQUEST_FLAGS, 0, &iov);
Nathan Harold1a371532017-01-30 12:30:48 -0800704}
705
706int XfrmController::fillNlAttrXfrmAlgoEnc(const XfrmAlgo& inAlgo, nlattr_algo_crypt* algo) {
Benedict Wongbe65b432017-08-22 21:43:14 -0700707 if (inAlgo.name.empty()) { // Do not fill anything if algorithm not provided
708 return 0;
709 }
710
Nathan Harold1a371532017-01-30 12:30:48 -0800711 int len = NLA_HDRLEN + sizeof(xfrm_algo);
Benedict Wongbe65b432017-08-22 21:43:14 -0700712 // Kernel always changes last char to null terminator; no safety checks needed.
Nathan Harold1a371532017-01-30 12:30:48 -0800713 strncpy(algo->crypt.alg_name, inAlgo.name.c_str(), sizeof(algo->crypt.alg_name));
714 algo->crypt.alg_key_len = inAlgo.key.size() * 8; // bits
Benedict Wongbe65b432017-08-22 21:43:14 -0700715 memcpy(algo->key, &inAlgo.key[0], inAlgo.key.size());
Nathan Harold1a371532017-01-30 12:30:48 -0800716 len += inAlgo.key.size();
717 fillXfrmNlaHdr(&algo->hdr, XFRMA_ALG_CRYPT, len);
718 return len;
719}
720
721int XfrmController::fillNlAttrXfrmAlgoAuth(const XfrmAlgo& inAlgo, nlattr_algo_auth* algo) {
Benedict Wongbe65b432017-08-22 21:43:14 -0700722 if (inAlgo.name.empty()) { // Do not fill anything if algorithm not provided
723 return 0;
724 }
725
Nathan Harold1a371532017-01-30 12:30:48 -0800726 int len = NLA_HDRLEN + sizeof(xfrm_algo_auth);
Benedict Wongbe65b432017-08-22 21:43:14 -0700727 // Kernel always changes last char to null terminator; no safety checks needed.
Nathan Harold1a371532017-01-30 12:30:48 -0800728 strncpy(algo->auth.alg_name, inAlgo.name.c_str(), sizeof(algo->auth.alg_name));
729 algo->auth.alg_key_len = inAlgo.key.size() * 8; // bits
730
731 // This is the extra field for ALG_AUTH_TRUNC
732 algo->auth.alg_trunc_len = inAlgo.truncLenBits;
733
Benedict Wongbe65b432017-08-22 21:43:14 -0700734 memcpy(algo->key, &inAlgo.key[0], inAlgo.key.size());
Nathan Harold1a371532017-01-30 12:30:48 -0800735 len += inAlgo.key.size();
736
737 fillXfrmNlaHdr(&algo->hdr, XFRMA_ALG_AUTH_TRUNC, len);
738 return len;
739}
740
Benedict Wongbe65b432017-08-22 21:43:14 -0700741int XfrmController::fillNlAttrXfrmAlgoAead(const XfrmAlgo& inAlgo, nlattr_algo_aead* algo) {
742 if (inAlgo.name.empty()) { // Do not fill anything if algorithm not provided
743 return 0;
744 }
745
746 int len = NLA_HDRLEN + sizeof(xfrm_algo_aead);
747 // Kernel always changes last char to null terminator; no safety checks needed.
748 strncpy(algo->aead.alg_name, inAlgo.name.c_str(), sizeof(algo->aead.alg_name));
749 algo->aead.alg_key_len = inAlgo.key.size() * 8; // bits
750
751 // This is the extra field for ALG_AEAD. ICV length is the same as truncation length
752 // for any AEAD algorithm.
753 algo->aead.alg_icv_len = inAlgo.truncLenBits;
754
755 memcpy(algo->key, &inAlgo.key[0], inAlgo.key.size());
756 len += inAlgo.key.size();
757
758 fillXfrmNlaHdr(&algo->hdr, XFRMA_ALG_AEAD, len);
759 return len;
760}
761
Nathan Harold420ceac2017-04-05 19:36:59 -0700762int XfrmController::fillNlAttrXfrmEncapTmpl(const XfrmSaInfo& record, nlattr_encap_tmpl* tmpl) {
763 if (record.encap.type == XfrmEncapType::NONE) {
764 return 0;
765 }
766
767 int len = NLA_HDRLEN + sizeof(xfrm_encap_tmpl);
768 tmpl->tmpl.encap_type = static_cast<uint16_t>(record.encap.type);
769 tmpl->tmpl.encap_sport = htons(record.encap.srcPort);
770 tmpl->tmpl.encap_dport = htons(record.encap.dstPort);
771 fillXfrmNlaHdr(&tmpl->hdr, XFRMA_ENCAP, len);
772 return len;
773}
774
Nathan Harold1a371532017-01-30 12:30:48 -0800775int XfrmController::fillUserSaInfo(const XfrmSaInfo& record, xfrm_usersa_info* usersa) {
776 fillTransportModeSelector(record, &usersa->sel);
777
778 usersa->id.proto = IPPROTO_ESP;
779 usersa->id.spi = record.spi;
780 usersa->id.daddr = record.dstAddr;
781
782 usersa->saddr = record.srcAddr;
783
784 fillXfrmLifetimeDefaults(&usersa->lft);
785 fillXfrmCurLifetimeDefaults(&usersa->curlft);
786 memset(&usersa->stats, 0, sizeof(usersa->stats)); // leave stats zeroed out
787 usersa->reqid = record.transformId;
788 usersa->family = record.addrFamily;
789 usersa->mode = static_cast<uint8_t>(record.mode);
790 usersa->replay_window = REPLAY_WINDOW_SIZE;
791 usersa->flags = 0; // TODO: should we actually set flags, XFRM_SA_XFLAG_DONT_ENCAP_DSCP?
792 return sizeof(*usersa);
793}
794
795int XfrmController::fillUserSaId(const XfrmSaId& record, xfrm_usersa_id* said) {
796 said->daddr = record.dstAddr;
797 said->spi = record.spi;
798 said->family = record.addrFamily;
799 said->proto = IPPROTO_ESP;
800
801 return sizeof(*said);
802}
803
ludi6e8eccd2017-08-14 14:40:37 -0700804netdutils::Status XfrmController::deleteSecurityAssociation(const XfrmSaId& record,
805 const XfrmSocket& sock) {
Nathan Harold1a371532017-01-30 12:30:48 -0800806 xfrm_usersa_id said{};
807
ludie51e3862017-08-15 19:28:12 -0700808 enum { NLMSG_HDR, USERSAID, USERSAID_PAD };
Nathan Harold1a371532017-01-30 12:30:48 -0800809
ludie51e3862017-08-15 19:28:12 -0700810 std::vector<iovec> iov = {
Nathan Harold1a371532017-01-30 12:30:48 -0800811 {NULL, 0}, // reserved for the eventual addition of a NLMSG_HDR
812 {&said, 0}, // main usersa_info struct
813 {kPadBytes, 0}, // up to NLMSG_ALIGNTO pad bytes of padding
814 };
815
816 int len;
817 len = iov[USERSAID].iov_len = fillUserSaId(record, &said);
818 iov[USERSAID_PAD].iov_len = NLMSG_ALIGN(len) - len;
819
ludie51e3862017-08-15 19:28:12 -0700820 return sock.sendMessage(XFRM_MSG_DELSA, NETLINK_REQUEST_FLAGS, 0, &iov);
Nathan Harold1a371532017-01-30 12:30:48 -0800821}
822
ludi6e8eccd2017-08-14 14:40:37 -0700823netdutils::Status XfrmController::allocateSpi(const XfrmSaInfo& record, uint32_t minSpi,
824 uint32_t maxSpi, uint32_t* outSpi,
825 const XfrmSocket& sock) {
Nathan Harold1a371532017-01-30 12:30:48 -0800826 xfrm_userspi_info spiInfo{};
827
ludie51e3862017-08-15 19:28:12 -0700828 enum { NLMSG_HDR, USERSAID, USERSAID_PAD };
Nathan Harold1a371532017-01-30 12:30:48 -0800829
ludie51e3862017-08-15 19:28:12 -0700830 std::vector<iovec> iov = {
Nathan Harold1a371532017-01-30 12:30:48 -0800831 {NULL, 0}, // reserved for the eventual addition of a NLMSG_HDR
832 {&spiInfo, 0}, // main userspi_info struct
833 {kPadBytes, 0}, // up to NLMSG_ALIGNTO pad bytes of padding
834 };
835
836 int len;
837 if (fillUserSaInfo(record, &spiInfo.info) == 0) {
838 ALOGE("Failed to fill transport SA Info");
839 }
840
841 len = iov[USERSAID].iov_len = sizeof(spiInfo);
842 iov[USERSAID_PAD].iov_len = NLMSG_ALIGN(len) - len;
843
844 RandomSpi spiGen = RandomSpi(minSpi, maxSpi);
ludi6e8eccd2017-08-14 14:40:37 -0700845 int spi;
846 netdutils::Status ret;
Nathan Harold1a371532017-01-30 12:30:48 -0800847 while ((spi = spiGen.next()) != INVALID_SPI) {
848 spiInfo.min = spi;
849 spiInfo.max = spi;
ludie51e3862017-08-15 19:28:12 -0700850 ret = sock.sendMessage(XFRM_MSG_ALLOCSPI, NETLINK_REQUEST_FLAGS, 0, &iov);
Nathan Harold1a371532017-01-30 12:30:48 -0800851
852 /* If the SPI is in use, we'll get ENOENT */
ludi6e8eccd2017-08-14 14:40:37 -0700853 if (netdutils::equalToErrno(ret, ENOENT))
Nathan Harold1a371532017-01-30 12:30:48 -0800854 continue;
855
ludi6e8eccd2017-08-14 14:40:37 -0700856 if (isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800857 *outSpi = spi;
Nathan Harold420ceac2017-04-05 19:36:59 -0700858 ALOGD("Allocated an SPI: %x", *outSpi);
Nathan Harold1a371532017-01-30 12:30:48 -0800859 } else {
860 *outSpi = INVALID_SPI;
ludi6e8eccd2017-08-14 14:40:37 -0700861 ALOGE("SPI Allocation Failed with error %d", ret.code());
Nathan Harold1a371532017-01-30 12:30:48 -0800862 }
863
864 return ret;
865 }
866
867 // Should always be -ENOENT if we get here
868 return ret;
869}
870
871int XfrmController::fillTransportModeUserSpInfo(const XfrmSaInfo& record,
872 xfrm_userpolicy_info* usersp) {
873 fillTransportModeSelector(record, &usersp->sel);
874 fillXfrmLifetimeDefaults(&usersp->lft);
875 fillXfrmCurLifetimeDefaults(&usersp->curlft);
Nathan Harold420ceac2017-04-05 19:36:59 -0700876 /* if (index) index & 0x3 == dir -- must be true
877 * xfrm_user.c:verify_newpolicy_info() */
Nathan Harold1a371532017-01-30 12:30:48 -0800878 usersp->index = 0;
879 usersp->dir = static_cast<uint8_t>(record.direction);
880 usersp->action = XFRM_POLICY_ALLOW;
881 usersp->flags = XFRM_POLICY_LOCALOK;
882 usersp->share = XFRM_SHARE_UNIQUE;
883 return sizeof(*usersp);
884}
885
886int XfrmController::fillUserTemplate(const XfrmSaInfo& record, xfrm_user_tmpl* tmpl) {
887 tmpl->id.daddr = record.dstAddr;
888 tmpl->id.spi = record.spi;
889 tmpl->id.proto = IPPROTO_ESP;
890
891 tmpl->family = record.addrFamily;
892 tmpl->saddr = record.srcAddr;
893 tmpl->reqid = record.transformId;
894 tmpl->mode = static_cast<uint8_t>(record.mode);
895 tmpl->share = XFRM_SHARE_UNIQUE;
896 tmpl->optional = 0; // if this is true, then a failed state lookup will be considered OK:
897 // http://lxr.free-electrons.com/source/net/xfrm/xfrm_policy.c#L1492
898 tmpl->aalgos = ALGO_MASK_AUTH_ALL; // TODO: if there's a bitmask somewhere of
899 // algos, we should find it and apply it.
900 // I can't find one.
901 tmpl->ealgos = ALGO_MASK_CRYPT_ALL; // TODO: if there's a bitmask somewhere...
902 return 0;
903}
904
905} // namespace net
906} // namespace android