blob: f915814bc50ab573f2d09e148ed0cc97de219993 [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>
Nathan Harold21299f72018-03-16 20:13:03 -070042#include <linux/ipsec.h>
Nathan Harold1a371532017-01-30 12:30:48 -080043#include <linux/netlink.h>
44#include <linux/xfrm.h>
45
Nathan Harold45c35662018-04-23 10:10:18 -070046#define LOG_TAG "XfrmController"
Nathan Harold21299f72018-03-16 20:13:03 -070047#include "InterfaceController.h"
Nathan Harold1a371532017-01-30 12:30:48 -080048#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 Harolda0345e12018-06-05 11:41:41 -070055#include <android-base/properties.h>
56#include <android-base/stringprintf.h>
57#include <android-base/strings.h>
58#include <android-base/unique_fd.h>
59#include <android/net/INetd.h>
Nathan Harold1a371532017-01-30 12:30:48 -080060#include <cutils/properties.h>
Logan Chien3f461482018-04-23 14:31:32 +080061#include <log/log.h>
Nathan Harolda0345e12018-06-05 11:41:41 -070062#include <log/log_properties.h>
Nathan Harold1a371532017-01-30 12:30:48 -080063#include <logwrap/logwrap.h>
64
Nathan Harold45c35662018-04-23 10:10:18 -070065using android::net::INetd;
ludi4072ff22017-06-15 08:56:52 -070066using android::netdutils::Fd;
67using android::netdutils::Slice;
68using android::netdutils::Status;
69using android::netdutils::StatusOr;
70using android::netdutils::Syscalls;
71
Nathan Harold1a371532017-01-30 12:30:48 -080072namespace android {
73namespace net {
74
Nathan Harold39b5df42017-08-02 18:45:25 -070075// Exposed for testing
Nathan Harold1a371532017-01-30 12:30:48 -080076constexpr uint32_t ALGO_MASK_AUTH_ALL = ~0;
Nathan Harold39b5df42017-08-02 18:45:25 -070077// Exposed for testing
Nathan Harold1a371532017-01-30 12:30:48 -080078constexpr uint32_t ALGO_MASK_CRYPT_ALL = ~0;
Nathan Harold39b5df42017-08-02 18:45:25 -070079// Exposed for testing
Benedict Wongbe65b432017-08-22 21:43:14 -070080constexpr uint32_t ALGO_MASK_AEAD_ALL = ~0;
81// Exposed for testing
Nathan Harold1a371532017-01-30 12:30:48 -080082constexpr uint8_t REPLAY_WINDOW_SIZE = 4;
83
Nathan Harold39b5df42017-08-02 18:45:25 -070084namespace {
85
Nathan Harold1012ffe2018-03-28 08:59:24 -070086constexpr uint32_t RAND_SPI_MIN = 256;
Nathan Harold1a371532017-01-30 12:30:48 -080087constexpr uint32_t RAND_SPI_MAX = 0xFFFFFFFE;
88
89constexpr uint32_t INVALID_SPI = 0;
90
Nathan Harolda0345e12018-06-05 11:41:41 -070091static inline bool isEngBuild() {
92 static const std::string sBuildType = android::base::GetProperty("ro.build.type", "user");
93 return sBuildType == "eng";
94}
95
Nathan Harold1a371532017-01-30 12:30:48 -080096#define XFRM_MSG_TRANS(x) \
97 case x: \
98 return #x;
99
100const char* xfrmMsgTypeToString(uint16_t msg) {
101 switch (msg) {
102 XFRM_MSG_TRANS(XFRM_MSG_NEWSA)
103 XFRM_MSG_TRANS(XFRM_MSG_DELSA)
104 XFRM_MSG_TRANS(XFRM_MSG_GETSA)
105 XFRM_MSG_TRANS(XFRM_MSG_NEWPOLICY)
106 XFRM_MSG_TRANS(XFRM_MSG_DELPOLICY)
107 XFRM_MSG_TRANS(XFRM_MSG_GETPOLICY)
108 XFRM_MSG_TRANS(XFRM_MSG_ALLOCSPI)
109 XFRM_MSG_TRANS(XFRM_MSG_ACQUIRE)
110 XFRM_MSG_TRANS(XFRM_MSG_EXPIRE)
111 XFRM_MSG_TRANS(XFRM_MSG_UPDPOLICY)
112 XFRM_MSG_TRANS(XFRM_MSG_UPDSA)
113 XFRM_MSG_TRANS(XFRM_MSG_POLEXPIRE)
114 XFRM_MSG_TRANS(XFRM_MSG_FLUSHSA)
115 XFRM_MSG_TRANS(XFRM_MSG_FLUSHPOLICY)
116 XFRM_MSG_TRANS(XFRM_MSG_NEWAE)
117 XFRM_MSG_TRANS(XFRM_MSG_GETAE)
118 XFRM_MSG_TRANS(XFRM_MSG_REPORT)
119 XFRM_MSG_TRANS(XFRM_MSG_MIGRATE)
120 XFRM_MSG_TRANS(XFRM_MSG_NEWSADINFO)
121 XFRM_MSG_TRANS(XFRM_MSG_GETSADINFO)
122 XFRM_MSG_TRANS(XFRM_MSG_GETSPDINFO)
123 XFRM_MSG_TRANS(XFRM_MSG_NEWSPDINFO)
124 XFRM_MSG_TRANS(XFRM_MSG_MAPPING)
125 default:
126 return "XFRM_MSG UNKNOWN";
127 }
128}
129
130// actually const but cannot be declared as such for reasons
131uint8_t kPadBytesArray[] = {0, 0, 0};
132void* kPadBytes = static_cast<void*>(kPadBytesArray);
133
Nathan Harold420ceac2017-04-05 19:36:59 -0700134#define LOG_HEX(__desc16__, __buf__, __len__) \
Nathan Harolda0345e12018-06-05 11:41:41 -0700135 do { \
136 if (isEngBuild()) { \
Manojd9c93c22017-10-19 13:40:26 -0700137 logHex(__desc16__, __buf__, __len__); \
Nathan Harolda0345e12018-06-05 11:41:41 -0700138 } \
139 } while (0)
Manojd9c93c22017-10-19 13:40:26 -0700140
ludie51e3862017-08-15 19:28:12 -0700141#define LOG_IOV(__iov__) \
Nathan Harolda0345e12018-06-05 11:41:41 -0700142 do { \
143 if (isEngBuild()) { \
Manojd9c93c22017-10-19 13:40:26 -0700144 logIov(__iov__); \
Nathan Harolda0345e12018-06-05 11:41:41 -0700145 } \
146 } while (0)
Nathan Harold1a371532017-01-30 12:30:48 -0800147
148void logHex(const char* desc16, const char* buf, size_t len) {
149 char* printBuf = new char[len * 2 + 1 + 26]; // len->ascii, +newline, +prefix strlen
150 int offset = 0;
151 if (desc16) {
152 sprintf(printBuf, "{%-16s}", desc16);
153 offset += 18; // prefix string length
154 }
155 sprintf(printBuf + offset, "[%4.4u]: ", (len > 9999) ? 9999 : (unsigned)len);
156 offset += 8;
157
158 for (uint32_t j = 0; j < (uint32_t)len; j++) {
Wolloh Chou4d1e5c72018-03-22 15:14:33 +0800159 sprintf(&printBuf[j * 2 + offset], "%0.2x", (unsigned char)buf[j]);
Nathan Harold1a371532017-01-30 12:30:48 -0800160 }
161 ALOGD("%s", printBuf);
162 delete[] printBuf;
163}
164
ludie51e3862017-08-15 19:28:12 -0700165void logIov(const std::vector<iovec>& iov) {
166 for (const iovec& row : iov) {
Yi Kongbdfd57e2018-07-25 13:26:10 -0700167 logHex(nullptr, reinterpret_cast<char*>(row.iov_base), row.iov_len);
Nathan Harold1a371532017-01-30 12:30:48 -0800168 }
169}
170
manojboopathi8707f232018-01-02 14:45:47 -0800171size_t fillNlAttr(__u16 nlaType, size_t valueSize, nlattr* nlAttr) {
172 size_t dataLen = valueSize;
173 int padLength = NLMSG_ALIGN(dataLen) - dataLen;
174 nlAttr->nla_len = (__u16)(dataLen + sizeof(nlattr));
175 nlAttr->nla_type = nlaType;
176 return padLength;
177}
178
179size_t fillNlAttrIpAddress(__u16 nlaType, int family, const std::string& value, nlattr* nlAttr,
180 Slice ipAddress) {
181 inet_pton(family, value.c_str(), ipAddress.base());
182 return fillNlAttr(nlaType, (family == AF_INET) ? sizeof(in_addr) : sizeof(in6_addr), nlAttr);
183}
184
185size_t fillNlAttrU32(__u16 nlaType, int32_t value, nlattr* nlAttr, uint32_t* u32Value) {
186 *u32Value = htonl(value);
187 return fillNlAttr(nlaType, sizeof((*u32Value)), nlAttr);
188}
189
190// returns the address family, placing the string in the provided buffer
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900191StatusOr<uint16_t> convertStringAddress(const std::string& addr, uint8_t* buffer) {
manojboopathi8707f232018-01-02 14:45:47 -0800192 if (inet_pton(AF_INET, addr.c_str(), buffer) == 1) {
193 return AF_INET;
194 } else if (inet_pton(AF_INET6, addr.c_str(), buffer) == 1) {
195 return AF_INET6;
196 } else {
197 return Status(EAFNOSUPPORT);
198 }
199}
200
ludi6e8eccd2017-08-14 14:40:37 -0700201// TODO: Need to consider a way to refer to the sSycalls instance
ludi4072ff22017-06-15 08:56:52 -0700202inline Syscalls& getSyscallInstance() { return netdutils::sSyscalls.get(); }
203
Nathan Harold1a371532017-01-30 12:30:48 -0800204class XfrmSocketImpl : public XfrmSocket {
205private:
206 static constexpr int NLMSG_DEFAULTSIZE = 8192;
207
208 union NetlinkResponse {
209 nlmsghdr hdr;
210 struct _err_ {
211 nlmsghdr hdr;
212 nlmsgerr err;
213 } err;
214
215 struct _buf_ {
216 nlmsghdr hdr;
217 char buf[NLMSG_DEFAULTSIZE];
218 } buf;
219 };
220
221public:
ludi6e8eccd2017-08-14 14:40:37 -0700222 netdutils::Status open() override {
Nathan Harold1a371532017-01-30 12:30:48 -0800223 mSock = openNetlinkSocket(NETLINK_XFRM);
ludi6e8eccd2017-08-14 14:40:37 -0700224 if (mSock < 0) {
Nathan Harold1a371532017-01-30 12:30:48 -0800225 ALOGW("Could not get a new socket, line=%d", __LINE__);
ludi6e8eccd2017-08-14 14:40:37 -0700226 return netdutils::statusFromErrno(-mSock, "Could not open netlink socket");
Nathan Harold1a371532017-01-30 12:30:48 -0800227 }
228
ludi6e8eccd2017-08-14 14:40:37 -0700229 return netdutils::status::ok;
Nathan Harold1a371532017-01-30 12:30:48 -0800230 }
231
ludi6e8eccd2017-08-14 14:40:37 -0700232 static netdutils::Status validateResponse(NetlinkResponse response, size_t len) {
Nathan Harold1a371532017-01-30 12:30:48 -0800233 if (len < sizeof(nlmsghdr)) {
234 ALOGW("Invalid response message received over netlink");
ludi6e8eccd2017-08-14 14:40:37 -0700235 return netdutils::statusFromErrno(EBADMSG, "Invalid message");
Nathan Harold1a371532017-01-30 12:30:48 -0800236 }
237
238 switch (response.hdr.nlmsg_type) {
239 case NLMSG_NOOP:
240 case NLMSG_DONE:
ludi6e8eccd2017-08-14 14:40:37 -0700241 return netdutils::status::ok;
Nathan Harold1a371532017-01-30 12:30:48 -0800242 case NLMSG_OVERRUN:
243 ALOGD("Netlink request overran kernel buffer");
ludi6e8eccd2017-08-14 14:40:37 -0700244 return netdutils::statusFromErrno(EBADMSG, "Kernel buffer overrun");
Nathan Harold1a371532017-01-30 12:30:48 -0800245 case NLMSG_ERROR:
246 if (len < sizeof(NetlinkResponse::_err_)) {
247 ALOGD("Netlink message received malformed error response");
ludi6e8eccd2017-08-14 14:40:37 -0700248 return netdutils::statusFromErrno(EBADMSG, "Malformed error response");
Nathan Harold1a371532017-01-30 12:30:48 -0800249 }
ludi6e8eccd2017-08-14 14:40:37 -0700250 return netdutils::statusFromErrno(
251 -response.err.err.error,
252 "Error netlink message"); // Netlink errors are negative errno.
Nathan Harold1a371532017-01-30 12:30:48 -0800253 case XFRM_MSG_NEWSA:
254 break;
255 }
256
257 if (response.hdr.nlmsg_type < XFRM_MSG_BASE /*== NLMSG_MIN_TYPE*/ ||
258 response.hdr.nlmsg_type > XFRM_MSG_MAX) {
259 ALOGD("Netlink message responded with an out-of-range message ID");
ludi6e8eccd2017-08-14 14:40:37 -0700260 return netdutils::statusFromErrno(EBADMSG, "Invalid message ID");
Nathan Harold1a371532017-01-30 12:30:48 -0800261 }
262
263 // TODO Add more message validation here
ludi6e8eccd2017-08-14 14:40:37 -0700264 return netdutils::status::ok;
Nathan Harold1a371532017-01-30 12:30:48 -0800265 }
266
ludi6e8eccd2017-08-14 14:40:37 -0700267 netdutils::Status sendMessage(uint16_t nlMsgType, uint16_t nlMsgFlags, uint16_t nlMsgSeqNum,
268 std::vector<iovec>* iovecs) const override {
Nathan Harold1a371532017-01-30 12:30:48 -0800269 nlmsghdr nlMsg = {
Nathan Harold7441c692017-12-12 21:25:01 -0800270 .nlmsg_type = nlMsgType,
271 .nlmsg_flags = nlMsgFlags,
272 .nlmsg_seq = nlMsgSeqNum,
Nathan Harold1a371532017-01-30 12:30:48 -0800273 };
274
ludie51e3862017-08-15 19:28:12 -0700275 (*iovecs)[0].iov_base = &nlMsg;
276 (*iovecs)[0].iov_len = NLMSG_HDRLEN;
277 for (const iovec& iov : *iovecs) {
278 nlMsg.nlmsg_len += iov.iov_len;
Nathan Harold1a371532017-01-30 12:30:48 -0800279 }
280
281 ALOGD("Sending Netlink XFRM Message: %s", xfrmMsgTypeToString(nlMsgType));
Manojd9c93c22017-10-19 13:40:26 -0700282 LOG_IOV(*iovecs);
Nathan Harold1a371532017-01-30 12:30:48 -0800283
ludie51e3862017-08-15 19:28:12 -0700284 StatusOr<size_t> writeResult = getSyscallInstance().writev(mSock, *iovecs);
ludi4072ff22017-06-15 08:56:52 -0700285 if (!isOk(writeResult)) {
286 ALOGE("netlink socket writev failed (%s)", toString(writeResult).c_str());
ludi6e8eccd2017-08-14 14:40:37 -0700287 return writeResult;
Nathan Harold1a371532017-01-30 12:30:48 -0800288 }
289
ludi4072ff22017-06-15 08:56:52 -0700290 if (nlMsg.nlmsg_len != writeResult.value()) {
291 ALOGE("Invalid netlink message length sent %d", static_cast<int>(writeResult.value()));
ludi6e8eccd2017-08-14 14:40:37 -0700292 return netdutils::statusFromErrno(EBADMSG, "Invalid message length");
Nathan Harold1a371532017-01-30 12:30:48 -0800293 }
294
ludi4072ff22017-06-15 08:56:52 -0700295 NetlinkResponse response = {};
Nathan Harold1a371532017-01-30 12:30:48 -0800296
ludi4072ff22017-06-15 08:56:52 -0700297 StatusOr<Slice> readResult =
298 getSyscallInstance().read(Fd(mSock), netdutils::makeSlice(response));
299 if (!isOk(readResult)) {
300 ALOGE("netlink response error (%s)", toString(readResult).c_str());
ludi6e8eccd2017-08-14 14:40:37 -0700301 return readResult;
ludi4072ff22017-06-15 08:56:52 -0700302 }
303
304 LOG_HEX("netlink msg resp", reinterpret_cast<char*>(readResult.value().base()),
305 readResult.value().size());
306
ludi6e8eccd2017-08-14 14:40:37 -0700307 Status validateStatus = validateResponse(response, readResult.value().size());
308 if (!isOk(validateStatus)) {
309 ALOGE("netlink response contains error (%s)", toString(validateStatus).c_str());
310 }
311
312 return validateStatus;
Nathan Harold1a371532017-01-30 12:30:48 -0800313 }
314};
315
ludi6e8eccd2017-08-14 14:40:37 -0700316StatusOr<int> convertToXfrmAddr(const std::string& strAddr, xfrm_address_t* xfrmAddr) {
Nathan Harold1a371532017-01-30 12:30:48 -0800317 if (strAddr.length() == 0) {
318 memset(xfrmAddr, 0, sizeof(*xfrmAddr));
319 return AF_UNSPEC;
320 }
321
322 if (inet_pton(AF_INET6, strAddr.c_str(), reinterpret_cast<void*>(xfrmAddr))) {
323 return AF_INET6;
324 } else if (inet_pton(AF_INET, strAddr.c_str(), reinterpret_cast<void*>(xfrmAddr))) {
325 return AF_INET;
326 } else {
ludi6e8eccd2017-08-14 14:40:37 -0700327 return netdutils::statusFromErrno(EAFNOSUPPORT, "Invalid address family");
Nathan Harold1a371532017-01-30 12:30:48 -0800328 }
329}
330
331void fillXfrmNlaHdr(nlattr* hdr, uint16_t type, uint16_t len) {
332 hdr->nla_type = type;
333 hdr->nla_len = len;
334}
335
336void fillXfrmCurLifetimeDefaults(xfrm_lifetime_cur* cur) {
337 memset(reinterpret_cast<char*>(cur), 0, sizeof(*cur));
338}
339void fillXfrmLifetimeDefaults(xfrm_lifetime_cfg* cfg) {
340 cfg->soft_byte_limit = XFRM_INF;
341 cfg->hard_byte_limit = XFRM_INF;
342 cfg->soft_packet_limit = XFRM_INF;
343 cfg->hard_packet_limit = XFRM_INF;
344}
345
346/*
347 * Allocate SPIs within an (inclusive) range of min-max.
348 * returns 0 (INVALID_SPI) once the entire range has been parsed.
349 */
350class RandomSpi {
351public:
352 RandomSpi(int min, int max) : mMin(min) {
Nathan Harold1e284452017-10-10 13:31:19 -0700353 // Re-seeding should be safe because the seed itself is
354 // sufficiently random and we don't need secure random
355 std::mt19937 rnd = std::mt19937(std::random_device()());
356 mNext = std::uniform_int_distribution<>(1, INT_MAX)(rnd);
Nathan Harold1a371532017-01-30 12:30:48 -0800357 mSize = max - min + 1;
358 mCount = mSize;
359 }
360
361 uint32_t next() {
362 if (!mCount)
363 return 0;
364 mCount--;
365 return (mNext++ % mSize) + mMin;
366 }
367
368private:
369 uint32_t mNext;
370 uint32_t mSize;
371 uint32_t mMin;
372 uint32_t mCount;
373};
374
375} // namespace
376
377//
378// Begin XfrmController Impl
379//
380//
381XfrmController::XfrmController(void) {}
382
Nathan Harold21299f72018-03-16 20:13:03 -0700383netdutils::Status XfrmController::Init() {
384 RETURN_IF_NOT_OK(flushInterfaces());
385 XfrmSocketImpl sock;
386 RETURN_IF_NOT_OK(sock.open());
387 RETURN_IF_NOT_OK(flushSaDb(sock));
388 return flushPolicyDb(sock);
389}
390
391netdutils::Status XfrmController::flushInterfaces() {
392 const auto& ifaces = InterfaceController::getIfaceNames();
393 RETURN_IF_NOT_OK(ifaces);
Nathan Harold45c35662018-04-23 10:10:18 -0700394 const String8 ifPrefix8 = String8(INetd::IPSEC_INTERFACE_PREFIX().string());
Nathan Harold21299f72018-03-16 20:13:03 -0700395
396 for (const std::string& iface : ifaces.value()) {
397 int status = 0;
398 // Look for the reserved interface prefix, which must be in the name at position 0
Nathan Haroldb6bd53e2018-05-14 11:56:59 -0700399 if (android::base::StartsWith(iface.c_str(), ifPrefix8.c_str()) &&
Nathan Harold21299f72018-03-16 20:13:03 -0700400 (status = removeVirtualTunnelInterface(iface)) < 0) {
401 ALOGE("Failed to delete ipsec tunnel %s.", iface.c_str());
402 return netdutils::statusFromErrno(status, "Failed to remove ipsec tunnel.");
403 }
404 }
405 return netdutils::status::ok;
406}
407
408netdutils::Status XfrmController::flushSaDb(const XfrmSocket& s) {
409 struct xfrm_usersa_flush flushUserSa = {.proto = IPSEC_PROTO_ANY};
410
Yi Kongbdfd57e2018-07-25 13:26:10 -0700411 std::vector<iovec> iov = {{nullptr, 0}, // reserved for the eventual addition of a NLMSG_HDR
Nathan Harold21299f72018-03-16 20:13:03 -0700412 {&flushUserSa, sizeof(flushUserSa)}, // xfrm_usersa_flush structure
413 {kPadBytes, NLMSG_ALIGN(sizeof(flushUserSa)) - sizeof(flushUserSa)}};
414
415 return s.sendMessage(XFRM_MSG_FLUSHSA, NETLINK_REQUEST_FLAGS, 0, &iov);
416}
417
418netdutils::Status XfrmController::flushPolicyDb(const XfrmSocket& s) {
Yi Kongbdfd57e2018-07-25 13:26:10 -0700419 std::vector<iovec> iov = {{nullptr, 0}}; // reserved for the eventual addition of a NLMSG_HDR
Nathan Harold21299f72018-03-16 20:13:03 -0700420 return s.sendMessage(XFRM_MSG_FLUSHPOLICY, NETLINK_REQUEST_FLAGS, 0, &iov);
421}
422
Benedict Wongb2daefb2017-12-06 22:05:46 -0800423netdutils::Status XfrmController::ipSecSetEncapSocketOwner(const android::base::unique_fd& socket,
424 int newUid, uid_t callerUid) {
425 ALOGD("XfrmController:%s, line=%d", __FUNCTION__, __LINE__);
426
427 const int fd = socket.get();
428 struct stat info;
429 if (fstat(fd, &info)) {
430 return netdutils::statusFromErrno(errno, "Failed to stat socket file descriptor");
431 }
432 if (info.st_uid != callerUid) {
433 return netdutils::statusFromErrno(EPERM, "fchown disabled for non-owner calls");
434 }
Nathan Haroldda54f122018-01-09 16:42:57 -0800435 if (S_ISSOCK(info.st_mode) == 0) {
Benedict Wongb2daefb2017-12-06 22:05:46 -0800436 return netdutils::statusFromErrno(EINVAL, "File descriptor was not a socket");
437 }
438
439 int optval;
440 socklen_t optlen;
Nathan Haroldda54f122018-01-09 16:42:57 -0800441 netdutils::Status status =
442 getSyscallInstance().getsockopt(Fd(socket), IPPROTO_UDP, UDP_ENCAP, &optval, &optlen);
Benedict Wongb2daefb2017-12-06 22:05:46 -0800443 if (status != netdutils::status::ok) {
444 return status;
445 }
Nathan Haroldda54f122018-01-09 16:42:57 -0800446 if (optval != UDP_ENCAP_ESPINUDP && optval != UDP_ENCAP_ESPINUDP_NON_IKE) {
Benedict Wongb2daefb2017-12-06 22:05:46 -0800447 return netdutils::statusFromErrno(EINVAL, "Socket did not have UDP-encap sockopt set");
448 }
449 if (fchown(fd, newUid, -1)) {
450 return netdutils::statusFromErrno(errno, "Failed to fchown socket file descriptor");
451 }
452
453 return netdutils::status::ok;
454}
455
Nathan Haroldda54f122018-01-09 16:42:57 -0800456netdutils::Status XfrmController::ipSecAllocateSpi(int32_t transformId,
457 const std::string& sourceAddress,
458 const std::string& destinationAddress,
459 int32_t inSpi, int32_t* outSpi) {
Nathan Harold1a371532017-01-30 12:30:48 -0800460 ALOGD("XfrmController:%s, line=%d", __FUNCTION__, __LINE__);
461 ALOGD("transformId=%d", transformId);
Nathan Haroldda54f122018-01-09 16:42:57 -0800462 ALOGD("sourceAddress=%s", sourceAddress.c_str());
463 ALOGD("destinationAddress=%s", destinationAddress.c_str());
Nathan Harold1a371532017-01-30 12:30:48 -0800464 ALOGD("inSpi=%0.8x", inSpi);
465
466 XfrmSaInfo saInfo{};
Benedict Wonga04ffa72018-05-09 21:42:42 -0700467 netdutils::Status ret = fillXfrmCommonInfo(sourceAddress, destinationAddress, INVALID_SPI, 0, 0,
468 transformId, &saInfo);
ludi6e8eccd2017-08-14 14:40:37 -0700469 if (!isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800470 return ret;
471 }
472
473 XfrmSocketImpl sock;
ludi6e8eccd2017-08-14 14:40:37 -0700474 netdutils::Status socketStatus = sock.open();
475 if (!isOk(socketStatus)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800476 ALOGD("Sock open failed for XFRM, line=%d", __LINE__);
ludi6e8eccd2017-08-14 14:40:37 -0700477 return socketStatus;
Nathan Harold1a371532017-01-30 12:30:48 -0800478 }
479
480 int minSpi = RAND_SPI_MIN, maxSpi = RAND_SPI_MAX;
481
482 if (inSpi)
483 minSpi = maxSpi = inSpi;
ludi6e8eccd2017-08-14 14:40:37 -0700484
Nathan Harold1a371532017-01-30 12:30:48 -0800485 ret = allocateSpi(saInfo, minSpi, maxSpi, reinterpret_cast<uint32_t*>(outSpi), sock);
ludi6e8eccd2017-08-14 14:40:37 -0700486 if (!isOk(ret)) {
487 // TODO: May want to return a new Status with a modified status string
Nathan Harold1a371532017-01-30 12:30:48 -0800488 ALOGD("Failed to Allocate an SPI, line=%d", __LINE__);
489 *outSpi = INVALID_SPI;
490 }
491
492 return ret;
493}
494
ludi6e8eccd2017-08-14 14:40:37 -0700495netdutils::Status XfrmController::ipSecAddSecurityAssociation(
Nathan Haroldda54f122018-01-09 16:42:57 -0800496 int32_t transformId, int32_t mode, const std::string& sourceAddress,
manojboopathi8707f232018-01-02 14:45:47 -0800497 const std::string& destinationAddress, int32_t underlyingNetId, int32_t spi, int32_t markValue,
498 int32_t markMask, const std::string& authAlgo, const std::vector<uint8_t>& authKey,
499 int32_t authTruncBits, const std::string& cryptAlgo, const std::vector<uint8_t>& cryptKey,
500 int32_t cryptTruncBits, const std::string& aeadAlgo, const std::vector<uint8_t>& aeadKey,
501 int32_t aeadIcvBits, int32_t encapType, int32_t encapLocalPort, int32_t encapRemotePort) {
Nathan Harold1a371532017-01-30 12:30:48 -0800502 ALOGD("XfrmController::%s, line=%d", __FUNCTION__, __LINE__);
503 ALOGD("transformId=%d", transformId);
504 ALOGD("mode=%d", mode);
Nathan Haroldda54f122018-01-09 16:42:57 -0800505 ALOGD("sourceAddress=%s", sourceAddress.c_str());
506 ALOGD("destinationAddress=%s", destinationAddress.c_str());
Benedict Wong96abf482018-01-22 13:56:41 -0800507 ALOGD("underlyingNetworkId=%d", underlyingNetId);
Nathan Harold1a371532017-01-30 12:30:48 -0800508 ALOGD("spi=%0.8x", spi);
Di Lu2ccb3e52018-01-03 16:19:20 -0800509 ALOGD("markValue=%x", markValue);
510 ALOGD("markMask=%x", markMask);
Nathan Harold1a371532017-01-30 12:30:48 -0800511 ALOGD("authAlgo=%s", authAlgo.c_str());
512 ALOGD("authTruncBits=%d", authTruncBits);
513 ALOGD("cryptAlgo=%s", cryptAlgo.c_str());
514 ALOGD("cryptTruncBits=%d,", cryptTruncBits);
Benedict Wongbe65b432017-08-22 21:43:14 -0700515 ALOGD("aeadAlgo=%s", aeadAlgo.c_str());
516 ALOGD("aeadIcvBits=%d,", aeadIcvBits);
Nathan Harold1a371532017-01-30 12:30:48 -0800517 ALOGD("encapType=%d", encapType);
518 ALOGD("encapLocalPort=%d", encapLocalPort);
519 ALOGD("encapRemotePort=%d", encapRemotePort);
520
521 XfrmSaInfo saInfo{};
Benedict Wonga04ffa72018-05-09 21:42:42 -0700522 netdutils::Status ret = fillXfrmCommonInfo(sourceAddress, destinationAddress, spi, markValue,
523 markMask, transformId, &saInfo);
ludi6e8eccd2017-08-14 14:40:37 -0700524 if (!isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800525 return ret;
526 }
527
Nathan Harold1a371532017-01-30 12:30:48 -0800528 saInfo.auth = XfrmAlgo{
529 .name = authAlgo, .key = authKey, .truncLenBits = static_cast<uint16_t>(authTruncBits)};
530
531 saInfo.crypt = XfrmAlgo{
532 .name = cryptAlgo, .key = cryptKey, .truncLenBits = static_cast<uint16_t>(cryptTruncBits)};
533
Benedict Wongbe65b432017-08-22 21:43:14 -0700534 saInfo.aead = XfrmAlgo{
535 .name = aeadAlgo, .key = aeadKey, .truncLenBits = static_cast<uint16_t>(aeadIcvBits)};
536
Nathan Harold1a371532017-01-30 12:30:48 -0800537 switch (static_cast<XfrmMode>(mode)) {
538 case XfrmMode::TRANSPORT:
539 case XfrmMode::TUNNEL:
540 saInfo.mode = static_cast<XfrmMode>(mode);
541 break;
542 default:
ludi6e8eccd2017-08-14 14:40:37 -0700543 return netdutils::statusFromErrno(EINVAL, "Invalid xfrm mode");
Nathan Harold1a371532017-01-30 12:30:48 -0800544 }
545
546 XfrmSocketImpl sock;
ludi6e8eccd2017-08-14 14:40:37 -0700547 netdutils::Status socketStatus = sock.open();
548 if (!isOk(socketStatus)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800549 ALOGD("Sock open failed for XFRM, line=%d", __LINE__);
ludi6e8eccd2017-08-14 14:40:37 -0700550 return socketStatus;
Nathan Harold1a371532017-01-30 12:30:48 -0800551 }
552
Nathan Harold420ceac2017-04-05 19:36:59 -0700553 switch (static_cast<XfrmEncapType>(encapType)) {
554 case XfrmEncapType::ESPINUDP:
555 case XfrmEncapType::ESPINUDP_NON_IKE:
556 if (saInfo.addrFamily != AF_INET) {
ludi6e8eccd2017-08-14 14:40:37 -0700557 return netdutils::statusFromErrno(EAFNOSUPPORT, "IPv6 encap not supported");
Nathan Harold420ceac2017-04-05 19:36:59 -0700558 }
Nathan Haroldda54f122018-01-09 16:42:57 -0800559 // The ports are not used on input SAs, so this is OK to be wrong when
560 // direction is ultimately input.
561 saInfo.encap.srcPort = encapLocalPort;
562 saInfo.encap.dstPort = encapRemotePort;
Nathan Harold420ceac2017-04-05 19:36:59 -0700563 // fall through
564 case XfrmEncapType::NONE:
565 saInfo.encap.type = static_cast<XfrmEncapType>(encapType);
566 break;
567 default:
ludi6e8eccd2017-08-14 14:40:37 -0700568 return netdutils::statusFromErrno(EINVAL, "Invalid encap type");
Nathan Harold420ceac2017-04-05 19:36:59 -0700569 }
570
Benedict Wong96abf482018-01-22 13:56:41 -0800571 saInfo.netId = underlyingNetId;
572
Di Lu0e16b5e2018-01-12 10:37:53 -0800573 ret = updateSecurityAssociation(saInfo, sock);
ludi6e8eccd2017-08-14 14:40:37 -0700574 if (!isOk(ret)) {
Di Lu0e16b5e2018-01-12 10:37:53 -0800575 ALOGD("Failed updating a Security Association, line=%d", __LINE__);
Nathan Harold1a371532017-01-30 12:30:48 -0800576 }
577
ludi6e8eccd2017-08-14 14:40:37 -0700578 return ret;
Nathan Harold1a371532017-01-30 12:30:48 -0800579}
580
Di Lu2ccb3e52018-01-03 16:19:20 -0800581netdutils::Status XfrmController::ipSecDeleteSecurityAssociation(
582 int32_t transformId, const std::string& sourceAddress, const std::string& destinationAddress,
583 int32_t spi, int32_t markValue, int32_t markMask) {
Nathan Harold1a371532017-01-30 12:30:48 -0800584 ALOGD("XfrmController:%s, line=%d", __FUNCTION__, __LINE__);
585 ALOGD("transformId=%d", transformId);
Nathan Haroldda54f122018-01-09 16:42:57 -0800586 ALOGD("sourceAddress=%s", sourceAddress.c_str());
587 ALOGD("destinationAddress=%s", destinationAddress.c_str());
Nathan Harold1a371532017-01-30 12:30:48 -0800588 ALOGD("spi=%0.8x", spi);
Di Lu2ccb3e52018-01-03 16:19:20 -0800589 ALOGD("markValue=%x", markValue);
590 ALOGD("markMask=%x", markMask);
Nathan Harold1a371532017-01-30 12:30:48 -0800591
Benedict Wonga04ffa72018-05-09 21:42:42 -0700592 XfrmSaInfo saInfo{};
593 netdutils::Status ret = fillXfrmCommonInfo(sourceAddress, destinationAddress, spi, markValue,
594 markMask, transformId, &saInfo);
ludi6e8eccd2017-08-14 14:40:37 -0700595 if (!isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800596 return ret;
597 }
598
599 XfrmSocketImpl sock;
ludi6e8eccd2017-08-14 14:40:37 -0700600 netdutils::Status socketStatus = sock.open();
601 if (!isOk(socketStatus)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800602 ALOGD("Sock open failed for XFRM, line=%d", __LINE__);
ludi6e8eccd2017-08-14 14:40:37 -0700603 return socketStatus;
Nathan Harold1a371532017-01-30 12:30:48 -0800604 }
605
Benedict Wonga04ffa72018-05-09 21:42:42 -0700606 ret = deleteSecurityAssociation(saInfo, sock);
ludi6e8eccd2017-08-14 14:40:37 -0700607 if (!isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800608 ALOGD("Failed to delete Security Association, line=%d", __LINE__);
Nathan Harold1a371532017-01-30 12:30:48 -0800609 }
610
611 return ret;
612}
613
Benedict Wonga04ffa72018-05-09 21:42:42 -0700614netdutils::Status XfrmController::fillXfrmCommonInfo(const std::string& sourceAddress,
615 const std::string& destinationAddress,
616 int32_t spi, int32_t markValue,
617 int32_t markMask, int32_t transformId,
618 XfrmCommonInfo* info) {
Nathan Harold7441c692017-12-12 21:25:01 -0800619 // Use the addresses to determine the address family and do validation
Nathan Haroldda54f122018-01-09 16:42:57 -0800620 xfrm_address_t sourceXfrmAddr{}, destXfrmAddr{};
621 StatusOr<int> sourceFamily, destFamily;
622 sourceFamily = convertToXfrmAddr(sourceAddress, &sourceXfrmAddr);
623 destFamily = convertToXfrmAddr(destinationAddress, &destXfrmAddr);
624 if (!isOk(sourceFamily) || !isOk(destFamily)) {
625 return netdutils::statusFromErrno(EINVAL, "Invalid address " + sourceAddress + "/" +
626 destinationAddress);
Nathan Harold1a371532017-01-30 12:30:48 -0800627 }
628
Nathan Haroldda54f122018-01-09 16:42:57 -0800629 if (destFamily.value() == AF_UNSPEC ||
630 (sourceFamily.value() != AF_UNSPEC && sourceFamily.value() != destFamily.value())) {
631 ALOGD("Invalid or Mismatched Address Families, %d != %d, line=%d", sourceFamily.value(),
632 destFamily.value(), __LINE__);
ludi6e8eccd2017-08-14 14:40:37 -0700633 return netdutils::statusFromErrno(EINVAL, "Invalid or mismatched address families");
Nathan Harold1a371532017-01-30 12:30:48 -0800634 }
635
Benedict Wonga04ffa72018-05-09 21:42:42 -0700636 info->addrFamily = destFamily.value();
Nathan Harold1a371532017-01-30 12:30:48 -0800637
Benedict Wonga04ffa72018-05-09 21:42:42 -0700638 info->dstAddr = destXfrmAddr;
639 info->srcAddr = sourceXfrmAddr;
640
641 return fillXfrmCommonInfo(spi, markValue, markMask, transformId, info);
642}
643
644netdutils::Status XfrmController::fillXfrmCommonInfo(int32_t spi, int32_t markValue,
645 int32_t markMask, int32_t transformId,
646 XfrmCommonInfo* info) {
647 info->transformId = transformId;
648 info->spi = htonl(spi);
649 info->mark.v = markValue;
650 info->mark.m = markMask;
651
ludi6e8eccd2017-08-14 14:40:37 -0700652 return netdutils::status::ok;
Nathan Harold1a371532017-01-30 12:30:48 -0800653}
654
ludi6e8eccd2017-08-14 14:40:37 -0700655netdutils::Status XfrmController::ipSecApplyTransportModeTransform(
656 const android::base::unique_fd& socket, int32_t transformId, int32_t direction,
Nathan Haroldda54f122018-01-09 16:42:57 -0800657 const std::string& sourceAddress, const std::string& destinationAddress, int32_t spi) {
Nathan Harold1a371532017-01-30 12:30:48 -0800658 ALOGD("XfrmController::%s, line=%d", __FUNCTION__, __LINE__);
659 ALOGD("transformId=%d", transformId);
660 ALOGD("direction=%d", direction);
Nathan Haroldda54f122018-01-09 16:42:57 -0800661 ALOGD("sourceAddress=%s", sourceAddress.c_str());
662 ALOGD("destinationAddress=%s", destinationAddress.c_str());
Nathan Harold1a371532017-01-30 12:30:48 -0800663 ALOGD("spi=%0.8x", spi);
664
ludi4072ff22017-06-15 08:56:52 -0700665 StatusOr<sockaddr_storage> ret = getSyscallInstance().getsockname<sockaddr_storage>(Fd(socket));
666 if (!isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800667 ALOGE("Failed to get socket info in %s", __FUNCTION__);
ludi6e8eccd2017-08-14 14:40:37 -0700668 return ret;
Nathan Harold1a371532017-01-30 12:30:48 -0800669 }
Nathan Harold7441c692017-12-12 21:25:01 -0800670 struct sockaddr_storage saddr = ret.value();
ludi4072ff22017-06-15 08:56:52 -0700671
Benedict Wonga04ffa72018-05-09 21:42:42 -0700672 XfrmSpInfo spInfo{};
Nathan Harold7441c692017-12-12 21:25:01 -0800673 netdutils::Status status =
Benedict Wonga04ffa72018-05-09 21:42:42 -0700674 fillXfrmCommonInfo(sourceAddress, destinationAddress, spi, 0, 0, transformId, &spInfo);
ludi6e8eccd2017-08-14 14:40:37 -0700675 if (!isOk(status)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800676 ALOGE("Couldn't build SA ID %s", __FUNCTION__);
ludi6e8eccd2017-08-14 14:40:37 -0700677 return status;
Nathan Harold1a371532017-01-30 12:30:48 -0800678 }
679
Benedict Wonga04ffa72018-05-09 21:42:42 -0700680 spInfo.selAddrFamily = spInfo.addrFamily;
681
682 // Allow dual stack sockets. Dual stack sockets are guaranteed to never have an AF_INET source
683 // address; the source address would instead be an IPv4-mapped address. Thus, disallow AF_INET
684 // sockets with mismatched address families (All other cases are acceptable).
685 if (saddr.ss_family == AF_INET && spInfo.addrFamily != AF_INET) {
manojboopathi26f42922017-12-14 10:51:57 -0800686 ALOGE("IPV4 socket address family(%d) should match IPV4 Transform "
687 "address family(%d)!",
Benedict Wonga04ffa72018-05-09 21:42:42 -0700688 saddr.ss_family, spInfo.addrFamily);
ludi6e8eccd2017-08-14 14:40:37 -0700689 return netdutils::statusFromErrno(EINVAL, "Mismatched address family");
Nathan Harold1a371532017-01-30 12:30:48 -0800690 }
691
692 struct {
693 xfrm_userpolicy_info info;
694 xfrm_user_tmpl tmpl;
695 } policy{};
696
Benedict Wonga04ffa72018-05-09 21:42:42 -0700697 fillUserSpInfo(spInfo, static_cast<XfrmDirection>(direction), &policy.info);
698 fillUserTemplate(spInfo, &policy.tmpl);
Nathan Harold1a371532017-01-30 12:30:48 -0800699
700 LOG_HEX("XfrmUserPolicy", reinterpret_cast<char*>(&policy), sizeof(policy));
701
702 int sockOpt, sockLayer;
manojboopathi26f42922017-12-14 10:51:57 -0800703 switch (saddr.ss_family) {
Nathan Harold1a371532017-01-30 12:30:48 -0800704 case AF_INET:
705 sockOpt = IP_XFRM_POLICY;
706 sockLayer = SOL_IP;
707 break;
708 case AF_INET6:
709 sockOpt = IPV6_XFRM_POLICY;
710 sockLayer = SOL_IPV6;
711 break;
712 default:
ludi6e8eccd2017-08-14 14:40:37 -0700713 return netdutils::statusFromErrno(EAFNOSUPPORT, "Invalid address family");
Nathan Harold1a371532017-01-30 12:30:48 -0800714 }
715
ludi6e8eccd2017-08-14 14:40:37 -0700716 status = getSyscallInstance().setsockopt(Fd(socket), sockLayer, sockOpt, policy);
ludi4072ff22017-06-15 08:56:52 -0700717 if (!isOk(status)) {
718 ALOGE("Error setting socket option for XFRM! (%s)", toString(status).c_str());
Nathan Harold1a371532017-01-30 12:30:48 -0800719 }
ludi6e8eccd2017-08-14 14:40:37 -0700720
721 return status;
Nathan Harold1a371532017-01-30 12:30:48 -0800722}
723
ludi6e8eccd2017-08-14 14:40:37 -0700724netdutils::Status
725XfrmController::ipSecRemoveTransportModeTransform(const android::base::unique_fd& socket) {
ludi87991632017-10-30 15:28:11 -0700726 ALOGD("XfrmController::%s, line=%d", __FUNCTION__, __LINE__);
727
728 StatusOr<sockaddr_storage> ret = getSyscallInstance().getsockname<sockaddr_storage>(Fd(socket));
729 if (!isOk(ret)) {
730 ALOGE("Failed to get socket info in %s! (%s)", __FUNCTION__, toString(ret).c_str());
731 return ret;
732 }
733
734 int sockOpt, sockLayer;
735 switch (ret.value().ss_family) {
736 case AF_INET:
737 sockOpt = IP_XFRM_POLICY;
738 sockLayer = SOL_IP;
739 break;
740 case AF_INET6:
741 sockOpt = IPV6_XFRM_POLICY;
742 sockLayer = SOL_IPV6;
743 break;
744 default:
745 return netdutils::statusFromErrno(EAFNOSUPPORT, "Invalid address family");
746 }
747
748 // Kernel will delete the security policy on this socket for both direction
749 // if optval is set to NULL and optlen is set to 0.
750 netdutils::Status status =
Yi Kongbdfd57e2018-07-25 13:26:10 -0700751 getSyscallInstance().setsockopt(Fd(socket), sockLayer, sockOpt, nullptr, 0);
ludi87991632017-10-30 15:28:11 -0700752 if (!isOk(status)) {
753 ALOGE("Error removing socket option for XFRM! (%s)", toString(status).c_str());
754 }
755
756 return status;
Nathan Harold1a371532017-01-30 12:30:48 -0800757}
758
Benedict Wonga04ffa72018-05-09 21:42:42 -0700759netdutils::Status XfrmController::ipSecAddSecurityPolicy(int32_t transformId, int32_t selAddrFamily,
760 int32_t direction,
Benedict Wongad600cb2018-05-14 17:22:35 -0700761 const std::string& tmplSrcAddress,
762 const std::string& tmplDstAddress,
Di Lu2ccb3e52018-01-03 16:19:20 -0800763 int32_t spi, int32_t markValue,
764 int32_t markMask) {
Benedict Wonga04ffa72018-05-09 21:42:42 -0700765 return processSecurityPolicy(transformId, selAddrFamily, direction, tmplSrcAddress,
766 tmplDstAddress, spi, markValue, markMask, XFRM_MSG_NEWPOLICY);
ludi771b8002017-11-20 15:09:05 -0800767}
768
Benedict Wonga04ffa72018-05-09 21:42:42 -0700769netdutils::Status XfrmController::ipSecUpdateSecurityPolicy(
770 int32_t transformId, int32_t selAddrFamily, int32_t direction,
771 const std::string& tmplSrcAddress, const std::string& tmplDstAddress, int32_t spi,
772 int32_t markValue, int32_t markMask) {
773 return processSecurityPolicy(transformId, selAddrFamily, direction, tmplSrcAddress,
774 tmplDstAddress, spi, markValue, markMask, XFRM_MSG_UPDPOLICY);
775}
776
777netdutils::Status XfrmController::ipSecDeleteSecurityPolicy(int32_t transformId,
778 int32_t selAddrFamily,
779 int32_t direction, int32_t markValue,
Di Lu2ccb3e52018-01-03 16:19:20 -0800780 int32_t markMask) {
Benedict Wonga04ffa72018-05-09 21:42:42 -0700781 return processSecurityPolicy(transformId, selAddrFamily, direction, "", "", 0, markValue,
782 markMask, XFRM_MSG_DELPOLICY);
ludi771b8002017-11-20 15:09:05 -0800783}
784
Benedict Wonga04ffa72018-05-09 21:42:42 -0700785netdutils::Status XfrmController::processSecurityPolicy(int32_t transformId, int32_t selAddrFamily,
786 int32_t direction,
Benedict Wongad600cb2018-05-14 17:22:35 -0700787 const std::string& tmplSrcAddress,
788 const std::string& tmplDstAddress,
Di Lu2ccb3e52018-01-03 16:19:20 -0800789 int32_t spi, int32_t markValue,
790 int32_t markMask, int32_t msgType) {
ludi771b8002017-11-20 15:09:05 -0800791 ALOGD("XfrmController::%s, line=%d", __FUNCTION__, __LINE__);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700792 ALOGD("selAddrFamily=%s", selAddrFamily == AF_INET6 ? "AF_INET6" : "AF_INET");
ludi771b8002017-11-20 15:09:05 -0800793 ALOGD("transformId=%d", transformId);
794 ALOGD("direction=%d", direction);
Benedict Wongad600cb2018-05-14 17:22:35 -0700795 ALOGD("tmplSrcAddress=%s", tmplSrcAddress.c_str());
796 ALOGD("tmplDstAddress=%s", tmplDstAddress.c_str());
ludi771b8002017-11-20 15:09:05 -0800797 ALOGD("spi=%0.8x", spi);
Di Lu2ccb3e52018-01-03 16:19:20 -0800798 ALOGD("markValue=%d", markValue);
799 ALOGD("markMask=%d", markMask);
ludi771b8002017-11-20 15:09:05 -0800800 ALOGD("msgType=%d", msgType);
801
Benedict Wonga04ffa72018-05-09 21:42:42 -0700802 XfrmSpInfo spInfo{};
803 spInfo.mode = XfrmMode::TUNNEL;
ludi771b8002017-11-20 15:09:05 -0800804
805 XfrmSocketImpl sock;
806 RETURN_IF_NOT_OK(sock.open());
807
Benedict Wonga04ffa72018-05-09 21:42:42 -0700808 // Set the correct address families. Tunnel mode policies use wildcard selectors, while
809 // templates have addresses set. These may be different address families. This method is called
810 // separately for IPv4 and IPv6 policies, and thus only need to map a single inner address
811 // family to the outer address families.
812 spInfo.selAddrFamily = selAddrFamily;
ludi771b8002017-11-20 15:09:05 -0800813
814 if (msgType == XFRM_MSG_DELPOLICY) {
Benedict Wonga04ffa72018-05-09 21:42:42 -0700815 RETURN_IF_NOT_OK(fillXfrmCommonInfo(spi, markValue, markMask, transformId, &spInfo));
816
817 return deleteTunnelModeSecurityPolicy(spInfo, sock, static_cast<XfrmDirection>(direction));
ludi771b8002017-11-20 15:09:05 -0800818 } else {
Benedict Wonga04ffa72018-05-09 21:42:42 -0700819 RETURN_IF_NOT_OK(fillXfrmCommonInfo(tmplSrcAddress, tmplDstAddress, spi, markValue,
820 markMask, transformId, &spInfo));
821
822 return updateTunnelModeSecurityPolicy(spInfo, sock, static_cast<XfrmDirection>(direction),
ludi771b8002017-11-20 15:09:05 -0800823 msgType);
824 }
825}
826
Benedict Wonga04ffa72018-05-09 21:42:42 -0700827void XfrmController::fillXfrmSelector(const int selAddrFamily, xfrm_selector* selector) {
828 selector->family = selAddrFamily;
manojboopathi8707f232018-01-02 14:45:47 -0800829 selector->proto = AF_UNSPEC; // TODO: do we need to match the protocol? it's
830 // possible via the socket
Nathan Harold1a371532017-01-30 12:30:48 -0800831}
832
Di Lu0e16b5e2018-01-12 10:37:53 -0800833netdutils::Status XfrmController::updateSecurityAssociation(const XfrmSaInfo& record,
manojboopathi4d2d6f12017-12-06 11:11:31 -0800834 const XfrmSocket& sock) {
Nathan Harold1a371532017-01-30 12:30:48 -0800835 xfrm_usersa_info usersa{};
836 nlattr_algo_crypt crypt{};
837 nlattr_algo_auth auth{};
Benedict Wongbe65b432017-08-22 21:43:14 -0700838 nlattr_algo_aead aead{};
Di Lu2ccb3e52018-01-03 16:19:20 -0800839 nlattr_xfrm_mark xfrmmark{};
Benedict Wong96abf482018-01-22 13:56:41 -0800840 nlattr_xfrm_output_mark xfrmoutputmark{};
Nathan Harold420ceac2017-04-05 19:36:59 -0700841 nlattr_encap_tmpl encap{};
Nathan Harold1a371532017-01-30 12:30:48 -0800842
Benedict Wongbe65b432017-08-22 21:43:14 -0700843 enum {
844 NLMSG_HDR,
845 USERSA,
846 USERSA_PAD,
847 CRYPT,
848 CRYPT_PAD,
849 AUTH,
850 AUTH_PAD,
851 AEAD,
852 AEAD_PAD,
Di Lu2ccb3e52018-01-03 16:19:20 -0800853 MARK,
854 MARK_PAD,
Benedict Wong96abf482018-01-22 13:56:41 -0800855 OUTPUT_MARK,
856 OUTPUT_MARK_PAD,
Benedict Wongbe65b432017-08-22 21:43:14 -0700857 ENCAP,
Di Lu2ccb3e52018-01-03 16:19:20 -0800858 ENCAP_PAD,
Benedict Wongbe65b432017-08-22 21:43:14 -0700859 };
Nathan Harold1a371532017-01-30 12:30:48 -0800860
ludie51e3862017-08-15 19:28:12 -0700861 std::vector<iovec> iov = {
Yi Kongbdfd57e2018-07-25 13:26:10 -0700862 {nullptr, 0}, // reserved for the eventual addition of a NLMSG_HDR
Benedict Wong96abf482018-01-22 13:56:41 -0800863 {&usersa, 0}, // main usersa_info struct
864 {kPadBytes, 0}, // up to NLMSG_ALIGNTO pad bytes of padding
865 {&crypt, 0}, // adjust size if crypt algo is present
866 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
867 {&auth, 0}, // adjust size if auth algo is present
868 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
869 {&aead, 0}, // adjust size if aead algo is present
870 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
871 {&xfrmmark, 0}, // adjust size if xfrm mark is present
872 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
873 {&xfrmoutputmark, 0}, // adjust size if xfrm output mark is present
874 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
875 {&encap, 0}, // adjust size if encapsulating
876 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
Nathan Harold1a371532017-01-30 12:30:48 -0800877 };
878
Benedict Wongbe65b432017-08-22 21:43:14 -0700879 if (!record.aead.name.empty() && (!record.auth.name.empty() || !record.crypt.name.empty())) {
880 return netdutils::statusFromErrno(EINVAL, "Invalid xfrm algo selection; AEAD is mutually "
881 "exclusive with both Authentication and "
882 "Encryption");
883 }
884
Benedict Wong4f60ee12017-10-10 12:27:25 -0700885 if (record.aead.key.size() > MAX_KEY_LENGTH || record.auth.key.size() > MAX_KEY_LENGTH ||
886 record.crypt.key.size() > MAX_KEY_LENGTH) {
887 return netdutils::statusFromErrno(EINVAL, "Key length invalid; exceeds MAX_KEY_LENGTH");
Benedict Wongbe65b432017-08-22 21:43:14 -0700888 }
889
Nathan Harold1a371532017-01-30 12:30:48 -0800890 int len;
891 len = iov[USERSA].iov_len = fillUserSaInfo(record, &usersa);
892 iov[USERSA_PAD].iov_len = NLMSG_ALIGN(len) - len;
893
894 len = iov[CRYPT].iov_len = fillNlAttrXfrmAlgoEnc(record.crypt, &crypt);
895 iov[CRYPT_PAD].iov_len = NLA_ALIGN(len) - len;
896
897 len = iov[AUTH].iov_len = fillNlAttrXfrmAlgoAuth(record.auth, &auth);
898 iov[AUTH_PAD].iov_len = NLA_ALIGN(len) - len;
899
Benedict Wongbe65b432017-08-22 21:43:14 -0700900 len = iov[AEAD].iov_len = fillNlAttrXfrmAlgoAead(record.aead, &aead);
901 iov[AEAD_PAD].iov_len = NLA_ALIGN(len) - len;
902
Di Lu2ccb3e52018-01-03 16:19:20 -0800903 len = iov[MARK].iov_len = fillNlAttrXfrmMark(record, &xfrmmark);
904 iov[MARK_PAD].iov_len = NLA_ALIGN(len) - len;
905
Benedict Wong96abf482018-01-22 13:56:41 -0800906 len = iov[OUTPUT_MARK].iov_len = fillNlAttrXfrmOutputMark(record.netId, &xfrmoutputmark);
907 iov[OUTPUT_MARK_PAD].iov_len = NLA_ALIGN(len) - len;
908
Nathan Harold420ceac2017-04-05 19:36:59 -0700909 len = iov[ENCAP].iov_len = fillNlAttrXfrmEncapTmpl(record, &encap);
910 iov[ENCAP_PAD].iov_len = NLA_ALIGN(len) - len;
Di Lu2ccb3e52018-01-03 16:19:20 -0800911
ludie51e3862017-08-15 19:28:12 -0700912 return sock.sendMessage(XFRM_MSG_UPDSA, NETLINK_REQUEST_FLAGS, 0, &iov);
Nathan Harold1a371532017-01-30 12:30:48 -0800913}
914
915int XfrmController::fillNlAttrXfrmAlgoEnc(const XfrmAlgo& inAlgo, nlattr_algo_crypt* algo) {
Benedict Wongbe65b432017-08-22 21:43:14 -0700916 if (inAlgo.name.empty()) { // Do not fill anything if algorithm not provided
917 return 0;
918 }
919
Nathan Harold1a371532017-01-30 12:30:48 -0800920 int len = NLA_HDRLEN + sizeof(xfrm_algo);
Benedict Wongbe65b432017-08-22 21:43:14 -0700921 // Kernel always changes last char to null terminator; no safety checks needed.
Nathan Harold1a371532017-01-30 12:30:48 -0800922 strncpy(algo->crypt.alg_name, inAlgo.name.c_str(), sizeof(algo->crypt.alg_name));
Nathan Harold7441c692017-12-12 21:25:01 -0800923 algo->crypt.alg_key_len = inAlgo.key.size() * 8; // bits
Benedict Wongbe65b432017-08-22 21:43:14 -0700924 memcpy(algo->key, &inAlgo.key[0], inAlgo.key.size());
Nathan Harold1a371532017-01-30 12:30:48 -0800925 len += inAlgo.key.size();
926 fillXfrmNlaHdr(&algo->hdr, XFRMA_ALG_CRYPT, len);
927 return len;
928}
929
930int XfrmController::fillNlAttrXfrmAlgoAuth(const XfrmAlgo& inAlgo, nlattr_algo_auth* algo) {
Benedict Wongbe65b432017-08-22 21:43:14 -0700931 if (inAlgo.name.empty()) { // Do not fill anything if algorithm not provided
932 return 0;
933 }
934
Nathan Harold1a371532017-01-30 12:30:48 -0800935 int len = NLA_HDRLEN + sizeof(xfrm_algo_auth);
Benedict Wongbe65b432017-08-22 21:43:14 -0700936 // Kernel always changes last char to null terminator; no safety checks needed.
Nathan Harold1a371532017-01-30 12:30:48 -0800937 strncpy(algo->auth.alg_name, inAlgo.name.c_str(), sizeof(algo->auth.alg_name));
938 algo->auth.alg_key_len = inAlgo.key.size() * 8; // bits
939
940 // This is the extra field for ALG_AUTH_TRUNC
941 algo->auth.alg_trunc_len = inAlgo.truncLenBits;
942
Benedict Wongbe65b432017-08-22 21:43:14 -0700943 memcpy(algo->key, &inAlgo.key[0], inAlgo.key.size());
Nathan Harold1a371532017-01-30 12:30:48 -0800944 len += inAlgo.key.size();
945
946 fillXfrmNlaHdr(&algo->hdr, XFRMA_ALG_AUTH_TRUNC, len);
947 return len;
948}
949
Benedict Wongbe65b432017-08-22 21:43:14 -0700950int XfrmController::fillNlAttrXfrmAlgoAead(const XfrmAlgo& inAlgo, nlattr_algo_aead* algo) {
951 if (inAlgo.name.empty()) { // Do not fill anything if algorithm not provided
952 return 0;
953 }
954
955 int len = NLA_HDRLEN + sizeof(xfrm_algo_aead);
956 // Kernel always changes last char to null terminator; no safety checks needed.
957 strncpy(algo->aead.alg_name, inAlgo.name.c_str(), sizeof(algo->aead.alg_name));
958 algo->aead.alg_key_len = inAlgo.key.size() * 8; // bits
959
960 // This is the extra field for ALG_AEAD. ICV length is the same as truncation length
961 // for any AEAD algorithm.
962 algo->aead.alg_icv_len = inAlgo.truncLenBits;
963
964 memcpy(algo->key, &inAlgo.key[0], inAlgo.key.size());
965 len += inAlgo.key.size();
966
967 fillXfrmNlaHdr(&algo->hdr, XFRMA_ALG_AEAD, len);
968 return len;
969}
970
Nathan Harold420ceac2017-04-05 19:36:59 -0700971int XfrmController::fillNlAttrXfrmEncapTmpl(const XfrmSaInfo& record, nlattr_encap_tmpl* tmpl) {
972 if (record.encap.type == XfrmEncapType::NONE) {
973 return 0;
974 }
975
976 int len = NLA_HDRLEN + sizeof(xfrm_encap_tmpl);
977 tmpl->tmpl.encap_type = static_cast<uint16_t>(record.encap.type);
978 tmpl->tmpl.encap_sport = htons(record.encap.srcPort);
979 tmpl->tmpl.encap_dport = htons(record.encap.dstPort);
980 fillXfrmNlaHdr(&tmpl->hdr, XFRMA_ENCAP, len);
981 return len;
982}
983
Nathan Harold1a371532017-01-30 12:30:48 -0800984int XfrmController::fillUserSaInfo(const XfrmSaInfo& record, xfrm_usersa_info* usersa) {
Benedict Wonga04ffa72018-05-09 21:42:42 -0700985 // Use AF_UNSPEC for all SAs. In transport mode, kernel picks selector family based on
986 // usersa->family, while in tunnel mode, the XFRM_STATE_AF_UNSPEC flag allows dual-stack SAs.
987 fillXfrmSelector(AF_UNSPEC, &usersa->sel);
Nathan Harold1a371532017-01-30 12:30:48 -0800988
989 usersa->id.proto = IPPROTO_ESP;
990 usersa->id.spi = record.spi;
991 usersa->id.daddr = record.dstAddr;
992
993 usersa->saddr = record.srcAddr;
994
995 fillXfrmLifetimeDefaults(&usersa->lft);
996 fillXfrmCurLifetimeDefaults(&usersa->curlft);
997 memset(&usersa->stats, 0, sizeof(usersa->stats)); // leave stats zeroed out
998 usersa->reqid = record.transformId;
999 usersa->family = record.addrFamily;
1000 usersa->mode = static_cast<uint8_t>(record.mode);
1001 usersa->replay_window = REPLAY_WINDOW_SIZE;
manojboopathi4d2d6f12017-12-06 11:11:31 -08001002
1003 if (record.mode == XfrmMode::TRANSPORT) {
1004 usersa->flags = 0; // TODO: should we actually set flags, XFRM_SA_XFLAG_DONT_ENCAP_DSCP?
1005 } else {
1006 usersa->flags = XFRM_STATE_AF_UNSPEC;
1007 }
1008
Nathan Harold1a371532017-01-30 12:30:48 -08001009 return sizeof(*usersa);
1010}
1011
Benedict Wonga04ffa72018-05-09 21:42:42 -07001012int XfrmController::fillUserSaId(const XfrmCommonInfo& record, xfrm_usersa_id* said) {
Nathan Harold1a371532017-01-30 12:30:48 -08001013 said->daddr = record.dstAddr;
1014 said->spi = record.spi;
1015 said->family = record.addrFamily;
1016 said->proto = IPPROTO_ESP;
1017
1018 return sizeof(*said);
1019}
1020
Benedict Wonga04ffa72018-05-09 21:42:42 -07001021netdutils::Status XfrmController::deleteSecurityAssociation(const XfrmCommonInfo& record,
ludi6e8eccd2017-08-14 14:40:37 -07001022 const XfrmSocket& sock) {
Nathan Harold1a371532017-01-30 12:30:48 -08001023 xfrm_usersa_id said{};
Di Lu2ccb3e52018-01-03 16:19:20 -08001024 nlattr_xfrm_mark xfrmmark{};
Nathan Harold1a371532017-01-30 12:30:48 -08001025
Di Lu2ccb3e52018-01-03 16:19:20 -08001026 enum { NLMSG_HDR, USERSAID, USERSAID_PAD, MARK, MARK_PAD };
Nathan Harold1a371532017-01-30 12:30:48 -08001027
ludie51e3862017-08-15 19:28:12 -07001028 std::vector<iovec> iov = {
Yi Kongbdfd57e2018-07-25 13:26:10 -07001029 {nullptr, 0}, // reserved for the eventual addition of a NLMSG_HDR
Nathan Harold1a371532017-01-30 12:30:48 -08001030 {&said, 0}, // main usersa_info struct
1031 {kPadBytes, 0}, // up to NLMSG_ALIGNTO pad bytes of padding
manojboopathi8707f232018-01-02 14:45:47 -08001032 {&xfrmmark, 0}, // adjust size if xfrm mark is present
1033 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
Nathan Harold1a371532017-01-30 12:30:48 -08001034 };
1035
1036 int len;
1037 len = iov[USERSAID].iov_len = fillUserSaId(record, &said);
1038 iov[USERSAID_PAD].iov_len = NLMSG_ALIGN(len) - len;
1039
Di Lu2ccb3e52018-01-03 16:19:20 -08001040 len = iov[MARK].iov_len = fillNlAttrXfrmMark(record, &xfrmmark);
1041 iov[MARK_PAD].iov_len = NLA_ALIGN(len) - len;
1042
ludie51e3862017-08-15 19:28:12 -07001043 return sock.sendMessage(XFRM_MSG_DELSA, NETLINK_REQUEST_FLAGS, 0, &iov);
Nathan Harold1a371532017-01-30 12:30:48 -08001044}
1045
ludi6e8eccd2017-08-14 14:40:37 -07001046netdutils::Status XfrmController::allocateSpi(const XfrmSaInfo& record, uint32_t minSpi,
1047 uint32_t maxSpi, uint32_t* outSpi,
1048 const XfrmSocket& sock) {
Nathan Harold1a371532017-01-30 12:30:48 -08001049 xfrm_userspi_info spiInfo{};
1050
ludie51e3862017-08-15 19:28:12 -07001051 enum { NLMSG_HDR, USERSAID, USERSAID_PAD };
Nathan Harold1a371532017-01-30 12:30:48 -08001052
ludie51e3862017-08-15 19:28:12 -07001053 std::vector<iovec> iov = {
Yi Kongbdfd57e2018-07-25 13:26:10 -07001054 {nullptr, 0}, // reserved for the eventual addition of a NLMSG_HDR
Nathan Harold1a371532017-01-30 12:30:48 -08001055 {&spiInfo, 0}, // main userspi_info struct
1056 {kPadBytes, 0}, // up to NLMSG_ALIGNTO pad bytes of padding
1057 };
1058
1059 int len;
1060 if (fillUserSaInfo(record, &spiInfo.info) == 0) {
1061 ALOGE("Failed to fill transport SA Info");
1062 }
1063
1064 len = iov[USERSAID].iov_len = sizeof(spiInfo);
1065 iov[USERSAID_PAD].iov_len = NLMSG_ALIGN(len) - len;
1066
1067 RandomSpi spiGen = RandomSpi(minSpi, maxSpi);
ludi6e8eccd2017-08-14 14:40:37 -07001068 int spi;
1069 netdutils::Status ret;
Nathan Harold1a371532017-01-30 12:30:48 -08001070 while ((spi = spiGen.next()) != INVALID_SPI) {
1071 spiInfo.min = spi;
1072 spiInfo.max = spi;
ludie51e3862017-08-15 19:28:12 -07001073 ret = sock.sendMessage(XFRM_MSG_ALLOCSPI, NETLINK_REQUEST_FLAGS, 0, &iov);
Nathan Harold1a371532017-01-30 12:30:48 -08001074
1075 /* If the SPI is in use, we'll get ENOENT */
ludi6e8eccd2017-08-14 14:40:37 -07001076 if (netdutils::equalToErrno(ret, ENOENT))
Nathan Harold1a371532017-01-30 12:30:48 -08001077 continue;
1078
ludi6e8eccd2017-08-14 14:40:37 -07001079 if (isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -08001080 *outSpi = spi;
Nathan Harold420ceac2017-04-05 19:36:59 -07001081 ALOGD("Allocated an SPI: %x", *outSpi);
Nathan Harold1a371532017-01-30 12:30:48 -08001082 } else {
1083 *outSpi = INVALID_SPI;
ludi6e8eccd2017-08-14 14:40:37 -07001084 ALOGE("SPI Allocation Failed with error %d", ret.code());
Nathan Harold1a371532017-01-30 12:30:48 -08001085 }
1086
1087 return ret;
1088 }
1089
1090 // Should always be -ENOENT if we get here
1091 return ret;
1092}
1093
Benedict Wonga04ffa72018-05-09 21:42:42 -07001094netdutils::Status XfrmController::updateTunnelModeSecurityPolicy(const XfrmSpInfo& record,
ludi771b8002017-11-20 15:09:05 -08001095 const XfrmSocket& sock,
1096 XfrmDirection direction,
1097 uint16_t msgType) {
1098 xfrm_userpolicy_info userpolicy{};
1099 nlattr_user_tmpl usertmpl{};
Di Lu2ccb3e52018-01-03 16:19:20 -08001100 nlattr_xfrm_mark xfrmmark{};
ludi771b8002017-11-20 15:09:05 -08001101
1102 enum {
1103 NLMSG_HDR,
1104 USERPOLICY,
1105 USERPOLICY_PAD,
1106 USERTMPL,
1107 USERTMPL_PAD,
Di Lu2ccb3e52018-01-03 16:19:20 -08001108 MARK,
1109 MARK_PAD,
ludi771b8002017-11-20 15:09:05 -08001110 };
1111
1112 std::vector<iovec> iov = {
Yi Kongbdfd57e2018-07-25 13:26:10 -07001113 {nullptr, 0}, // reserved for the eventual addition of a NLMSG_HDR
ludi771b8002017-11-20 15:09:05 -08001114 {&userpolicy, 0}, // main xfrm_userpolicy_info struct
1115 {kPadBytes, 0}, // up to NLMSG_ALIGNTO pad bytes of padding
1116 {&usertmpl, 0}, // adjust size if xfrm_user_tmpl struct is present
1117 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
Di Lu2ccb3e52018-01-03 16:19:20 -08001118 {&xfrmmark, 0}, // adjust size if xfrm mark is present
1119 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
ludi771b8002017-11-20 15:09:05 -08001120 };
1121
1122 int len;
Benedict Wonga04ffa72018-05-09 21:42:42 -07001123 len = iov[USERPOLICY].iov_len = fillUserSpInfo(record, direction, &userpolicy);
ludi771b8002017-11-20 15:09:05 -08001124 iov[USERPOLICY_PAD].iov_len = NLMSG_ALIGN(len) - len;
1125
1126 len = iov[USERTMPL].iov_len = fillNlAttrUserTemplate(record, &usertmpl);
1127 iov[USERTMPL_PAD].iov_len = NLA_ALIGN(len) - len;
1128
Di Lu2ccb3e52018-01-03 16:19:20 -08001129 len = iov[MARK].iov_len = fillNlAttrXfrmMark(record, &xfrmmark);
1130 iov[MARK_PAD].iov_len = NLA_ALIGN(len) - len;
1131
ludi771b8002017-11-20 15:09:05 -08001132 return sock.sendMessage(msgType, NETLINK_REQUEST_FLAGS, 0, &iov);
1133}
1134
Benedict Wonga04ffa72018-05-09 21:42:42 -07001135netdutils::Status XfrmController::deleteTunnelModeSecurityPolicy(const XfrmSpInfo& record,
ludi771b8002017-11-20 15:09:05 -08001136 const XfrmSocket& sock,
1137 XfrmDirection direction) {
1138 xfrm_userpolicy_id policyid{};
Di Lu2ccb3e52018-01-03 16:19:20 -08001139 nlattr_xfrm_mark xfrmmark{};
ludi771b8002017-11-20 15:09:05 -08001140
1141 enum {
1142 NLMSG_HDR,
1143 USERPOLICYID,
1144 USERPOLICYID_PAD,
Di Lu2ccb3e52018-01-03 16:19:20 -08001145 MARK,
1146 MARK_PAD,
ludi771b8002017-11-20 15:09:05 -08001147 };
1148
1149 std::vector<iovec> iov = {
Yi Kongbdfd57e2018-07-25 13:26:10 -07001150 {nullptr, 0}, // reserved for the eventual addition of a NLMSG_HDR
ludi771b8002017-11-20 15:09:05 -08001151 {&policyid, 0}, // main xfrm_userpolicy_id struct
1152 {kPadBytes, 0}, // up to NLMSG_ALIGNTO pad bytes of padding
manojboopathi8707f232018-01-02 14:45:47 -08001153 {&xfrmmark, 0}, // adjust size if xfrm mark is present
1154 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
ludi771b8002017-11-20 15:09:05 -08001155 };
1156
1157 int len = iov[USERPOLICYID].iov_len = fillUserPolicyId(record, direction, &policyid);
1158 iov[USERPOLICYID_PAD].iov_len = NLMSG_ALIGN(len) - len;
1159
Di Lu2ccb3e52018-01-03 16:19:20 -08001160 len = iov[MARK].iov_len = fillNlAttrXfrmMark(record, &xfrmmark);
1161 iov[MARK_PAD].iov_len = NLA_ALIGN(len) - len;
1162
ludi771b8002017-11-20 15:09:05 -08001163 return sock.sendMessage(XFRM_MSG_DELPOLICY, NETLINK_REQUEST_FLAGS, 0, &iov);
1164}
1165
Benedict Wonga04ffa72018-05-09 21:42:42 -07001166int XfrmController::fillUserSpInfo(const XfrmSpInfo& record, XfrmDirection direction,
1167 xfrm_userpolicy_info* usersp) {
1168 fillXfrmSelector(record.selAddrFamily, &usersp->sel);
Nathan Harold1a371532017-01-30 12:30:48 -08001169 fillXfrmLifetimeDefaults(&usersp->lft);
1170 fillXfrmCurLifetimeDefaults(&usersp->curlft);
Nathan Harold420ceac2017-04-05 19:36:59 -07001171 /* if (index) index & 0x3 == dir -- must be true
1172 * xfrm_user.c:verify_newpolicy_info() */
Nathan Harold1a371532017-01-30 12:30:48 -08001173 usersp->index = 0;
Nathan Haroldda54f122018-01-09 16:42:57 -08001174 usersp->dir = static_cast<uint8_t>(direction);
Nathan Harold1a371532017-01-30 12:30:48 -08001175 usersp->action = XFRM_POLICY_ALLOW;
1176 usersp->flags = XFRM_POLICY_LOCALOK;
1177 usersp->share = XFRM_SHARE_UNIQUE;
1178 return sizeof(*usersp);
1179}
1180
Benedict Wonga04ffa72018-05-09 21:42:42 -07001181int XfrmController::fillUserTemplate(const XfrmSpInfo& record, xfrm_user_tmpl* tmpl) {
Nathan Harold1a371532017-01-30 12:30:48 -08001182 tmpl->id.daddr = record.dstAddr;
1183 tmpl->id.spi = record.spi;
1184 tmpl->id.proto = IPPROTO_ESP;
1185
1186 tmpl->family = record.addrFamily;
1187 tmpl->saddr = record.srcAddr;
1188 tmpl->reqid = record.transformId;
1189 tmpl->mode = static_cast<uint8_t>(record.mode);
1190 tmpl->share = XFRM_SHARE_UNIQUE;
1191 tmpl->optional = 0; // if this is true, then a failed state lookup will be considered OK:
1192 // http://lxr.free-electrons.com/source/net/xfrm/xfrm_policy.c#L1492
1193 tmpl->aalgos = ALGO_MASK_AUTH_ALL; // TODO: if there's a bitmask somewhere of
1194 // algos, we should find it and apply it.
1195 // I can't find one.
1196 tmpl->ealgos = ALGO_MASK_CRYPT_ALL; // TODO: if there's a bitmask somewhere...
ludi771b8002017-11-20 15:09:05 -08001197 return sizeof(xfrm_user_tmpl*);
Nathan Harold1a371532017-01-30 12:30:48 -08001198}
1199
Benedict Wonga04ffa72018-05-09 21:42:42 -07001200int XfrmController::fillNlAttrUserTemplate(const XfrmSpInfo& record, nlattr_user_tmpl* tmpl) {
ludi771b8002017-11-20 15:09:05 -08001201 fillUserTemplate(record, &tmpl->tmpl);
1202
1203 int len = NLA_HDRLEN + sizeof(xfrm_user_tmpl);
1204 fillXfrmNlaHdr(&tmpl->hdr, XFRMA_TMPL, len);
1205 return len;
1206}
1207
Benedict Wonga04ffa72018-05-09 21:42:42 -07001208int XfrmController::fillNlAttrXfrmMark(const XfrmCommonInfo& record, nlattr_xfrm_mark* mark) {
Di Lu2ccb3e52018-01-03 16:19:20 -08001209 mark->mark.v = record.mark.v; // set to 0 if it's not used
1210 mark->mark.m = record.mark.m; // set to 0 if it's not used
1211 int len = NLA_HDRLEN + sizeof(xfrm_mark);
1212 fillXfrmNlaHdr(&mark->hdr, XFRMA_MARK, len);
1213 return len;
1214}
1215
manojboopathi8707f232018-01-02 14:45:47 -08001216int XfrmController::fillNlAttrXfrmOutputMark(const __u32 output_mark_value,
1217 nlattr_xfrm_output_mark* output_mark) {
Benedict Wong96abf482018-01-22 13:56:41 -08001218 // Do not set if we were not given an output mark
1219 if (output_mark_value == 0) {
1220 return 0;
1221 }
1222
1223 output_mark->outputMark = output_mark_value;
1224 int len = NLA_HDRLEN + sizeof(__u32);
1225 fillXfrmNlaHdr(&output_mark->hdr, XFRMA_OUTPUT_MARK, len);
1226 return len;
1227}
1228
Benedict Wonga04ffa72018-05-09 21:42:42 -07001229int XfrmController::fillUserPolicyId(const XfrmSpInfo& record, XfrmDirection direction,
ludi771b8002017-11-20 15:09:05 -08001230 xfrm_userpolicy_id* usersp) {
1231 // For DELPOLICY, when index is absent, selector is needed to match the policy
Benedict Wonga04ffa72018-05-09 21:42:42 -07001232 fillXfrmSelector(record.selAddrFamily, &usersp->sel);
ludi771b8002017-11-20 15:09:05 -08001233 usersp->dir = static_cast<uint8_t>(direction);
1234 return sizeof(*usersp);
1235}
1236
manojboopathi8707f232018-01-02 14:45:47 -08001237int XfrmController::addVirtualTunnelInterface(const std::string& deviceName,
1238 const std::string& localAddress,
1239 const std::string& remoteAddress, int32_t ikey,
1240 int32_t okey, bool isUpdate) {
1241 ALOGD("XfrmController::%s, line=%d", __FUNCTION__, __LINE__);
1242 ALOGD("deviceName=%s", deviceName.c_str());
1243 ALOGD("localAddress=%s", localAddress.c_str());
1244 ALOGD("remoteAddress=%s", remoteAddress.c_str());
1245 ALOGD("ikey=%0.8x", ikey);
1246 ALOGD("okey=%0.8x", okey);
1247 ALOGD("isUpdate=%d", isUpdate);
1248
1249 if (deviceName.empty() || localAddress.empty() || remoteAddress.empty()) {
1250 return EINVAL;
1251 }
1252
1253 const char* INFO_KIND_VTI6 = "vti6";
1254 const char* INFO_KIND_VTI = "vti";
1255 uint8_t PADDING_BUFFER[] = {0, 0, 0, 0};
1256
1257 // Find address family.
1258 uint8_t remAddr[sizeof(in6_addr)];
1259
1260 StatusOr<uint16_t> statusOrRemoteFam = convertStringAddress(remoteAddress, remAddr);
1261 if (!isOk(statusOrRemoteFam)) {
1262 return statusOrRemoteFam.status().code();
1263 }
1264
1265 uint8_t locAddr[sizeof(in6_addr)];
1266 StatusOr<uint16_t> statusOrLocalFam = convertStringAddress(localAddress, locAddr);
1267 if (!isOk(statusOrLocalFam)) {
1268 return statusOrLocalFam.status().code();
1269 }
1270
1271 if (statusOrLocalFam.value() != statusOrRemoteFam.value()) {
1272 return EINVAL;
1273 }
1274
1275 uint16_t family = statusOrLocalFam.value();
1276
1277 ifinfomsg ifInfoMsg{};
1278
1279 // Construct IFLA_IFNAME
1280 nlattr iflaIfName;
1281 char iflaIfNameStrValue[deviceName.length() + 1];
1282 size_t iflaIfNameLength =
1283 strlcpy(iflaIfNameStrValue, deviceName.c_str(), sizeof(iflaIfNameStrValue));
1284 size_t iflaIfNamePad = fillNlAttr(IFLA_IFNAME, iflaIfNameLength, &iflaIfName);
1285
1286 // Construct IFLA_INFO_KIND
1287 // Constants "vti6" and "vti" enable the kernel to call different code paths,
1288 // (ip_tunnel.c, ip6_tunnel), based on the family.
1289 const std::string infoKindValue = (family == AF_INET6) ? INFO_KIND_VTI6 : INFO_KIND_VTI;
1290 nlattr iflaIfInfoKind;
1291 char infoKindValueStrValue[infoKindValue.length() + 1];
1292 size_t iflaIfInfoKindLength =
1293 strlcpy(infoKindValueStrValue, infoKindValue.c_str(), sizeof(infoKindValueStrValue));
1294 size_t iflaIfInfoKindPad = fillNlAttr(IFLA_INFO_KIND, iflaIfInfoKindLength, &iflaIfInfoKind);
1295
1296 // Construct IFLA_VTI_LOCAL
1297 nlattr iflaVtiLocal;
1298 uint8_t binaryLocalAddress[sizeof(in6_addr)];
1299 size_t iflaVtiLocalPad =
1300 fillNlAttrIpAddress(IFLA_VTI_LOCAL, family, localAddress, &iflaVtiLocal,
1301 netdutils::makeSlice(binaryLocalAddress));
1302
1303 // Construct IFLA_VTI_REMOTE
1304 nlattr iflaVtiRemote;
1305 uint8_t binaryRemoteAddress[sizeof(in6_addr)];
1306 size_t iflaVtiRemotePad =
1307 fillNlAttrIpAddress(IFLA_VTI_REMOTE, family, remoteAddress, &iflaVtiRemote,
1308 netdutils::makeSlice(binaryRemoteAddress));
1309
1310 // Construct IFLA_VTI_OKEY
1311 nlattr iflaVtiIKey;
1312 uint32_t iKeyValue;
1313 size_t iflaVtiIKeyPad = fillNlAttrU32(IFLA_VTI_IKEY, ikey, &iflaVtiIKey, &iKeyValue);
1314
1315 // Construct IFLA_VTI_IKEY
1316 nlattr iflaVtiOKey;
1317 uint32_t oKeyValue;
1318 size_t iflaVtiOKeyPad = fillNlAttrU32(IFLA_VTI_OKEY, okey, &iflaVtiOKey, &oKeyValue);
1319
1320 int iflaInfoDataPayloadLength = iflaVtiLocal.nla_len + iflaVtiLocalPad + iflaVtiRemote.nla_len +
1321 iflaVtiRemotePad + iflaVtiIKey.nla_len + iflaVtiIKeyPad +
1322 iflaVtiOKey.nla_len + iflaVtiOKeyPad;
1323
1324 // Construct IFLA_INFO_DATA
1325 nlattr iflaInfoData;
1326 size_t iflaInfoDataPad = fillNlAttr(IFLA_INFO_DATA, iflaInfoDataPayloadLength, &iflaInfoData);
1327
1328 // Construct IFLA_LINKINFO
1329 nlattr iflaLinkInfo;
1330 size_t iflaLinkInfoPad = fillNlAttr(IFLA_LINKINFO,
1331 iflaInfoData.nla_len + iflaInfoDataPad +
1332 iflaIfInfoKind.nla_len + iflaIfInfoKindPad,
1333 &iflaLinkInfo);
1334
1335 iovec iov[] = {
Yi Kongbdfd57e2018-07-25 13:26:10 -07001336 {nullptr, 0},
manojboopathi8707f232018-01-02 14:45:47 -08001337 {&ifInfoMsg, sizeof(ifInfoMsg)},
1338
1339 {&iflaIfName, sizeof(iflaIfName)},
1340 {iflaIfNameStrValue, iflaIfNameLength},
1341 {&PADDING_BUFFER, iflaIfNamePad},
1342
1343 {&iflaLinkInfo, sizeof(iflaLinkInfo)},
1344
1345 {&iflaIfInfoKind, sizeof(iflaIfInfoKind)},
1346 {infoKindValueStrValue, iflaIfInfoKindLength},
1347 {&PADDING_BUFFER, iflaIfInfoKindPad},
1348
1349 {&iflaInfoData, sizeof(iflaInfoData)},
1350
1351 {&iflaVtiLocal, sizeof(iflaVtiLocal)},
1352 {&binaryLocalAddress, (family == AF_INET) ? sizeof(in_addr) : sizeof(in6_addr)},
1353 {&PADDING_BUFFER, iflaVtiLocalPad},
1354
1355 {&iflaVtiRemote, sizeof(iflaVtiRemote)},
1356 {&binaryRemoteAddress, (family == AF_INET) ? sizeof(in_addr) : sizeof(in6_addr)},
1357 {&PADDING_BUFFER, iflaVtiRemotePad},
1358
1359 {&iflaVtiIKey, sizeof(iflaVtiIKey)},
1360 {&iKeyValue, sizeof(iKeyValue)},
1361 {&PADDING_BUFFER, iflaVtiIKeyPad},
1362
1363 {&iflaVtiOKey, sizeof(iflaVtiOKey)},
1364 {&oKeyValue, sizeof(oKeyValue)},
1365 {&PADDING_BUFFER, iflaVtiOKeyPad},
1366
1367 {&PADDING_BUFFER, iflaInfoDataPad},
1368
1369 {&PADDING_BUFFER, iflaLinkInfoPad},
1370 };
1371
1372 uint16_t action = RTM_NEWLINK;
1373 uint16_t flags = NLM_F_REQUEST | NLM_F_ACK;
1374
1375 if (!isUpdate) {
1376 flags |= NLM_F_EXCL | NLM_F_CREATE;
1377 }
1378
Nathan Harold5be66022018-05-10 14:15:36 -07001379 // sendNetlinkRequest returns -errno
1380 int ret = -1 * sendNetlinkRequest(action, flags, iov, ARRAY_SIZE(iov), nullptr);
manojboopathi8707f232018-01-02 14:45:47 -08001381 if (ret) {
1382 ALOGE("Error in %s virtual tunnel interface. Error Code: %d",
1383 isUpdate ? "updating" : "adding", ret);
1384 }
1385 return ret;
1386}
1387
1388int XfrmController::removeVirtualTunnelInterface(const std::string& deviceName) {
1389 ALOGD("XfrmController::%s, line=%d", __FUNCTION__, __LINE__);
1390 ALOGD("deviceName=%s", deviceName.c_str());
1391
1392 if (deviceName.empty()) {
1393 return EINVAL;
1394 }
1395
1396 uint8_t PADDING_BUFFER[] = {0, 0, 0, 0};
1397
1398 ifinfomsg ifInfoMsg{};
1399 nlattr iflaIfName;
1400 char iflaIfNameStrValue[deviceName.length() + 1];
1401 size_t iflaIfNameLength =
1402 strlcpy(iflaIfNameStrValue, deviceName.c_str(), sizeof(iflaIfNameStrValue));
1403 size_t iflaIfNamePad = fillNlAttr(IFLA_IFNAME, iflaIfNameLength, &iflaIfName);
1404
1405 iovec iov[] = {
Yi Kongbdfd57e2018-07-25 13:26:10 -07001406 {nullptr, 0},
manojboopathi8707f232018-01-02 14:45:47 -08001407 {&ifInfoMsg, sizeof(ifInfoMsg)},
1408
1409 {&iflaIfName, sizeof(iflaIfName)},
1410 {iflaIfNameStrValue, iflaIfNameLength},
1411 {&PADDING_BUFFER, iflaIfNamePad},
1412 };
1413
1414 uint16_t action = RTM_DELLINK;
1415 uint16_t flags = NLM_F_REQUEST | NLM_F_ACK;
1416
Nathan Harold5be66022018-05-10 14:15:36 -07001417 // sendNetlinkRequest returns -errno
1418 int ret = -1 * sendNetlinkRequest(action, flags, iov, ARRAY_SIZE(iov), nullptr);
manojboopathi8707f232018-01-02 14:45:47 -08001419 if (ret) {
1420 ALOGE("Error in removing virtual tunnel interface %s. Error Code: %d", iflaIfNameStrValue,
1421 ret);
1422 }
1423 return ret;
1424}
ludi771b8002017-11-20 15:09:05 -08001425
Nathan Harold1a371532017-01-30 12:30:48 -08001426} // namespace net
1427} // namespace android