blob: cc2c3054a266901bf0e0530c3202d7730220c852 [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
Nathan Harold1e284452017-10-10 13:31:19 -070018#include <random>
Nathan Harold7441c692017-12-12 21:25:01 -080019#include <string>
Nathan Harold1a371532017-01-30 12:30:48 -080020#include <vector>
21
22#include <ctype.h>
23#include <errno.h>
24#include <fcntl.h>
25#include <getopt.h>
26#include <stdio.h>
27#include <stdlib.h>
28#include <string.h>
Nathan Harold420ceac2017-04-05 19:36:59 -070029
30#define __STDC_FORMAT_MACROS
Nathan Harold1a371532017-01-30 12:30:48 -080031#include <inttypes.h>
32
33#include <arpa/inet.h>
34#include <netinet/in.h>
35
36#include <sys/socket.h>
37#include <sys/stat.h>
38#include <sys/types.h>
39#include <sys/wait.h>
40
41#include <linux/in.h>
42#include <linux/netlink.h>
43#include <linux/xfrm.h>
44
45#include "android-base/stringprintf.h"
46#include "android-base/strings.h"
47#include "android-base/unique_fd.h"
Manojd9c93c22017-10-19 13:40:26 -070048#include <log/log_properties.h>
Nathan Harold1a371532017-01-30 12:30:48 -080049#define LOG_TAG "XfrmController"
50#include "NetdConstants.h"
51#include "NetlinkCommands.h"
52#include "ResponseCode.h"
53#include "XfrmController.h"
ludi4072ff22017-06-15 08:56:52 -070054#include "netdutils/Fd.h"
55#include "netdutils/Slice.h"
56#include "netdutils/Syscalls.h"
Nathan Harold1a371532017-01-30 12:30:48 -080057#include <cutils/log.h>
58#include <cutils/properties.h>
59#include <logwrap/logwrap.h>
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
Nathan Harold420ceac2017-04-05 19:36:59 -0700124#define LOG_HEX(__desc16__, __buf__, __len__) \
Manojd9c93c22017-10-19 13:40:26 -0700125 if (__android_log_is_debuggable()) { \
126 do { \
127 logHex(__desc16__, __buf__, __len__); \
Nathan Harold7441c692017-12-12 21:25:01 -0800128 } while (0); \
Manojd9c93c22017-10-19 13:40:26 -0700129 }
130
ludie51e3862017-08-15 19:28:12 -0700131#define LOG_IOV(__iov__) \
Manojd9c93c22017-10-19 13:40:26 -0700132 if (__android_log_is_debuggable()) { \
133 do { \
134 logIov(__iov__); \
Nathan Harold7441c692017-12-12 21:25:01 -0800135 } while (0); \
136 }
Nathan Harold1a371532017-01-30 12:30:48 -0800137
138void logHex(const char* desc16, const char* buf, size_t len) {
139 char* printBuf = new char[len * 2 + 1 + 26]; // len->ascii, +newline, +prefix strlen
140 int offset = 0;
141 if (desc16) {
142 sprintf(printBuf, "{%-16s}", desc16);
143 offset += 18; // prefix string length
144 }
145 sprintf(printBuf + offset, "[%4.4u]: ", (len > 9999) ? 9999 : (unsigned)len);
146 offset += 8;
147
148 for (uint32_t j = 0; j < (uint32_t)len; j++) {
149 sprintf(&printBuf[j * 2 + offset], "%0.2x", buf[j]);
150 }
151 ALOGD("%s", printBuf);
152 delete[] printBuf;
153}
154
ludie51e3862017-08-15 19:28:12 -0700155void logIov(const std::vector<iovec>& iov) {
156 for (const iovec& row : iov) {
157 logHex(0, reinterpret_cast<char*>(row.iov_base), row.iov_len);
Nathan Harold1a371532017-01-30 12:30:48 -0800158 }
159}
160
manojboopathi8707f232018-01-02 14:45:47 -0800161size_t fillNlAttr(__u16 nlaType, size_t valueSize, nlattr* nlAttr) {
162 size_t dataLen = valueSize;
163 int padLength = NLMSG_ALIGN(dataLen) - dataLen;
164 nlAttr->nla_len = (__u16)(dataLen + sizeof(nlattr));
165 nlAttr->nla_type = nlaType;
166 return padLength;
167}
168
169size_t fillNlAttrIpAddress(__u16 nlaType, int family, const std::string& value, nlattr* nlAttr,
170 Slice ipAddress) {
171 inet_pton(family, value.c_str(), ipAddress.base());
172 return fillNlAttr(nlaType, (family == AF_INET) ? sizeof(in_addr) : sizeof(in6_addr), nlAttr);
173}
174
175size_t fillNlAttrU32(__u16 nlaType, int32_t value, nlattr* nlAttr, uint32_t* u32Value) {
176 *u32Value = htonl(value);
177 return fillNlAttr(nlaType, sizeof((*u32Value)), nlAttr);
178}
179
180// returns the address family, placing the string in the provided buffer
181StatusOr<uint16_t> convertStringAddress(std::string addr, uint8_t* buffer) {
182 if (inet_pton(AF_INET, addr.c_str(), buffer) == 1) {
183 return AF_INET;
184 } else if (inet_pton(AF_INET6, addr.c_str(), buffer) == 1) {
185 return AF_INET6;
186 } else {
187 return Status(EAFNOSUPPORT);
188 }
189}
190
ludi6e8eccd2017-08-14 14:40:37 -0700191// TODO: Need to consider a way to refer to the sSycalls instance
ludi4072ff22017-06-15 08:56:52 -0700192inline Syscalls& getSyscallInstance() { return netdutils::sSyscalls.get(); }
193
Nathan Harold1a371532017-01-30 12:30:48 -0800194class XfrmSocketImpl : public XfrmSocket {
195private:
196 static constexpr int NLMSG_DEFAULTSIZE = 8192;
197
198 union NetlinkResponse {
199 nlmsghdr hdr;
200 struct _err_ {
201 nlmsghdr hdr;
202 nlmsgerr err;
203 } err;
204
205 struct _buf_ {
206 nlmsghdr hdr;
207 char buf[NLMSG_DEFAULTSIZE];
208 } buf;
209 };
210
211public:
ludi6e8eccd2017-08-14 14:40:37 -0700212 netdutils::Status open() override {
Nathan Harold1a371532017-01-30 12:30:48 -0800213 mSock = openNetlinkSocket(NETLINK_XFRM);
ludi6e8eccd2017-08-14 14:40:37 -0700214 if (mSock < 0) {
Nathan Harold1a371532017-01-30 12:30:48 -0800215 ALOGW("Could not get a new socket, line=%d", __LINE__);
ludi6e8eccd2017-08-14 14:40:37 -0700216 return netdutils::statusFromErrno(-mSock, "Could not open netlink socket");
Nathan Harold1a371532017-01-30 12:30:48 -0800217 }
218
ludi6e8eccd2017-08-14 14:40:37 -0700219 return netdutils::status::ok;
Nathan Harold1a371532017-01-30 12:30:48 -0800220 }
221
ludi6e8eccd2017-08-14 14:40:37 -0700222 static netdutils::Status validateResponse(NetlinkResponse response, size_t len) {
Nathan Harold1a371532017-01-30 12:30:48 -0800223 if (len < sizeof(nlmsghdr)) {
224 ALOGW("Invalid response message received over netlink");
ludi6e8eccd2017-08-14 14:40:37 -0700225 return netdutils::statusFromErrno(EBADMSG, "Invalid message");
Nathan Harold1a371532017-01-30 12:30:48 -0800226 }
227
228 switch (response.hdr.nlmsg_type) {
229 case NLMSG_NOOP:
230 case NLMSG_DONE:
ludi6e8eccd2017-08-14 14:40:37 -0700231 return netdutils::status::ok;
Nathan Harold1a371532017-01-30 12:30:48 -0800232 case NLMSG_OVERRUN:
233 ALOGD("Netlink request overran kernel buffer");
ludi6e8eccd2017-08-14 14:40:37 -0700234 return netdutils::statusFromErrno(EBADMSG, "Kernel buffer overrun");
Nathan Harold1a371532017-01-30 12:30:48 -0800235 case NLMSG_ERROR:
236 if (len < sizeof(NetlinkResponse::_err_)) {
237 ALOGD("Netlink message received malformed error response");
ludi6e8eccd2017-08-14 14:40:37 -0700238 return netdutils::statusFromErrno(EBADMSG, "Malformed error response");
Nathan Harold1a371532017-01-30 12:30:48 -0800239 }
ludi6e8eccd2017-08-14 14:40:37 -0700240 return netdutils::statusFromErrno(
241 -response.err.err.error,
242 "Error netlink message"); // Netlink errors are negative errno.
Nathan Harold1a371532017-01-30 12:30:48 -0800243 case XFRM_MSG_NEWSA:
244 break;
245 }
246
247 if (response.hdr.nlmsg_type < XFRM_MSG_BASE /*== NLMSG_MIN_TYPE*/ ||
248 response.hdr.nlmsg_type > XFRM_MSG_MAX) {
249 ALOGD("Netlink message responded with an out-of-range message ID");
ludi6e8eccd2017-08-14 14:40:37 -0700250 return netdutils::statusFromErrno(EBADMSG, "Invalid message ID");
Nathan Harold1a371532017-01-30 12:30:48 -0800251 }
252
253 // TODO Add more message validation here
ludi6e8eccd2017-08-14 14:40:37 -0700254 return netdutils::status::ok;
Nathan Harold1a371532017-01-30 12:30:48 -0800255 }
256
ludi6e8eccd2017-08-14 14:40:37 -0700257 netdutils::Status sendMessage(uint16_t nlMsgType, uint16_t nlMsgFlags, uint16_t nlMsgSeqNum,
258 std::vector<iovec>* iovecs) const override {
Nathan Harold1a371532017-01-30 12:30:48 -0800259 nlmsghdr nlMsg = {
Nathan Harold7441c692017-12-12 21:25:01 -0800260 .nlmsg_type = nlMsgType,
261 .nlmsg_flags = nlMsgFlags,
262 .nlmsg_seq = nlMsgSeqNum,
Nathan Harold1a371532017-01-30 12:30:48 -0800263 };
264
ludie51e3862017-08-15 19:28:12 -0700265 (*iovecs)[0].iov_base = &nlMsg;
266 (*iovecs)[0].iov_len = NLMSG_HDRLEN;
267 for (const iovec& iov : *iovecs) {
268 nlMsg.nlmsg_len += iov.iov_len;
Nathan Harold1a371532017-01-30 12:30:48 -0800269 }
270
271 ALOGD("Sending Netlink XFRM Message: %s", xfrmMsgTypeToString(nlMsgType));
Manojd9c93c22017-10-19 13:40:26 -0700272 LOG_IOV(*iovecs);
Nathan Harold1a371532017-01-30 12:30:48 -0800273
ludie51e3862017-08-15 19:28:12 -0700274 StatusOr<size_t> writeResult = getSyscallInstance().writev(mSock, *iovecs);
ludi4072ff22017-06-15 08:56:52 -0700275 if (!isOk(writeResult)) {
276 ALOGE("netlink socket writev failed (%s)", toString(writeResult).c_str());
ludi6e8eccd2017-08-14 14:40:37 -0700277 return writeResult;
Nathan Harold1a371532017-01-30 12:30:48 -0800278 }
279
ludi4072ff22017-06-15 08:56:52 -0700280 if (nlMsg.nlmsg_len != writeResult.value()) {
281 ALOGE("Invalid netlink message length sent %d", static_cast<int>(writeResult.value()));
ludi6e8eccd2017-08-14 14:40:37 -0700282 return netdutils::statusFromErrno(EBADMSG, "Invalid message length");
Nathan Harold1a371532017-01-30 12:30:48 -0800283 }
284
ludi4072ff22017-06-15 08:56:52 -0700285 NetlinkResponse response = {};
Nathan Harold1a371532017-01-30 12:30:48 -0800286
ludi4072ff22017-06-15 08:56:52 -0700287 StatusOr<Slice> readResult =
288 getSyscallInstance().read(Fd(mSock), netdutils::makeSlice(response));
289 if (!isOk(readResult)) {
290 ALOGE("netlink response error (%s)", toString(readResult).c_str());
ludi6e8eccd2017-08-14 14:40:37 -0700291 return readResult;
ludi4072ff22017-06-15 08:56:52 -0700292 }
293
294 LOG_HEX("netlink msg resp", reinterpret_cast<char*>(readResult.value().base()),
295 readResult.value().size());
296
ludi6e8eccd2017-08-14 14:40:37 -0700297 Status validateStatus = validateResponse(response, readResult.value().size());
298 if (!isOk(validateStatus)) {
299 ALOGE("netlink response contains error (%s)", toString(validateStatus).c_str());
300 }
301
302 return validateStatus;
Nathan Harold1a371532017-01-30 12:30:48 -0800303 }
304};
305
ludi6e8eccd2017-08-14 14:40:37 -0700306StatusOr<int> convertToXfrmAddr(const std::string& strAddr, xfrm_address_t* xfrmAddr) {
Nathan Harold1a371532017-01-30 12:30:48 -0800307 if (strAddr.length() == 0) {
308 memset(xfrmAddr, 0, sizeof(*xfrmAddr));
309 return AF_UNSPEC;
310 }
311
312 if (inet_pton(AF_INET6, strAddr.c_str(), reinterpret_cast<void*>(xfrmAddr))) {
313 return AF_INET6;
314 } else if (inet_pton(AF_INET, strAddr.c_str(), reinterpret_cast<void*>(xfrmAddr))) {
315 return AF_INET;
316 } else {
ludi6e8eccd2017-08-14 14:40:37 -0700317 return netdutils::statusFromErrno(EAFNOSUPPORT, "Invalid address family");
Nathan Harold1a371532017-01-30 12:30:48 -0800318 }
319}
320
321void fillXfrmNlaHdr(nlattr* hdr, uint16_t type, uint16_t len) {
322 hdr->nla_type = type;
323 hdr->nla_len = len;
324}
325
326void fillXfrmCurLifetimeDefaults(xfrm_lifetime_cur* cur) {
327 memset(reinterpret_cast<char*>(cur), 0, sizeof(*cur));
328}
329void fillXfrmLifetimeDefaults(xfrm_lifetime_cfg* cfg) {
330 cfg->soft_byte_limit = XFRM_INF;
331 cfg->hard_byte_limit = XFRM_INF;
332 cfg->soft_packet_limit = XFRM_INF;
333 cfg->hard_packet_limit = XFRM_INF;
334}
335
336/*
337 * Allocate SPIs within an (inclusive) range of min-max.
338 * returns 0 (INVALID_SPI) once the entire range has been parsed.
339 */
340class RandomSpi {
341public:
342 RandomSpi(int min, int max) : mMin(min) {
Nathan Harold1e284452017-10-10 13:31:19 -0700343 // Re-seeding should be safe because the seed itself is
344 // sufficiently random and we don't need secure random
345 std::mt19937 rnd = std::mt19937(std::random_device()());
346 mNext = std::uniform_int_distribution<>(1, INT_MAX)(rnd);
Nathan Harold1a371532017-01-30 12:30:48 -0800347 mSize = max - min + 1;
348 mCount = mSize;
349 }
350
351 uint32_t next() {
352 if (!mCount)
353 return 0;
354 mCount--;
355 return (mNext++ % mSize) + mMin;
356 }
357
358private:
359 uint32_t mNext;
360 uint32_t mSize;
361 uint32_t mMin;
362 uint32_t mCount;
363};
364
365} // namespace
366
367//
368// Begin XfrmController Impl
369//
370//
371XfrmController::XfrmController(void) {}
372
Benedict Wongb2daefb2017-12-06 22:05:46 -0800373netdutils::Status XfrmController::ipSecSetEncapSocketOwner(const android::base::unique_fd& socket,
374 int newUid, uid_t callerUid) {
375 ALOGD("XfrmController:%s, line=%d", __FUNCTION__, __LINE__);
376
377 const int fd = socket.get();
378 struct stat info;
379 if (fstat(fd, &info)) {
380 return netdutils::statusFromErrno(errno, "Failed to stat socket file descriptor");
381 }
382 if (info.st_uid != callerUid) {
383 return netdutils::statusFromErrno(EPERM, "fchown disabled for non-owner calls");
384 }
Nathan Haroldda54f122018-01-09 16:42:57 -0800385 if (S_ISSOCK(info.st_mode) == 0) {
Benedict Wongb2daefb2017-12-06 22:05:46 -0800386 return netdutils::statusFromErrno(EINVAL, "File descriptor was not a socket");
387 }
388
389 int optval;
390 socklen_t optlen;
Nathan Haroldda54f122018-01-09 16:42:57 -0800391 netdutils::Status status =
392 getSyscallInstance().getsockopt(Fd(socket), IPPROTO_UDP, UDP_ENCAP, &optval, &optlen);
Benedict Wongb2daefb2017-12-06 22:05:46 -0800393 if (status != netdutils::status::ok) {
394 return status;
395 }
Nathan Haroldda54f122018-01-09 16:42:57 -0800396 if (optval != UDP_ENCAP_ESPINUDP && optval != UDP_ENCAP_ESPINUDP_NON_IKE) {
Benedict Wongb2daefb2017-12-06 22:05:46 -0800397 return netdutils::statusFromErrno(EINVAL, "Socket did not have UDP-encap sockopt set");
398 }
399 if (fchown(fd, newUid, -1)) {
400 return netdutils::statusFromErrno(errno, "Failed to fchown socket file descriptor");
401 }
402
403 return netdutils::status::ok;
404}
405
Nathan Haroldda54f122018-01-09 16:42:57 -0800406netdutils::Status XfrmController::ipSecAllocateSpi(int32_t transformId,
407 const std::string& sourceAddress,
408 const std::string& destinationAddress,
409 int32_t inSpi, int32_t* outSpi) {
Nathan Harold1a371532017-01-30 12:30:48 -0800410 ALOGD("XfrmController:%s, line=%d", __FUNCTION__, __LINE__);
411 ALOGD("transformId=%d", transformId);
Nathan Haroldda54f122018-01-09 16:42:57 -0800412 ALOGD("sourceAddress=%s", sourceAddress.c_str());
413 ALOGD("destinationAddress=%s", destinationAddress.c_str());
Nathan Harold1a371532017-01-30 12:30:48 -0800414 ALOGD("inSpi=%0.8x", inSpi);
415
416 XfrmSaInfo saInfo{};
ludi6e8eccd2017-08-14 14:40:37 -0700417 netdutils::Status ret =
Di Lu2ccb3e52018-01-03 16:19:20 -0800418 fillXfrmId(sourceAddress, destinationAddress, INVALID_SPI, 0, 0, transformId, &saInfo);
ludi6e8eccd2017-08-14 14:40:37 -0700419 if (!isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800420 return ret;
421 }
422
423 XfrmSocketImpl sock;
ludi6e8eccd2017-08-14 14:40:37 -0700424 netdutils::Status socketStatus = sock.open();
425 if (!isOk(socketStatus)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800426 ALOGD("Sock open failed for XFRM, line=%d", __LINE__);
ludi6e8eccd2017-08-14 14:40:37 -0700427 return socketStatus;
Nathan Harold1a371532017-01-30 12:30:48 -0800428 }
429
430 int minSpi = RAND_SPI_MIN, maxSpi = RAND_SPI_MAX;
431
432 if (inSpi)
433 minSpi = maxSpi = inSpi;
ludi6e8eccd2017-08-14 14:40:37 -0700434
Nathan Harold1a371532017-01-30 12:30:48 -0800435 ret = allocateSpi(saInfo, minSpi, maxSpi, reinterpret_cast<uint32_t*>(outSpi), sock);
ludi6e8eccd2017-08-14 14:40:37 -0700436 if (!isOk(ret)) {
437 // TODO: May want to return a new Status with a modified status string
Nathan Harold1a371532017-01-30 12:30:48 -0800438 ALOGD("Failed to Allocate an SPI, line=%d", __LINE__);
439 *outSpi = INVALID_SPI;
440 }
441
442 return ret;
443}
444
ludi6e8eccd2017-08-14 14:40:37 -0700445netdutils::Status XfrmController::ipSecAddSecurityAssociation(
Nathan Haroldda54f122018-01-09 16:42:57 -0800446 int32_t transformId, int32_t mode, const std::string& sourceAddress,
manojboopathi8707f232018-01-02 14:45:47 -0800447 const std::string& destinationAddress, int32_t underlyingNetId, int32_t spi, int32_t markValue,
448 int32_t markMask, const std::string& authAlgo, const std::vector<uint8_t>& authKey,
449 int32_t authTruncBits, const std::string& cryptAlgo, const std::vector<uint8_t>& cryptKey,
450 int32_t cryptTruncBits, const std::string& aeadAlgo, const std::vector<uint8_t>& aeadKey,
451 int32_t aeadIcvBits, int32_t encapType, int32_t encapLocalPort, int32_t encapRemotePort) {
Nathan Harold1a371532017-01-30 12:30:48 -0800452 ALOGD("XfrmController::%s, line=%d", __FUNCTION__, __LINE__);
453 ALOGD("transformId=%d", transformId);
454 ALOGD("mode=%d", mode);
Nathan Haroldda54f122018-01-09 16:42:57 -0800455 ALOGD("sourceAddress=%s", sourceAddress.c_str());
456 ALOGD("destinationAddress=%s", destinationAddress.c_str());
Benedict Wong96abf482018-01-22 13:56:41 -0800457 ALOGD("underlyingNetworkId=%d", underlyingNetId);
Nathan Harold1a371532017-01-30 12:30:48 -0800458 ALOGD("spi=%0.8x", spi);
Di Lu2ccb3e52018-01-03 16:19:20 -0800459 ALOGD("markValue=%x", markValue);
460 ALOGD("markMask=%x", markMask);
Nathan Harold1a371532017-01-30 12:30:48 -0800461 ALOGD("authAlgo=%s", authAlgo.c_str());
462 ALOGD("authTruncBits=%d", authTruncBits);
463 ALOGD("cryptAlgo=%s", cryptAlgo.c_str());
464 ALOGD("cryptTruncBits=%d,", cryptTruncBits);
Benedict Wongbe65b432017-08-22 21:43:14 -0700465 ALOGD("aeadAlgo=%s", aeadAlgo.c_str());
466 ALOGD("aeadIcvBits=%d,", aeadIcvBits);
Nathan Harold1a371532017-01-30 12:30:48 -0800467 ALOGD("encapType=%d", encapType);
468 ALOGD("encapLocalPort=%d", encapLocalPort);
469 ALOGD("encapRemotePort=%d", encapRemotePort);
470
471 XfrmSaInfo saInfo{};
Di Lu2ccb3e52018-01-03 16:19:20 -0800472 netdutils::Status ret = fillXfrmId(sourceAddress, destinationAddress, spi, markValue, markMask,
473 transformId, &saInfo);
ludi6e8eccd2017-08-14 14:40:37 -0700474 if (!isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800475 return ret;
476 }
477
Nathan Harold1a371532017-01-30 12:30:48 -0800478 saInfo.auth = XfrmAlgo{
479 .name = authAlgo, .key = authKey, .truncLenBits = static_cast<uint16_t>(authTruncBits)};
480
481 saInfo.crypt = XfrmAlgo{
482 .name = cryptAlgo, .key = cryptKey, .truncLenBits = static_cast<uint16_t>(cryptTruncBits)};
483
Benedict Wongbe65b432017-08-22 21:43:14 -0700484 saInfo.aead = XfrmAlgo{
485 .name = aeadAlgo, .key = aeadKey, .truncLenBits = static_cast<uint16_t>(aeadIcvBits)};
486
Nathan Harold1a371532017-01-30 12:30:48 -0800487 switch (static_cast<XfrmMode>(mode)) {
488 case XfrmMode::TRANSPORT:
489 case XfrmMode::TUNNEL:
490 saInfo.mode = static_cast<XfrmMode>(mode);
491 break;
492 default:
ludi6e8eccd2017-08-14 14:40:37 -0700493 return netdutils::statusFromErrno(EINVAL, "Invalid xfrm mode");
Nathan Harold1a371532017-01-30 12:30:48 -0800494 }
495
496 XfrmSocketImpl sock;
ludi6e8eccd2017-08-14 14:40:37 -0700497 netdutils::Status socketStatus = sock.open();
498 if (!isOk(socketStatus)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800499 ALOGD("Sock open failed for XFRM, line=%d", __LINE__);
ludi6e8eccd2017-08-14 14:40:37 -0700500 return socketStatus;
Nathan Harold1a371532017-01-30 12:30:48 -0800501 }
502
Nathan Harold420ceac2017-04-05 19:36:59 -0700503 switch (static_cast<XfrmEncapType>(encapType)) {
504 case XfrmEncapType::ESPINUDP:
505 case XfrmEncapType::ESPINUDP_NON_IKE:
506 if (saInfo.addrFamily != AF_INET) {
ludi6e8eccd2017-08-14 14:40:37 -0700507 return netdutils::statusFromErrno(EAFNOSUPPORT, "IPv6 encap not supported");
Nathan Harold420ceac2017-04-05 19:36:59 -0700508 }
Nathan Haroldda54f122018-01-09 16:42:57 -0800509 // The ports are not used on input SAs, so this is OK to be wrong when
510 // direction is ultimately input.
511 saInfo.encap.srcPort = encapLocalPort;
512 saInfo.encap.dstPort = encapRemotePort;
Nathan Harold420ceac2017-04-05 19:36:59 -0700513 // fall through
514 case XfrmEncapType::NONE:
515 saInfo.encap.type = static_cast<XfrmEncapType>(encapType);
516 break;
517 default:
ludi6e8eccd2017-08-14 14:40:37 -0700518 return netdutils::statusFromErrno(EINVAL, "Invalid encap type");
Nathan Harold420ceac2017-04-05 19:36:59 -0700519 }
520
Benedict Wong96abf482018-01-22 13:56:41 -0800521 saInfo.netId = underlyingNetId;
522
Di Lu0e16b5e2018-01-12 10:37:53 -0800523 ret = updateSecurityAssociation(saInfo, sock);
ludi6e8eccd2017-08-14 14:40:37 -0700524 if (!isOk(ret)) {
Di Lu0e16b5e2018-01-12 10:37:53 -0800525 ALOGD("Failed updating a Security Association, line=%d", __LINE__);
Nathan Harold1a371532017-01-30 12:30:48 -0800526 }
527
ludi6e8eccd2017-08-14 14:40:37 -0700528 return ret;
Nathan Harold1a371532017-01-30 12:30:48 -0800529}
530
Di Lu2ccb3e52018-01-03 16:19:20 -0800531netdutils::Status XfrmController::ipSecDeleteSecurityAssociation(
532 int32_t transformId, const std::string& sourceAddress, const std::string& destinationAddress,
533 int32_t spi, int32_t markValue, int32_t markMask) {
Nathan Harold1a371532017-01-30 12:30:48 -0800534 ALOGD("XfrmController:%s, line=%d", __FUNCTION__, __LINE__);
535 ALOGD("transformId=%d", transformId);
Nathan Haroldda54f122018-01-09 16:42:57 -0800536 ALOGD("sourceAddress=%s", sourceAddress.c_str());
537 ALOGD("destinationAddress=%s", destinationAddress.c_str());
Nathan Harold1a371532017-01-30 12:30:48 -0800538 ALOGD("spi=%0.8x", spi);
Di Lu2ccb3e52018-01-03 16:19:20 -0800539 ALOGD("markValue=%x", markValue);
540 ALOGD("markMask=%x", markMask);
Nathan Harold1a371532017-01-30 12:30:48 -0800541
Nathan Harold7441c692017-12-12 21:25:01 -0800542 XfrmId saId{};
Di Lu2ccb3e52018-01-03 16:19:20 -0800543 netdutils::Status ret =
544 fillXfrmId(sourceAddress, destinationAddress, spi, markValue, markMask, transformId, &saId);
ludi6e8eccd2017-08-14 14:40:37 -0700545 if (!isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800546 return ret;
547 }
548
549 XfrmSocketImpl sock;
ludi6e8eccd2017-08-14 14:40:37 -0700550 netdutils::Status socketStatus = sock.open();
551 if (!isOk(socketStatus)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800552 ALOGD("Sock open failed for XFRM, line=%d", __LINE__);
ludi6e8eccd2017-08-14 14:40:37 -0700553 return socketStatus;
Nathan Harold1a371532017-01-30 12:30:48 -0800554 }
555
556 ret = deleteSecurityAssociation(saId, sock);
ludi6e8eccd2017-08-14 14:40:37 -0700557 if (!isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800558 ALOGD("Failed to delete Security Association, line=%d", __LINE__);
Nathan Harold1a371532017-01-30 12:30:48 -0800559 }
560
561 return ret;
562}
563
Nathan Haroldda54f122018-01-09 16:42:57 -0800564netdutils::Status XfrmController::fillXfrmId(const std::string& sourceAddress,
565 const std::string& destinationAddress, int32_t spi,
Di Lu2ccb3e52018-01-03 16:19:20 -0800566 int32_t markValue, int32_t markMask,
Nathan Harold7441c692017-12-12 21:25:01 -0800567 int32_t transformId, XfrmId* xfrmId) {
568 // Fill the straightforward fields first
569 xfrmId->transformId = transformId;
Nathan Harold7441c692017-12-12 21:25:01 -0800570 xfrmId->spi = htonl(spi);
Di Lu2ccb3e52018-01-03 16:19:20 -0800571 xfrmId->mark.v = markValue;
572 xfrmId->mark.m = markMask;
Nathan Harold1a371532017-01-30 12:30:48 -0800573
Nathan Harold7441c692017-12-12 21:25:01 -0800574 // Use the addresses to determine the address family and do validation
Nathan Haroldda54f122018-01-09 16:42:57 -0800575 xfrm_address_t sourceXfrmAddr{}, destXfrmAddr{};
576 StatusOr<int> sourceFamily, destFamily;
577 sourceFamily = convertToXfrmAddr(sourceAddress, &sourceXfrmAddr);
578 destFamily = convertToXfrmAddr(destinationAddress, &destXfrmAddr);
579 if (!isOk(sourceFamily) || !isOk(destFamily)) {
580 return netdutils::statusFromErrno(EINVAL, "Invalid address " + sourceAddress + "/" +
581 destinationAddress);
Nathan Harold1a371532017-01-30 12:30:48 -0800582 }
583
Nathan Haroldda54f122018-01-09 16:42:57 -0800584 if (destFamily.value() == AF_UNSPEC ||
585 (sourceFamily.value() != AF_UNSPEC && sourceFamily.value() != destFamily.value())) {
586 ALOGD("Invalid or Mismatched Address Families, %d != %d, line=%d", sourceFamily.value(),
587 destFamily.value(), __LINE__);
ludi6e8eccd2017-08-14 14:40:37 -0700588 return netdutils::statusFromErrno(EINVAL, "Invalid or mismatched address families");
Nathan Harold1a371532017-01-30 12:30:48 -0800589 }
590
Nathan Haroldda54f122018-01-09 16:42:57 -0800591 xfrmId->addrFamily = destFamily.value();
Nathan Harold1a371532017-01-30 12:30:48 -0800592
Nathan Haroldda54f122018-01-09 16:42:57 -0800593 xfrmId->dstAddr = destXfrmAddr;
594 xfrmId->srcAddr = sourceXfrmAddr;
ludi6e8eccd2017-08-14 14:40:37 -0700595 return netdutils::status::ok;
Nathan Harold1a371532017-01-30 12:30:48 -0800596}
597
ludi6e8eccd2017-08-14 14:40:37 -0700598netdutils::Status XfrmController::ipSecApplyTransportModeTransform(
599 const android::base::unique_fd& socket, int32_t transformId, int32_t direction,
Nathan Haroldda54f122018-01-09 16:42:57 -0800600 const std::string& sourceAddress, const std::string& destinationAddress, int32_t spi) {
Nathan Harold1a371532017-01-30 12:30:48 -0800601 ALOGD("XfrmController::%s, line=%d", __FUNCTION__, __LINE__);
602 ALOGD("transformId=%d", transformId);
603 ALOGD("direction=%d", direction);
Nathan Haroldda54f122018-01-09 16:42:57 -0800604 ALOGD("sourceAddress=%s", sourceAddress.c_str());
605 ALOGD("destinationAddress=%s", destinationAddress.c_str());
Nathan Harold1a371532017-01-30 12:30:48 -0800606 ALOGD("spi=%0.8x", spi);
607
ludi4072ff22017-06-15 08:56:52 -0700608 StatusOr<sockaddr_storage> ret = getSyscallInstance().getsockname<sockaddr_storage>(Fd(socket));
609 if (!isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800610 ALOGE("Failed to get socket info in %s", __FUNCTION__);
ludi6e8eccd2017-08-14 14:40:37 -0700611 return ret;
Nathan Harold1a371532017-01-30 12:30:48 -0800612 }
Nathan Harold7441c692017-12-12 21:25:01 -0800613 struct sockaddr_storage saddr = ret.value();
ludi4072ff22017-06-15 08:56:52 -0700614
Nathan Harold1a371532017-01-30 12:30:48 -0800615 XfrmSaInfo saInfo{};
Nathan Harold7441c692017-12-12 21:25:01 -0800616 netdutils::Status status =
Di Lu2ccb3e52018-01-03 16:19:20 -0800617 fillXfrmId(sourceAddress, destinationAddress, spi, 0, 0, transformId, &saInfo);
ludi6e8eccd2017-08-14 14:40:37 -0700618 if (!isOk(status)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800619 ALOGE("Couldn't build SA ID %s", __FUNCTION__);
ludi6e8eccd2017-08-14 14:40:37 -0700620 return status;
Nathan Harold1a371532017-01-30 12:30:48 -0800621 }
622
manojboopathi26f42922017-12-14 10:51:57 -0800623 if (saddr.ss_family == AF_INET && saInfo.addrFamily != AF_INET) {
624 ALOGE("IPV4 socket address family(%d) should match IPV4 Transform "
625 "address family(%d)!",
626 saddr.ss_family, saInfo.addrFamily);
ludi6e8eccd2017-08-14 14:40:37 -0700627 return netdutils::statusFromErrno(EINVAL, "Mismatched address family");
Nathan Harold1a371532017-01-30 12:30:48 -0800628 }
629
630 struct {
631 xfrm_userpolicy_info info;
632 xfrm_user_tmpl tmpl;
633 } policy{};
634
Nathan Haroldda54f122018-01-09 16:42:57 -0800635 fillTransportModeUserSpInfo(saInfo, static_cast<XfrmDirection>(direction), &policy.info);
Nathan Harold1a371532017-01-30 12:30:48 -0800636 fillUserTemplate(saInfo, &policy.tmpl);
637
638 LOG_HEX("XfrmUserPolicy", reinterpret_cast<char*>(&policy), sizeof(policy));
639
640 int sockOpt, sockLayer;
manojboopathi26f42922017-12-14 10:51:57 -0800641 switch (saddr.ss_family) {
Nathan Harold1a371532017-01-30 12:30:48 -0800642 case AF_INET:
643 sockOpt = IP_XFRM_POLICY;
644 sockLayer = SOL_IP;
645 break;
646 case AF_INET6:
647 sockOpt = IPV6_XFRM_POLICY;
648 sockLayer = SOL_IPV6;
649 break;
650 default:
ludi6e8eccd2017-08-14 14:40:37 -0700651 return netdutils::statusFromErrno(EAFNOSUPPORT, "Invalid address family");
Nathan Harold1a371532017-01-30 12:30:48 -0800652 }
653
ludi6e8eccd2017-08-14 14:40:37 -0700654 status = getSyscallInstance().setsockopt(Fd(socket), sockLayer, sockOpt, policy);
ludi4072ff22017-06-15 08:56:52 -0700655 if (!isOk(status)) {
656 ALOGE("Error setting socket option for XFRM! (%s)", toString(status).c_str());
Nathan Harold1a371532017-01-30 12:30:48 -0800657 }
ludi6e8eccd2017-08-14 14:40:37 -0700658
659 return status;
Nathan Harold1a371532017-01-30 12:30:48 -0800660}
661
ludi6e8eccd2017-08-14 14:40:37 -0700662netdutils::Status
663XfrmController::ipSecRemoveTransportModeTransform(const android::base::unique_fd& socket) {
ludi87991632017-10-30 15:28:11 -0700664 ALOGD("XfrmController::%s, line=%d", __FUNCTION__, __LINE__);
665
666 StatusOr<sockaddr_storage> ret = getSyscallInstance().getsockname<sockaddr_storage>(Fd(socket));
667 if (!isOk(ret)) {
668 ALOGE("Failed to get socket info in %s! (%s)", __FUNCTION__, toString(ret).c_str());
669 return ret;
670 }
671
672 int sockOpt, sockLayer;
673 switch (ret.value().ss_family) {
674 case AF_INET:
675 sockOpt = IP_XFRM_POLICY;
676 sockLayer = SOL_IP;
677 break;
678 case AF_INET6:
679 sockOpt = IPV6_XFRM_POLICY;
680 sockLayer = SOL_IPV6;
681 break;
682 default:
683 return netdutils::statusFromErrno(EAFNOSUPPORT, "Invalid address family");
684 }
685
686 // Kernel will delete the security policy on this socket for both direction
687 // if optval is set to NULL and optlen is set to 0.
688 netdutils::Status status =
689 getSyscallInstance().setsockopt(Fd(socket), sockLayer, sockOpt, NULL, 0);
690 if (!isOk(status)) {
691 ALOGE("Error removing socket option for XFRM! (%s)", toString(status).c_str());
692 }
693
694 return status;
Nathan Harold1a371532017-01-30 12:30:48 -0800695}
696
ludi771b8002017-11-20 15:09:05 -0800697netdutils::Status XfrmController::ipSecAddSecurityPolicy(int32_t transformId, int32_t direction,
698 const std::string& localAddress,
699 const std::string& remoteAddress,
Di Lu2ccb3e52018-01-03 16:19:20 -0800700 int32_t spi, int32_t markValue,
701 int32_t markMask) {
ludi771b8002017-11-20 15:09:05 -0800702 return processSecurityPolicy(transformId, direction, localAddress, remoteAddress, spi,
Di Lu2ccb3e52018-01-03 16:19:20 -0800703 markValue, markMask, XFRM_MSG_NEWPOLICY);
ludi771b8002017-11-20 15:09:05 -0800704}
705
706netdutils::Status XfrmController::ipSecUpdateSecurityPolicy(int32_t transformId, int32_t direction,
707 const std::string& localAddress,
708 const std::string& remoteAddress,
Di Lu2ccb3e52018-01-03 16:19:20 -0800709 int32_t spi, int32_t markValue,
710 int32_t markMask) {
ludi771b8002017-11-20 15:09:05 -0800711 return processSecurityPolicy(transformId, direction, localAddress, remoteAddress, spi,
Di Lu2ccb3e52018-01-03 16:19:20 -0800712 markValue, markMask, XFRM_MSG_UPDPOLICY);
ludi771b8002017-11-20 15:09:05 -0800713}
714
715netdutils::Status XfrmController::ipSecDeleteSecurityPolicy(int32_t transformId, int32_t direction,
716 const std::string& localAddress,
Di Lu2ccb3e52018-01-03 16:19:20 -0800717 const std::string& remoteAddress,
718 int32_t markValue, int32_t markMask) {
manojboopathi8707f232018-01-02 14:45:47 -0800719 return processSecurityPolicy(transformId, direction, localAddress, remoteAddress, 0, markValue,
720 markMask, XFRM_MSG_DELPOLICY);
ludi771b8002017-11-20 15:09:05 -0800721}
722
723netdutils::Status XfrmController::processSecurityPolicy(int32_t transformId, int32_t direction,
724 const std::string& localAddress,
725 const std::string& remoteAddress,
Di Lu2ccb3e52018-01-03 16:19:20 -0800726 int32_t spi, int32_t markValue,
727 int32_t markMask, int32_t msgType) {
ludi771b8002017-11-20 15:09:05 -0800728 ALOGD("XfrmController::%s, line=%d", __FUNCTION__, __LINE__);
729 ALOGD("transformId=%d", transformId);
730 ALOGD("direction=%d", direction);
731 ALOGD("localAddress=%s", localAddress.c_str());
732 ALOGD("remoteAddress=%s", remoteAddress.c_str());
733 ALOGD("spi=%0.8x", spi);
Di Lu2ccb3e52018-01-03 16:19:20 -0800734 ALOGD("markValue=%d", markValue);
735 ALOGD("markMask=%d", markMask);
ludi771b8002017-11-20 15:09:05 -0800736 ALOGD("msgType=%d", msgType);
737
738 XfrmSaInfo saInfo{};
739 saInfo.mode = XfrmMode::TUNNEL;
740
741 XfrmSocketImpl sock;
742 RETURN_IF_NOT_OK(sock.open());
743
Di Lu2ccb3e52018-01-03 16:19:20 -0800744 RETURN_IF_NOT_OK(
745 fillXfrmId(localAddress, remoteAddress, spi, markValue, markMask, transformId, &saInfo));
ludi771b8002017-11-20 15:09:05 -0800746
747 if (msgType == XFRM_MSG_DELPOLICY) {
748 return deleteTunnelModeSecurityPolicy(saInfo, sock, static_cast<XfrmDirection>(direction));
749 } else {
750 return updateTunnelModeSecurityPolicy(saInfo, sock, static_cast<XfrmDirection>(direction),
751 msgType);
752 }
753}
754
755void XfrmController::fillXfrmSelector(const XfrmSaInfo& record, xfrm_selector* selector) {
Nathan Harold1a371532017-01-30 12:30:48 -0800756 selector->family = record.addrFamily;
manojboopathi8707f232018-01-02 14:45:47 -0800757 selector->proto = AF_UNSPEC; // TODO: do we need to match the protocol? it's
758 // possible via the socket
Nathan Harold1a371532017-01-30 12:30:48 -0800759}
760
Di Lu0e16b5e2018-01-12 10:37:53 -0800761netdutils::Status XfrmController::updateSecurityAssociation(const XfrmSaInfo& record,
manojboopathi4d2d6f12017-12-06 11:11:31 -0800762 const XfrmSocket& sock) {
Nathan Harold1a371532017-01-30 12:30:48 -0800763 xfrm_usersa_info usersa{};
764 nlattr_algo_crypt crypt{};
765 nlattr_algo_auth auth{};
Benedict Wongbe65b432017-08-22 21:43:14 -0700766 nlattr_algo_aead aead{};
Di Lu2ccb3e52018-01-03 16:19:20 -0800767 nlattr_xfrm_mark xfrmmark{};
Benedict Wong96abf482018-01-22 13:56:41 -0800768 nlattr_xfrm_output_mark xfrmoutputmark{};
Nathan Harold420ceac2017-04-05 19:36:59 -0700769 nlattr_encap_tmpl encap{};
Nathan Harold1a371532017-01-30 12:30:48 -0800770
Benedict Wongbe65b432017-08-22 21:43:14 -0700771 enum {
772 NLMSG_HDR,
773 USERSA,
774 USERSA_PAD,
775 CRYPT,
776 CRYPT_PAD,
777 AUTH,
778 AUTH_PAD,
779 AEAD,
780 AEAD_PAD,
Di Lu2ccb3e52018-01-03 16:19:20 -0800781 MARK,
782 MARK_PAD,
Benedict Wong96abf482018-01-22 13:56:41 -0800783 OUTPUT_MARK,
784 OUTPUT_MARK_PAD,
Benedict Wongbe65b432017-08-22 21:43:14 -0700785 ENCAP,
Di Lu2ccb3e52018-01-03 16:19:20 -0800786 ENCAP_PAD,
Benedict Wongbe65b432017-08-22 21:43:14 -0700787 };
Nathan Harold1a371532017-01-30 12:30:48 -0800788
ludie51e3862017-08-15 19:28:12 -0700789 std::vector<iovec> iov = {
Benedict Wong96abf482018-01-22 13:56:41 -0800790 {NULL, 0}, // reserved for the eventual addition of a NLMSG_HDR
791 {&usersa, 0}, // main usersa_info struct
792 {kPadBytes, 0}, // up to NLMSG_ALIGNTO pad bytes of padding
793 {&crypt, 0}, // adjust size if crypt algo is present
794 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
795 {&auth, 0}, // adjust size if auth algo is present
796 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
797 {&aead, 0}, // adjust size if aead algo is present
798 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
799 {&xfrmmark, 0}, // adjust size if xfrm mark is present
800 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
801 {&xfrmoutputmark, 0}, // adjust size if xfrm output mark is present
802 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
803 {&encap, 0}, // adjust size if encapsulating
804 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
Nathan Harold1a371532017-01-30 12:30:48 -0800805 };
806
Benedict Wongbe65b432017-08-22 21:43:14 -0700807 if (!record.aead.name.empty() && (!record.auth.name.empty() || !record.crypt.name.empty())) {
808 return netdutils::statusFromErrno(EINVAL, "Invalid xfrm algo selection; AEAD is mutually "
809 "exclusive with both Authentication and "
810 "Encryption");
811 }
812
Benedict Wong4f60ee12017-10-10 12:27:25 -0700813 if (record.aead.key.size() > MAX_KEY_LENGTH || record.auth.key.size() > MAX_KEY_LENGTH ||
814 record.crypt.key.size() > MAX_KEY_LENGTH) {
815 return netdutils::statusFromErrno(EINVAL, "Key length invalid; exceeds MAX_KEY_LENGTH");
Benedict Wongbe65b432017-08-22 21:43:14 -0700816 }
817
Nathan Harold1a371532017-01-30 12:30:48 -0800818 int len;
819 len = iov[USERSA].iov_len = fillUserSaInfo(record, &usersa);
820 iov[USERSA_PAD].iov_len = NLMSG_ALIGN(len) - len;
821
822 len = iov[CRYPT].iov_len = fillNlAttrXfrmAlgoEnc(record.crypt, &crypt);
823 iov[CRYPT_PAD].iov_len = NLA_ALIGN(len) - len;
824
825 len = iov[AUTH].iov_len = fillNlAttrXfrmAlgoAuth(record.auth, &auth);
826 iov[AUTH_PAD].iov_len = NLA_ALIGN(len) - len;
827
Benedict Wongbe65b432017-08-22 21:43:14 -0700828 len = iov[AEAD].iov_len = fillNlAttrXfrmAlgoAead(record.aead, &aead);
829 iov[AEAD_PAD].iov_len = NLA_ALIGN(len) - len;
830
Di Lu2ccb3e52018-01-03 16:19:20 -0800831 len = iov[MARK].iov_len = fillNlAttrXfrmMark(record, &xfrmmark);
832 iov[MARK_PAD].iov_len = NLA_ALIGN(len) - len;
833
Benedict Wong96abf482018-01-22 13:56:41 -0800834 len = iov[OUTPUT_MARK].iov_len = fillNlAttrXfrmOutputMark(record.netId, &xfrmoutputmark);
835 iov[OUTPUT_MARK_PAD].iov_len = NLA_ALIGN(len) - len;
836
Nathan Harold420ceac2017-04-05 19:36:59 -0700837 len = iov[ENCAP].iov_len = fillNlAttrXfrmEncapTmpl(record, &encap);
838 iov[ENCAP_PAD].iov_len = NLA_ALIGN(len) - len;
Di Lu2ccb3e52018-01-03 16:19:20 -0800839
ludie51e3862017-08-15 19:28:12 -0700840 return sock.sendMessage(XFRM_MSG_UPDSA, NETLINK_REQUEST_FLAGS, 0, &iov);
Nathan Harold1a371532017-01-30 12:30:48 -0800841}
842
843int XfrmController::fillNlAttrXfrmAlgoEnc(const XfrmAlgo& inAlgo, nlattr_algo_crypt* algo) {
Benedict Wongbe65b432017-08-22 21:43:14 -0700844 if (inAlgo.name.empty()) { // Do not fill anything if algorithm not provided
845 return 0;
846 }
847
Nathan Harold1a371532017-01-30 12:30:48 -0800848 int len = NLA_HDRLEN + sizeof(xfrm_algo);
Benedict Wongbe65b432017-08-22 21:43:14 -0700849 // Kernel always changes last char to null terminator; no safety checks needed.
Nathan Harold1a371532017-01-30 12:30:48 -0800850 strncpy(algo->crypt.alg_name, inAlgo.name.c_str(), sizeof(algo->crypt.alg_name));
Nathan Harold7441c692017-12-12 21:25:01 -0800851 algo->crypt.alg_key_len = inAlgo.key.size() * 8; // bits
Benedict Wongbe65b432017-08-22 21:43:14 -0700852 memcpy(algo->key, &inAlgo.key[0], inAlgo.key.size());
Nathan Harold1a371532017-01-30 12:30:48 -0800853 len += inAlgo.key.size();
854 fillXfrmNlaHdr(&algo->hdr, XFRMA_ALG_CRYPT, len);
855 return len;
856}
857
858int XfrmController::fillNlAttrXfrmAlgoAuth(const XfrmAlgo& inAlgo, nlattr_algo_auth* algo) {
Benedict Wongbe65b432017-08-22 21:43:14 -0700859 if (inAlgo.name.empty()) { // Do not fill anything if algorithm not provided
860 return 0;
861 }
862
Nathan Harold1a371532017-01-30 12:30:48 -0800863 int len = NLA_HDRLEN + sizeof(xfrm_algo_auth);
Benedict Wongbe65b432017-08-22 21:43:14 -0700864 // Kernel always changes last char to null terminator; no safety checks needed.
Nathan Harold1a371532017-01-30 12:30:48 -0800865 strncpy(algo->auth.alg_name, inAlgo.name.c_str(), sizeof(algo->auth.alg_name));
866 algo->auth.alg_key_len = inAlgo.key.size() * 8; // bits
867
868 // This is the extra field for ALG_AUTH_TRUNC
869 algo->auth.alg_trunc_len = inAlgo.truncLenBits;
870
Benedict Wongbe65b432017-08-22 21:43:14 -0700871 memcpy(algo->key, &inAlgo.key[0], inAlgo.key.size());
Nathan Harold1a371532017-01-30 12:30:48 -0800872 len += inAlgo.key.size();
873
874 fillXfrmNlaHdr(&algo->hdr, XFRMA_ALG_AUTH_TRUNC, len);
875 return len;
876}
877
Benedict Wongbe65b432017-08-22 21:43:14 -0700878int XfrmController::fillNlAttrXfrmAlgoAead(const XfrmAlgo& inAlgo, nlattr_algo_aead* algo) {
879 if (inAlgo.name.empty()) { // Do not fill anything if algorithm not provided
880 return 0;
881 }
882
883 int len = NLA_HDRLEN + sizeof(xfrm_algo_aead);
884 // Kernel always changes last char to null terminator; no safety checks needed.
885 strncpy(algo->aead.alg_name, inAlgo.name.c_str(), sizeof(algo->aead.alg_name));
886 algo->aead.alg_key_len = inAlgo.key.size() * 8; // bits
887
888 // This is the extra field for ALG_AEAD. ICV length is the same as truncation length
889 // for any AEAD algorithm.
890 algo->aead.alg_icv_len = inAlgo.truncLenBits;
891
892 memcpy(algo->key, &inAlgo.key[0], inAlgo.key.size());
893 len += inAlgo.key.size();
894
895 fillXfrmNlaHdr(&algo->hdr, XFRMA_ALG_AEAD, len);
896 return len;
897}
898
Nathan Harold420ceac2017-04-05 19:36:59 -0700899int XfrmController::fillNlAttrXfrmEncapTmpl(const XfrmSaInfo& record, nlattr_encap_tmpl* tmpl) {
900 if (record.encap.type == XfrmEncapType::NONE) {
901 return 0;
902 }
903
904 int len = NLA_HDRLEN + sizeof(xfrm_encap_tmpl);
905 tmpl->tmpl.encap_type = static_cast<uint16_t>(record.encap.type);
906 tmpl->tmpl.encap_sport = htons(record.encap.srcPort);
907 tmpl->tmpl.encap_dport = htons(record.encap.dstPort);
908 fillXfrmNlaHdr(&tmpl->hdr, XFRMA_ENCAP, len);
909 return len;
910}
911
Nathan Harold1a371532017-01-30 12:30:48 -0800912int XfrmController::fillUserSaInfo(const XfrmSaInfo& record, xfrm_usersa_info* usersa) {
ludi771b8002017-11-20 15:09:05 -0800913 fillXfrmSelector(record, &usersa->sel);
Nathan Harold1a371532017-01-30 12:30:48 -0800914
915 usersa->id.proto = IPPROTO_ESP;
916 usersa->id.spi = record.spi;
917 usersa->id.daddr = record.dstAddr;
918
919 usersa->saddr = record.srcAddr;
920
921 fillXfrmLifetimeDefaults(&usersa->lft);
922 fillXfrmCurLifetimeDefaults(&usersa->curlft);
923 memset(&usersa->stats, 0, sizeof(usersa->stats)); // leave stats zeroed out
924 usersa->reqid = record.transformId;
925 usersa->family = record.addrFamily;
926 usersa->mode = static_cast<uint8_t>(record.mode);
927 usersa->replay_window = REPLAY_WINDOW_SIZE;
manojboopathi4d2d6f12017-12-06 11:11:31 -0800928
929 if (record.mode == XfrmMode::TRANSPORT) {
930 usersa->flags = 0; // TODO: should we actually set flags, XFRM_SA_XFLAG_DONT_ENCAP_DSCP?
931 } else {
932 usersa->flags = XFRM_STATE_AF_UNSPEC;
933 }
934
Nathan Harold1a371532017-01-30 12:30:48 -0800935 return sizeof(*usersa);
936}
937
Nathan Harold7441c692017-12-12 21:25:01 -0800938int XfrmController::fillUserSaId(const XfrmId& record, xfrm_usersa_id* said) {
Nathan Harold1a371532017-01-30 12:30:48 -0800939 said->daddr = record.dstAddr;
940 said->spi = record.spi;
941 said->family = record.addrFamily;
942 said->proto = IPPROTO_ESP;
943
944 return sizeof(*said);
945}
946
Nathan Harold7441c692017-12-12 21:25:01 -0800947netdutils::Status XfrmController::deleteSecurityAssociation(const XfrmId& record,
ludi6e8eccd2017-08-14 14:40:37 -0700948 const XfrmSocket& sock) {
Nathan Harold1a371532017-01-30 12:30:48 -0800949 xfrm_usersa_id said{};
Di Lu2ccb3e52018-01-03 16:19:20 -0800950 nlattr_xfrm_mark xfrmmark{};
Nathan Harold1a371532017-01-30 12:30:48 -0800951
Di Lu2ccb3e52018-01-03 16:19:20 -0800952 enum { NLMSG_HDR, USERSAID, USERSAID_PAD, MARK, MARK_PAD };
Nathan Harold1a371532017-01-30 12:30:48 -0800953
ludie51e3862017-08-15 19:28:12 -0700954 std::vector<iovec> iov = {
Nathan Harold1a371532017-01-30 12:30:48 -0800955 {NULL, 0}, // reserved for the eventual addition of a NLMSG_HDR
956 {&said, 0}, // main usersa_info struct
957 {kPadBytes, 0}, // up to NLMSG_ALIGNTO pad bytes of padding
manojboopathi8707f232018-01-02 14:45:47 -0800958 {&xfrmmark, 0}, // adjust size if xfrm mark is present
959 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
Nathan Harold1a371532017-01-30 12:30:48 -0800960 };
961
962 int len;
963 len = iov[USERSAID].iov_len = fillUserSaId(record, &said);
964 iov[USERSAID_PAD].iov_len = NLMSG_ALIGN(len) - len;
965
Di Lu2ccb3e52018-01-03 16:19:20 -0800966 len = iov[MARK].iov_len = fillNlAttrXfrmMark(record, &xfrmmark);
967 iov[MARK_PAD].iov_len = NLA_ALIGN(len) - len;
968
ludie51e3862017-08-15 19:28:12 -0700969 return sock.sendMessage(XFRM_MSG_DELSA, NETLINK_REQUEST_FLAGS, 0, &iov);
Nathan Harold1a371532017-01-30 12:30:48 -0800970}
971
ludi6e8eccd2017-08-14 14:40:37 -0700972netdutils::Status XfrmController::allocateSpi(const XfrmSaInfo& record, uint32_t minSpi,
973 uint32_t maxSpi, uint32_t* outSpi,
974 const XfrmSocket& sock) {
Nathan Harold1a371532017-01-30 12:30:48 -0800975 xfrm_userspi_info spiInfo{};
976
ludie51e3862017-08-15 19:28:12 -0700977 enum { NLMSG_HDR, USERSAID, USERSAID_PAD };
Nathan Harold1a371532017-01-30 12:30:48 -0800978
ludie51e3862017-08-15 19:28:12 -0700979 std::vector<iovec> iov = {
Nathan Harold1a371532017-01-30 12:30:48 -0800980 {NULL, 0}, // reserved for the eventual addition of a NLMSG_HDR
981 {&spiInfo, 0}, // main userspi_info struct
982 {kPadBytes, 0}, // up to NLMSG_ALIGNTO pad bytes of padding
983 };
984
985 int len;
986 if (fillUserSaInfo(record, &spiInfo.info) == 0) {
987 ALOGE("Failed to fill transport SA Info");
988 }
989
990 len = iov[USERSAID].iov_len = sizeof(spiInfo);
991 iov[USERSAID_PAD].iov_len = NLMSG_ALIGN(len) - len;
992
993 RandomSpi spiGen = RandomSpi(minSpi, maxSpi);
ludi6e8eccd2017-08-14 14:40:37 -0700994 int spi;
995 netdutils::Status ret;
Nathan Harold1a371532017-01-30 12:30:48 -0800996 while ((spi = spiGen.next()) != INVALID_SPI) {
997 spiInfo.min = spi;
998 spiInfo.max = spi;
ludie51e3862017-08-15 19:28:12 -0700999 ret = sock.sendMessage(XFRM_MSG_ALLOCSPI, NETLINK_REQUEST_FLAGS, 0, &iov);
Nathan Harold1a371532017-01-30 12:30:48 -08001000
1001 /* If the SPI is in use, we'll get ENOENT */
ludi6e8eccd2017-08-14 14:40:37 -07001002 if (netdutils::equalToErrno(ret, ENOENT))
Nathan Harold1a371532017-01-30 12:30:48 -08001003 continue;
1004
ludi6e8eccd2017-08-14 14:40:37 -07001005 if (isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -08001006 *outSpi = spi;
Nathan Harold420ceac2017-04-05 19:36:59 -07001007 ALOGD("Allocated an SPI: %x", *outSpi);
Nathan Harold1a371532017-01-30 12:30:48 -08001008 } else {
1009 *outSpi = INVALID_SPI;
ludi6e8eccd2017-08-14 14:40:37 -07001010 ALOGE("SPI Allocation Failed with error %d", ret.code());
Nathan Harold1a371532017-01-30 12:30:48 -08001011 }
1012
1013 return ret;
1014 }
1015
1016 // Should always be -ENOENT if we get here
1017 return ret;
1018}
1019
ludi771b8002017-11-20 15:09:05 -08001020netdutils::Status XfrmController::updateTunnelModeSecurityPolicy(const XfrmSaInfo& record,
1021 const XfrmSocket& sock,
1022 XfrmDirection direction,
1023 uint16_t msgType) {
1024 xfrm_userpolicy_info userpolicy{};
1025 nlattr_user_tmpl usertmpl{};
Di Lu2ccb3e52018-01-03 16:19:20 -08001026 nlattr_xfrm_mark xfrmmark{};
ludi771b8002017-11-20 15:09:05 -08001027
1028 enum {
1029 NLMSG_HDR,
1030 USERPOLICY,
1031 USERPOLICY_PAD,
1032 USERTMPL,
1033 USERTMPL_PAD,
Di Lu2ccb3e52018-01-03 16:19:20 -08001034 MARK,
1035 MARK_PAD,
ludi771b8002017-11-20 15:09:05 -08001036 };
1037
1038 std::vector<iovec> iov = {
1039 {NULL, 0}, // reserved for the eventual addition of a NLMSG_HDR
1040 {&userpolicy, 0}, // main xfrm_userpolicy_info struct
1041 {kPadBytes, 0}, // up to NLMSG_ALIGNTO pad bytes of padding
1042 {&usertmpl, 0}, // adjust size if xfrm_user_tmpl struct is present
1043 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
Di Lu2ccb3e52018-01-03 16:19:20 -08001044 {&xfrmmark, 0}, // adjust size if xfrm mark is present
1045 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
ludi771b8002017-11-20 15:09:05 -08001046 };
1047
1048 int len;
1049 len = iov[USERPOLICY].iov_len = fillTransportModeUserSpInfo(record, direction, &userpolicy);
1050 iov[USERPOLICY_PAD].iov_len = NLMSG_ALIGN(len) - len;
1051
1052 len = iov[USERTMPL].iov_len = fillNlAttrUserTemplate(record, &usertmpl);
1053 iov[USERTMPL_PAD].iov_len = NLA_ALIGN(len) - len;
1054
Di Lu2ccb3e52018-01-03 16:19:20 -08001055 len = iov[MARK].iov_len = fillNlAttrXfrmMark(record, &xfrmmark);
1056 iov[MARK_PAD].iov_len = NLA_ALIGN(len) - len;
1057
ludi771b8002017-11-20 15:09:05 -08001058 return sock.sendMessage(msgType, NETLINK_REQUEST_FLAGS, 0, &iov);
1059}
1060
1061netdutils::Status XfrmController::deleteTunnelModeSecurityPolicy(const XfrmSaInfo& record,
1062 const XfrmSocket& sock,
1063 XfrmDirection direction) {
1064 xfrm_userpolicy_id policyid{};
Di Lu2ccb3e52018-01-03 16:19:20 -08001065 nlattr_xfrm_mark xfrmmark{};
ludi771b8002017-11-20 15:09:05 -08001066
1067 enum {
1068 NLMSG_HDR,
1069 USERPOLICYID,
1070 USERPOLICYID_PAD,
Di Lu2ccb3e52018-01-03 16:19:20 -08001071 MARK,
1072 MARK_PAD,
ludi771b8002017-11-20 15:09:05 -08001073 };
1074
1075 std::vector<iovec> iov = {
1076 {NULL, 0}, // reserved for the eventual addition of a NLMSG_HDR
1077 {&policyid, 0}, // main xfrm_userpolicy_id struct
1078 {kPadBytes, 0}, // up to NLMSG_ALIGNTO pad bytes of padding
manojboopathi8707f232018-01-02 14:45:47 -08001079 {&xfrmmark, 0}, // adjust size if xfrm mark is present
1080 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
ludi771b8002017-11-20 15:09:05 -08001081 };
1082
1083 int len = iov[USERPOLICYID].iov_len = fillUserPolicyId(record, direction, &policyid);
1084 iov[USERPOLICYID_PAD].iov_len = NLMSG_ALIGN(len) - len;
1085
Di Lu2ccb3e52018-01-03 16:19:20 -08001086 len = iov[MARK].iov_len = fillNlAttrXfrmMark(record, &xfrmmark);
1087 iov[MARK_PAD].iov_len = NLA_ALIGN(len) - len;
1088
ludi771b8002017-11-20 15:09:05 -08001089 return sock.sendMessage(XFRM_MSG_DELPOLICY, NETLINK_REQUEST_FLAGS, 0, &iov);
1090}
1091
Nathan Haroldda54f122018-01-09 16:42:57 -08001092int XfrmController::fillTransportModeUserSpInfo(const XfrmSaInfo& record, XfrmDirection direction,
Nathan Harold1a371532017-01-30 12:30:48 -08001093 xfrm_userpolicy_info* usersp) {
ludi771b8002017-11-20 15:09:05 -08001094 fillXfrmSelector(record, &usersp->sel);
Nathan Harold1a371532017-01-30 12:30:48 -08001095 fillXfrmLifetimeDefaults(&usersp->lft);
1096 fillXfrmCurLifetimeDefaults(&usersp->curlft);
Nathan Harold420ceac2017-04-05 19:36:59 -07001097 /* if (index) index & 0x3 == dir -- must be true
1098 * xfrm_user.c:verify_newpolicy_info() */
Nathan Harold1a371532017-01-30 12:30:48 -08001099 usersp->index = 0;
Nathan Haroldda54f122018-01-09 16:42:57 -08001100 usersp->dir = static_cast<uint8_t>(direction);
Nathan Harold1a371532017-01-30 12:30:48 -08001101 usersp->action = XFRM_POLICY_ALLOW;
1102 usersp->flags = XFRM_POLICY_LOCALOK;
1103 usersp->share = XFRM_SHARE_UNIQUE;
1104 return sizeof(*usersp);
1105}
1106
1107int XfrmController::fillUserTemplate(const XfrmSaInfo& record, xfrm_user_tmpl* tmpl) {
1108 tmpl->id.daddr = record.dstAddr;
1109 tmpl->id.spi = record.spi;
1110 tmpl->id.proto = IPPROTO_ESP;
1111
1112 tmpl->family = record.addrFamily;
1113 tmpl->saddr = record.srcAddr;
1114 tmpl->reqid = record.transformId;
1115 tmpl->mode = static_cast<uint8_t>(record.mode);
1116 tmpl->share = XFRM_SHARE_UNIQUE;
1117 tmpl->optional = 0; // if this is true, then a failed state lookup will be considered OK:
1118 // http://lxr.free-electrons.com/source/net/xfrm/xfrm_policy.c#L1492
1119 tmpl->aalgos = ALGO_MASK_AUTH_ALL; // TODO: if there's a bitmask somewhere of
1120 // algos, we should find it and apply it.
1121 // I can't find one.
1122 tmpl->ealgos = ALGO_MASK_CRYPT_ALL; // TODO: if there's a bitmask somewhere...
ludi771b8002017-11-20 15:09:05 -08001123 return sizeof(xfrm_user_tmpl*);
Nathan Harold1a371532017-01-30 12:30:48 -08001124}
1125
ludi771b8002017-11-20 15:09:05 -08001126int XfrmController::fillNlAttrUserTemplate(const XfrmSaInfo& record, nlattr_user_tmpl* tmpl) {
1127 fillUserTemplate(record, &tmpl->tmpl);
1128
1129 int len = NLA_HDRLEN + sizeof(xfrm_user_tmpl);
1130 fillXfrmNlaHdr(&tmpl->hdr, XFRMA_TMPL, len);
1131 return len;
1132}
1133
Di Lu2ccb3e52018-01-03 16:19:20 -08001134int XfrmController::fillNlAttrXfrmMark(const XfrmId& record, nlattr_xfrm_mark* mark) {
1135 mark->mark.v = record.mark.v; // set to 0 if it's not used
1136 mark->mark.m = record.mark.m; // set to 0 if it's not used
1137 int len = NLA_HDRLEN + sizeof(xfrm_mark);
1138 fillXfrmNlaHdr(&mark->hdr, XFRMA_MARK, len);
1139 return len;
1140}
1141
manojboopathi8707f232018-01-02 14:45:47 -08001142int XfrmController::fillNlAttrXfrmOutputMark(const __u32 output_mark_value,
1143 nlattr_xfrm_output_mark* output_mark) {
Benedict Wong96abf482018-01-22 13:56:41 -08001144 // Do not set if we were not given an output mark
1145 if (output_mark_value == 0) {
1146 return 0;
1147 }
1148
1149 output_mark->outputMark = output_mark_value;
1150 int len = NLA_HDRLEN + sizeof(__u32);
1151 fillXfrmNlaHdr(&output_mark->hdr, XFRMA_OUTPUT_MARK, len);
1152 return len;
1153}
1154
ludi771b8002017-11-20 15:09:05 -08001155int XfrmController::fillUserPolicyId(const XfrmSaInfo& record, XfrmDirection direction,
1156 xfrm_userpolicy_id* usersp) {
1157 // For DELPOLICY, when index is absent, selector is needed to match the policy
1158 fillXfrmSelector(record, &usersp->sel);
1159 usersp->dir = static_cast<uint8_t>(direction);
1160 return sizeof(*usersp);
1161}
1162
manojboopathi8707f232018-01-02 14:45:47 -08001163int XfrmController::addVirtualTunnelInterface(const std::string& deviceName,
1164 const std::string& localAddress,
1165 const std::string& remoteAddress, int32_t ikey,
1166 int32_t okey, bool isUpdate) {
1167 ALOGD("XfrmController::%s, line=%d", __FUNCTION__, __LINE__);
1168 ALOGD("deviceName=%s", deviceName.c_str());
1169 ALOGD("localAddress=%s", localAddress.c_str());
1170 ALOGD("remoteAddress=%s", remoteAddress.c_str());
1171 ALOGD("ikey=%0.8x", ikey);
1172 ALOGD("okey=%0.8x", okey);
1173 ALOGD("isUpdate=%d", isUpdate);
1174
1175 if (deviceName.empty() || localAddress.empty() || remoteAddress.empty()) {
1176 return EINVAL;
1177 }
1178
1179 const char* INFO_KIND_VTI6 = "vti6";
1180 const char* INFO_KIND_VTI = "vti";
1181 uint8_t PADDING_BUFFER[] = {0, 0, 0, 0};
1182
1183 // Find address family.
1184 uint8_t remAddr[sizeof(in6_addr)];
1185
1186 StatusOr<uint16_t> statusOrRemoteFam = convertStringAddress(remoteAddress, remAddr);
1187 if (!isOk(statusOrRemoteFam)) {
1188 return statusOrRemoteFam.status().code();
1189 }
1190
1191 uint8_t locAddr[sizeof(in6_addr)];
1192 StatusOr<uint16_t> statusOrLocalFam = convertStringAddress(localAddress, locAddr);
1193 if (!isOk(statusOrLocalFam)) {
1194 return statusOrLocalFam.status().code();
1195 }
1196
1197 if (statusOrLocalFam.value() != statusOrRemoteFam.value()) {
1198 return EINVAL;
1199 }
1200
1201 uint16_t family = statusOrLocalFam.value();
1202
1203 ifinfomsg ifInfoMsg{};
1204
1205 // Construct IFLA_IFNAME
1206 nlattr iflaIfName;
1207 char iflaIfNameStrValue[deviceName.length() + 1];
1208 size_t iflaIfNameLength =
1209 strlcpy(iflaIfNameStrValue, deviceName.c_str(), sizeof(iflaIfNameStrValue));
1210 size_t iflaIfNamePad = fillNlAttr(IFLA_IFNAME, iflaIfNameLength, &iflaIfName);
1211
1212 // Construct IFLA_INFO_KIND
1213 // Constants "vti6" and "vti" enable the kernel to call different code paths,
1214 // (ip_tunnel.c, ip6_tunnel), based on the family.
1215 const std::string infoKindValue = (family == AF_INET6) ? INFO_KIND_VTI6 : INFO_KIND_VTI;
1216 nlattr iflaIfInfoKind;
1217 char infoKindValueStrValue[infoKindValue.length() + 1];
1218 size_t iflaIfInfoKindLength =
1219 strlcpy(infoKindValueStrValue, infoKindValue.c_str(), sizeof(infoKindValueStrValue));
1220 size_t iflaIfInfoKindPad = fillNlAttr(IFLA_INFO_KIND, iflaIfInfoKindLength, &iflaIfInfoKind);
1221
1222 // Construct IFLA_VTI_LOCAL
1223 nlattr iflaVtiLocal;
1224 uint8_t binaryLocalAddress[sizeof(in6_addr)];
1225 size_t iflaVtiLocalPad =
1226 fillNlAttrIpAddress(IFLA_VTI_LOCAL, family, localAddress, &iflaVtiLocal,
1227 netdutils::makeSlice(binaryLocalAddress));
1228
1229 // Construct IFLA_VTI_REMOTE
1230 nlattr iflaVtiRemote;
1231 uint8_t binaryRemoteAddress[sizeof(in6_addr)];
1232 size_t iflaVtiRemotePad =
1233 fillNlAttrIpAddress(IFLA_VTI_REMOTE, family, remoteAddress, &iflaVtiRemote,
1234 netdutils::makeSlice(binaryRemoteAddress));
1235
1236 // Construct IFLA_VTI_OKEY
1237 nlattr iflaVtiIKey;
1238 uint32_t iKeyValue;
1239 size_t iflaVtiIKeyPad = fillNlAttrU32(IFLA_VTI_IKEY, ikey, &iflaVtiIKey, &iKeyValue);
1240
1241 // Construct IFLA_VTI_IKEY
1242 nlattr iflaVtiOKey;
1243 uint32_t oKeyValue;
1244 size_t iflaVtiOKeyPad = fillNlAttrU32(IFLA_VTI_OKEY, okey, &iflaVtiOKey, &oKeyValue);
1245
1246 int iflaInfoDataPayloadLength = iflaVtiLocal.nla_len + iflaVtiLocalPad + iflaVtiRemote.nla_len +
1247 iflaVtiRemotePad + iflaVtiIKey.nla_len + iflaVtiIKeyPad +
1248 iflaVtiOKey.nla_len + iflaVtiOKeyPad;
1249
1250 // Construct IFLA_INFO_DATA
1251 nlattr iflaInfoData;
1252 size_t iflaInfoDataPad = fillNlAttr(IFLA_INFO_DATA, iflaInfoDataPayloadLength, &iflaInfoData);
1253
1254 // Construct IFLA_LINKINFO
1255 nlattr iflaLinkInfo;
1256 size_t iflaLinkInfoPad = fillNlAttr(IFLA_LINKINFO,
1257 iflaInfoData.nla_len + iflaInfoDataPad +
1258 iflaIfInfoKind.nla_len + iflaIfInfoKindPad,
1259 &iflaLinkInfo);
1260
1261 iovec iov[] = {
1262 {NULL, 0},
1263 {&ifInfoMsg, sizeof(ifInfoMsg)},
1264
1265 {&iflaIfName, sizeof(iflaIfName)},
1266 {iflaIfNameStrValue, iflaIfNameLength},
1267 {&PADDING_BUFFER, iflaIfNamePad},
1268
1269 {&iflaLinkInfo, sizeof(iflaLinkInfo)},
1270
1271 {&iflaIfInfoKind, sizeof(iflaIfInfoKind)},
1272 {infoKindValueStrValue, iflaIfInfoKindLength},
1273 {&PADDING_BUFFER, iflaIfInfoKindPad},
1274
1275 {&iflaInfoData, sizeof(iflaInfoData)},
1276
1277 {&iflaVtiLocal, sizeof(iflaVtiLocal)},
1278 {&binaryLocalAddress, (family == AF_INET) ? sizeof(in_addr) : sizeof(in6_addr)},
1279 {&PADDING_BUFFER, iflaVtiLocalPad},
1280
1281 {&iflaVtiRemote, sizeof(iflaVtiRemote)},
1282 {&binaryRemoteAddress, (family == AF_INET) ? sizeof(in_addr) : sizeof(in6_addr)},
1283 {&PADDING_BUFFER, iflaVtiRemotePad},
1284
1285 {&iflaVtiIKey, sizeof(iflaVtiIKey)},
1286 {&iKeyValue, sizeof(iKeyValue)},
1287 {&PADDING_BUFFER, iflaVtiIKeyPad},
1288
1289 {&iflaVtiOKey, sizeof(iflaVtiOKey)},
1290 {&oKeyValue, sizeof(oKeyValue)},
1291 {&PADDING_BUFFER, iflaVtiOKeyPad},
1292
1293 {&PADDING_BUFFER, iflaInfoDataPad},
1294
1295 {&PADDING_BUFFER, iflaLinkInfoPad},
1296 };
1297
1298 uint16_t action = RTM_NEWLINK;
1299 uint16_t flags = NLM_F_REQUEST | NLM_F_ACK;
1300
1301 if (!isUpdate) {
1302 flags |= NLM_F_EXCL | NLM_F_CREATE;
1303 }
1304
1305 int ret = sendNetlinkRequest(action, flags, iov, ARRAY_SIZE(iov), nullptr);
1306 if (ret) {
1307 ALOGE("Error in %s virtual tunnel interface. Error Code: %d",
1308 isUpdate ? "updating" : "adding", ret);
1309 }
1310 return ret;
1311}
1312
1313int XfrmController::removeVirtualTunnelInterface(const std::string& deviceName) {
1314 ALOGD("XfrmController::%s, line=%d", __FUNCTION__, __LINE__);
1315 ALOGD("deviceName=%s", deviceName.c_str());
1316
1317 if (deviceName.empty()) {
1318 return EINVAL;
1319 }
1320
1321 uint8_t PADDING_BUFFER[] = {0, 0, 0, 0};
1322
1323 ifinfomsg ifInfoMsg{};
1324 nlattr iflaIfName;
1325 char iflaIfNameStrValue[deviceName.length() + 1];
1326 size_t iflaIfNameLength =
1327 strlcpy(iflaIfNameStrValue, deviceName.c_str(), sizeof(iflaIfNameStrValue));
1328 size_t iflaIfNamePad = fillNlAttr(IFLA_IFNAME, iflaIfNameLength, &iflaIfName);
1329
1330 iovec iov[] = {
1331 {NULL, 0},
1332 {&ifInfoMsg, sizeof(ifInfoMsg)},
1333
1334 {&iflaIfName, sizeof(iflaIfName)},
1335 {iflaIfNameStrValue, iflaIfNameLength},
1336 {&PADDING_BUFFER, iflaIfNamePad},
1337 };
1338
1339 uint16_t action = RTM_DELLINK;
1340 uint16_t flags = NLM_F_REQUEST | NLM_F_ACK;
1341
1342 int ret = sendNetlinkRequest(action, flags, iov, ARRAY_SIZE(iov), nullptr);
1343 if (ret) {
1344 ALOGE("Error in removing virtual tunnel interface %s. Error Code: %d", iflaIfNameStrValue,
1345 ret);
1346 }
1347 return ret;
1348}
ludi771b8002017-11-20 15:09:05 -08001349
Nathan Harold1a371532017-01-30 12:30:48 -08001350} // namespace net
1351} // namespace android