blob: c27342e043d37ef3df73183dc1c5551a9571b0b8 [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 Harolda0345e12018-06-05 11:41:41 -070047#include <android-base/properties.h>
48#include <android-base/stringprintf.h>
49#include <android-base/strings.h>
50#include <android-base/unique_fd.h>
51#include <android/net/INetd.h>
Nathan Harold1a371532017-01-30 12:30:48 -080052#include <cutils/properties.h>
Logan Chien3f461482018-04-23 14:31:32 +080053#include <log/log.h>
Nathan Harolda0345e12018-06-05 11:41:41 -070054#include <log/log_properties.h>
Nathan Harold1a371532017-01-30 12:30:48 -080055#include <logwrap/logwrap.h>
Benedict Wongd8b6a382018-09-18 17:16:10 -070056#include "Fwmark.h"
57#include "InterfaceController.h"
58#include "NetdConstants.h"
59#include "NetlinkCommands.h"
60#include "Permission.h"
61#include "ResponseCode.h"
62#include "XfrmController.h"
63#include "netdutils/Fd.h"
64#include "netdutils/Slice.h"
65#include "netdutils/Syscalls.h"
Nathan Harold1a371532017-01-30 12:30:48 -080066
Nathan Harold45c35662018-04-23 10:10:18 -070067using android::net::INetd;
ludi4072ff22017-06-15 08:56:52 -070068using android::netdutils::Fd;
69using android::netdutils::Slice;
70using android::netdutils::Status;
71using android::netdutils::StatusOr;
72using android::netdutils::Syscalls;
73
Nathan Harold1a371532017-01-30 12:30:48 -080074namespace android {
75namespace net {
76
Nathan Harold39b5df42017-08-02 18:45:25 -070077// Exposed for testing
Nathan Harold1a371532017-01-30 12:30:48 -080078constexpr uint32_t ALGO_MASK_AUTH_ALL = ~0;
Nathan Harold39b5df42017-08-02 18:45:25 -070079// Exposed for testing
Nathan Harold1a371532017-01-30 12:30:48 -080080constexpr uint32_t ALGO_MASK_CRYPT_ALL = ~0;
Nathan Harold39b5df42017-08-02 18:45:25 -070081// Exposed for testing
Benedict Wongbe65b432017-08-22 21:43:14 -070082constexpr uint32_t ALGO_MASK_AEAD_ALL = ~0;
83// Exposed for testing
Nathan Harold1a371532017-01-30 12:30:48 -080084constexpr uint8_t REPLAY_WINDOW_SIZE = 4;
85
Nathan Harold39b5df42017-08-02 18:45:25 -070086namespace {
87
Nathan Harold1012ffe2018-03-28 08:59:24 -070088constexpr uint32_t RAND_SPI_MIN = 256;
Nathan Harold1a371532017-01-30 12:30:48 -080089constexpr uint32_t RAND_SPI_MAX = 0xFFFFFFFE;
90
91constexpr uint32_t INVALID_SPI = 0;
92
Nathan Harolda0345e12018-06-05 11:41:41 -070093static inline bool isEngBuild() {
94 static const std::string sBuildType = android::base::GetProperty("ro.build.type", "user");
95 return sBuildType == "eng";
96}
97
Nathan Harold1a371532017-01-30 12:30:48 -080098#define XFRM_MSG_TRANS(x) \
99 case x: \
100 return #x;
101
102const char* xfrmMsgTypeToString(uint16_t msg) {
103 switch (msg) {
104 XFRM_MSG_TRANS(XFRM_MSG_NEWSA)
105 XFRM_MSG_TRANS(XFRM_MSG_DELSA)
106 XFRM_MSG_TRANS(XFRM_MSG_GETSA)
107 XFRM_MSG_TRANS(XFRM_MSG_NEWPOLICY)
108 XFRM_MSG_TRANS(XFRM_MSG_DELPOLICY)
109 XFRM_MSG_TRANS(XFRM_MSG_GETPOLICY)
110 XFRM_MSG_TRANS(XFRM_MSG_ALLOCSPI)
111 XFRM_MSG_TRANS(XFRM_MSG_ACQUIRE)
112 XFRM_MSG_TRANS(XFRM_MSG_EXPIRE)
113 XFRM_MSG_TRANS(XFRM_MSG_UPDPOLICY)
114 XFRM_MSG_TRANS(XFRM_MSG_UPDSA)
115 XFRM_MSG_TRANS(XFRM_MSG_POLEXPIRE)
116 XFRM_MSG_TRANS(XFRM_MSG_FLUSHSA)
117 XFRM_MSG_TRANS(XFRM_MSG_FLUSHPOLICY)
118 XFRM_MSG_TRANS(XFRM_MSG_NEWAE)
119 XFRM_MSG_TRANS(XFRM_MSG_GETAE)
120 XFRM_MSG_TRANS(XFRM_MSG_REPORT)
121 XFRM_MSG_TRANS(XFRM_MSG_MIGRATE)
122 XFRM_MSG_TRANS(XFRM_MSG_NEWSADINFO)
123 XFRM_MSG_TRANS(XFRM_MSG_GETSADINFO)
124 XFRM_MSG_TRANS(XFRM_MSG_GETSPDINFO)
125 XFRM_MSG_TRANS(XFRM_MSG_NEWSPDINFO)
126 XFRM_MSG_TRANS(XFRM_MSG_MAPPING)
127 default:
128 return "XFRM_MSG UNKNOWN";
129 }
130}
131
132// actually const but cannot be declared as such for reasons
133uint8_t kPadBytesArray[] = {0, 0, 0};
134void* kPadBytes = static_cast<void*>(kPadBytesArray);
135
Nathan Harold420ceac2017-04-05 19:36:59 -0700136#define LOG_HEX(__desc16__, __buf__, __len__) \
Nathan Harolda0345e12018-06-05 11:41:41 -0700137 do { \
138 if (isEngBuild()) { \
Manojd9c93c22017-10-19 13:40:26 -0700139 logHex(__desc16__, __buf__, __len__); \
Nathan Harolda0345e12018-06-05 11:41:41 -0700140 } \
141 } while (0)
Manojd9c93c22017-10-19 13:40:26 -0700142
ludie51e3862017-08-15 19:28:12 -0700143#define LOG_IOV(__iov__) \
Nathan Harolda0345e12018-06-05 11:41:41 -0700144 do { \
145 if (isEngBuild()) { \
Manojd9c93c22017-10-19 13:40:26 -0700146 logIov(__iov__); \
Nathan Harolda0345e12018-06-05 11:41:41 -0700147 } \
148 } while (0)
Nathan Harold1a371532017-01-30 12:30:48 -0800149
150void logHex(const char* desc16, const char* buf, size_t len) {
151 char* printBuf = new char[len * 2 + 1 + 26]; // len->ascii, +newline, +prefix strlen
152 int offset = 0;
153 if (desc16) {
154 sprintf(printBuf, "{%-16s}", desc16);
155 offset += 18; // prefix string length
156 }
157 sprintf(printBuf + offset, "[%4.4u]: ", (len > 9999) ? 9999 : (unsigned)len);
158 offset += 8;
159
160 for (uint32_t j = 0; j < (uint32_t)len; j++) {
Wolloh Chou4d1e5c72018-03-22 15:14:33 +0800161 sprintf(&printBuf[j * 2 + offset], "%0.2x", (unsigned char)buf[j]);
Nathan Harold1a371532017-01-30 12:30:48 -0800162 }
163 ALOGD("%s", printBuf);
164 delete[] printBuf;
165}
166
ludie51e3862017-08-15 19:28:12 -0700167void logIov(const std::vector<iovec>& iov) {
168 for (const iovec& row : iov) {
Yi Kongbdfd57e2018-07-25 13:26:10 -0700169 logHex(nullptr, reinterpret_cast<char*>(row.iov_base), row.iov_len);
Nathan Harold1a371532017-01-30 12:30:48 -0800170 }
171}
172
manojboopathi8707f232018-01-02 14:45:47 -0800173size_t fillNlAttr(__u16 nlaType, size_t valueSize, nlattr* nlAttr) {
174 size_t dataLen = valueSize;
175 int padLength = NLMSG_ALIGN(dataLen) - dataLen;
176 nlAttr->nla_len = (__u16)(dataLen + sizeof(nlattr));
177 nlAttr->nla_type = nlaType;
178 return padLength;
179}
180
181size_t fillNlAttrIpAddress(__u16 nlaType, int family, const std::string& value, nlattr* nlAttr,
182 Slice ipAddress) {
183 inet_pton(family, value.c_str(), ipAddress.base());
184 return fillNlAttr(nlaType, (family == AF_INET) ? sizeof(in_addr) : sizeof(in6_addr), nlAttr);
185}
186
187size_t fillNlAttrU32(__u16 nlaType, int32_t value, nlattr* nlAttr, uint32_t* u32Value) {
188 *u32Value = htonl(value);
189 return fillNlAttr(nlaType, sizeof((*u32Value)), nlAttr);
190}
191
192// returns the address family, placing the string in the provided buffer
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900193StatusOr<uint16_t> convertStringAddress(const std::string& addr, uint8_t* buffer) {
manojboopathi8707f232018-01-02 14:45:47 -0800194 if (inet_pton(AF_INET, addr.c_str(), buffer) == 1) {
195 return AF_INET;
196 } else if (inet_pton(AF_INET6, addr.c_str(), buffer) == 1) {
197 return AF_INET6;
198 } else {
199 return Status(EAFNOSUPPORT);
200 }
201}
202
ludi6e8eccd2017-08-14 14:40:37 -0700203// TODO: Need to consider a way to refer to the sSycalls instance
ludi4072ff22017-06-15 08:56:52 -0700204inline Syscalls& getSyscallInstance() { return netdutils::sSyscalls.get(); }
205
Nathan Harold1a371532017-01-30 12:30:48 -0800206class XfrmSocketImpl : public XfrmSocket {
207private:
208 static constexpr int NLMSG_DEFAULTSIZE = 8192;
209
210 union NetlinkResponse {
211 nlmsghdr hdr;
212 struct _err_ {
213 nlmsghdr hdr;
214 nlmsgerr err;
215 } err;
216
217 struct _buf_ {
218 nlmsghdr hdr;
219 char buf[NLMSG_DEFAULTSIZE];
220 } buf;
221 };
222
223public:
ludi6e8eccd2017-08-14 14:40:37 -0700224 netdutils::Status open() override {
Nathan Harold1a371532017-01-30 12:30:48 -0800225 mSock = openNetlinkSocket(NETLINK_XFRM);
ludi6e8eccd2017-08-14 14:40:37 -0700226 if (mSock < 0) {
Nathan Harold1a371532017-01-30 12:30:48 -0800227 ALOGW("Could not get a new socket, line=%d", __LINE__);
ludi6e8eccd2017-08-14 14:40:37 -0700228 return netdutils::statusFromErrno(-mSock, "Could not open netlink socket");
Nathan Harold1a371532017-01-30 12:30:48 -0800229 }
230
ludi6e8eccd2017-08-14 14:40:37 -0700231 return netdutils::status::ok;
Nathan Harold1a371532017-01-30 12:30:48 -0800232 }
233
ludi6e8eccd2017-08-14 14:40:37 -0700234 static netdutils::Status validateResponse(NetlinkResponse response, size_t len) {
Nathan Harold1a371532017-01-30 12:30:48 -0800235 if (len < sizeof(nlmsghdr)) {
236 ALOGW("Invalid response message received over netlink");
ludi6e8eccd2017-08-14 14:40:37 -0700237 return netdutils::statusFromErrno(EBADMSG, "Invalid message");
Nathan Harold1a371532017-01-30 12:30:48 -0800238 }
239
240 switch (response.hdr.nlmsg_type) {
241 case NLMSG_NOOP:
242 case NLMSG_DONE:
ludi6e8eccd2017-08-14 14:40:37 -0700243 return netdutils::status::ok;
Nathan Harold1a371532017-01-30 12:30:48 -0800244 case NLMSG_OVERRUN:
245 ALOGD("Netlink request overran kernel buffer");
ludi6e8eccd2017-08-14 14:40:37 -0700246 return netdutils::statusFromErrno(EBADMSG, "Kernel buffer overrun");
Nathan Harold1a371532017-01-30 12:30:48 -0800247 case NLMSG_ERROR:
248 if (len < sizeof(NetlinkResponse::_err_)) {
249 ALOGD("Netlink message received malformed error response");
ludi6e8eccd2017-08-14 14:40:37 -0700250 return netdutils::statusFromErrno(EBADMSG, "Malformed error response");
Nathan Harold1a371532017-01-30 12:30:48 -0800251 }
ludi6e8eccd2017-08-14 14:40:37 -0700252 return netdutils::statusFromErrno(
253 -response.err.err.error,
254 "Error netlink message"); // Netlink errors are negative errno.
Nathan Harold1a371532017-01-30 12:30:48 -0800255 case XFRM_MSG_NEWSA:
256 break;
257 }
258
259 if (response.hdr.nlmsg_type < XFRM_MSG_BASE /*== NLMSG_MIN_TYPE*/ ||
260 response.hdr.nlmsg_type > XFRM_MSG_MAX) {
261 ALOGD("Netlink message responded with an out-of-range message ID");
ludi6e8eccd2017-08-14 14:40:37 -0700262 return netdutils::statusFromErrno(EBADMSG, "Invalid message ID");
Nathan Harold1a371532017-01-30 12:30:48 -0800263 }
264
265 // TODO Add more message validation here
ludi6e8eccd2017-08-14 14:40:37 -0700266 return netdutils::status::ok;
Nathan Harold1a371532017-01-30 12:30:48 -0800267 }
268
ludi6e8eccd2017-08-14 14:40:37 -0700269 netdutils::Status sendMessage(uint16_t nlMsgType, uint16_t nlMsgFlags, uint16_t nlMsgSeqNum,
270 std::vector<iovec>* iovecs) const override {
Nathan Harold1a371532017-01-30 12:30:48 -0800271 nlmsghdr nlMsg = {
Nathan Harold7441c692017-12-12 21:25:01 -0800272 .nlmsg_type = nlMsgType,
273 .nlmsg_flags = nlMsgFlags,
274 .nlmsg_seq = nlMsgSeqNum,
Nathan Harold1a371532017-01-30 12:30:48 -0800275 };
276
ludie51e3862017-08-15 19:28:12 -0700277 (*iovecs)[0].iov_base = &nlMsg;
278 (*iovecs)[0].iov_len = NLMSG_HDRLEN;
279 for (const iovec& iov : *iovecs) {
280 nlMsg.nlmsg_len += iov.iov_len;
Nathan Harold1a371532017-01-30 12:30:48 -0800281 }
282
283 ALOGD("Sending Netlink XFRM Message: %s", xfrmMsgTypeToString(nlMsgType));
Manojd9c93c22017-10-19 13:40:26 -0700284 LOG_IOV(*iovecs);
Nathan Harold1a371532017-01-30 12:30:48 -0800285
ludie51e3862017-08-15 19:28:12 -0700286 StatusOr<size_t> writeResult = getSyscallInstance().writev(mSock, *iovecs);
ludi4072ff22017-06-15 08:56:52 -0700287 if (!isOk(writeResult)) {
288 ALOGE("netlink socket writev failed (%s)", toString(writeResult).c_str());
ludi6e8eccd2017-08-14 14:40:37 -0700289 return writeResult;
Nathan Harold1a371532017-01-30 12:30:48 -0800290 }
291
ludi4072ff22017-06-15 08:56:52 -0700292 if (nlMsg.nlmsg_len != writeResult.value()) {
293 ALOGE("Invalid netlink message length sent %d", static_cast<int>(writeResult.value()));
ludi6e8eccd2017-08-14 14:40:37 -0700294 return netdutils::statusFromErrno(EBADMSG, "Invalid message length");
Nathan Harold1a371532017-01-30 12:30:48 -0800295 }
296
ludi4072ff22017-06-15 08:56:52 -0700297 NetlinkResponse response = {};
Nathan Harold1a371532017-01-30 12:30:48 -0800298
ludi4072ff22017-06-15 08:56:52 -0700299 StatusOr<Slice> readResult =
300 getSyscallInstance().read(Fd(mSock), netdutils::makeSlice(response));
301 if (!isOk(readResult)) {
302 ALOGE("netlink response error (%s)", toString(readResult).c_str());
ludi6e8eccd2017-08-14 14:40:37 -0700303 return readResult;
ludi4072ff22017-06-15 08:56:52 -0700304 }
305
306 LOG_HEX("netlink msg resp", reinterpret_cast<char*>(readResult.value().base()),
307 readResult.value().size());
308
ludi6e8eccd2017-08-14 14:40:37 -0700309 Status validateStatus = validateResponse(response, readResult.value().size());
310 if (!isOk(validateStatus)) {
311 ALOGE("netlink response contains error (%s)", toString(validateStatus).c_str());
312 }
313
314 return validateStatus;
Nathan Harold1a371532017-01-30 12:30:48 -0800315 }
316};
317
ludi6e8eccd2017-08-14 14:40:37 -0700318StatusOr<int> convertToXfrmAddr(const std::string& strAddr, xfrm_address_t* xfrmAddr) {
Nathan Harold1a371532017-01-30 12:30:48 -0800319 if (strAddr.length() == 0) {
320 memset(xfrmAddr, 0, sizeof(*xfrmAddr));
321 return AF_UNSPEC;
322 }
323
324 if (inet_pton(AF_INET6, strAddr.c_str(), reinterpret_cast<void*>(xfrmAddr))) {
325 return AF_INET6;
326 } else if (inet_pton(AF_INET, strAddr.c_str(), reinterpret_cast<void*>(xfrmAddr))) {
327 return AF_INET;
328 } else {
ludi6e8eccd2017-08-14 14:40:37 -0700329 return netdutils::statusFromErrno(EAFNOSUPPORT, "Invalid address family");
Nathan Harold1a371532017-01-30 12:30:48 -0800330 }
331}
332
333void fillXfrmNlaHdr(nlattr* hdr, uint16_t type, uint16_t len) {
334 hdr->nla_type = type;
335 hdr->nla_len = len;
336}
337
338void fillXfrmCurLifetimeDefaults(xfrm_lifetime_cur* cur) {
339 memset(reinterpret_cast<char*>(cur), 0, sizeof(*cur));
340}
341void fillXfrmLifetimeDefaults(xfrm_lifetime_cfg* cfg) {
342 cfg->soft_byte_limit = XFRM_INF;
343 cfg->hard_byte_limit = XFRM_INF;
344 cfg->soft_packet_limit = XFRM_INF;
345 cfg->hard_packet_limit = XFRM_INF;
346}
347
348/*
349 * Allocate SPIs within an (inclusive) range of min-max.
350 * returns 0 (INVALID_SPI) once the entire range has been parsed.
351 */
352class RandomSpi {
353public:
354 RandomSpi(int min, int max) : mMin(min) {
Nathan Harold1e284452017-10-10 13:31:19 -0700355 // Re-seeding should be safe because the seed itself is
356 // sufficiently random and we don't need secure random
357 std::mt19937 rnd = std::mt19937(std::random_device()());
358 mNext = std::uniform_int_distribution<>(1, INT_MAX)(rnd);
Nathan Harold1a371532017-01-30 12:30:48 -0800359 mSize = max - min + 1;
360 mCount = mSize;
361 }
362
363 uint32_t next() {
364 if (!mCount)
365 return 0;
366 mCount--;
367 return (mNext++ % mSize) + mMin;
368 }
369
370private:
371 uint32_t mNext;
372 uint32_t mSize;
373 uint32_t mMin;
374 uint32_t mCount;
375};
376
377} // namespace
378
379//
380// Begin XfrmController Impl
381//
382//
383XfrmController::XfrmController(void) {}
384
Nathan Harold21299f72018-03-16 20:13:03 -0700385netdutils::Status XfrmController::Init() {
386 RETURN_IF_NOT_OK(flushInterfaces());
387 XfrmSocketImpl sock;
388 RETURN_IF_NOT_OK(sock.open());
389 RETURN_IF_NOT_OK(flushSaDb(sock));
390 return flushPolicyDb(sock);
391}
392
393netdutils::Status XfrmController::flushInterfaces() {
394 const auto& ifaces = InterfaceController::getIfaceNames();
395 RETURN_IF_NOT_OK(ifaces);
Nathan Harold45c35662018-04-23 10:10:18 -0700396 const String8 ifPrefix8 = String8(INetd::IPSEC_INTERFACE_PREFIX().string());
Nathan Harold21299f72018-03-16 20:13:03 -0700397
398 for (const std::string& iface : ifaces.value()) {
399 int status = 0;
400 // Look for the reserved interface prefix, which must be in the name at position 0
Nathan Haroldb6bd53e2018-05-14 11:56:59 -0700401 if (android::base::StartsWith(iface.c_str(), ifPrefix8.c_str()) &&
Nathan Harold21299f72018-03-16 20:13:03 -0700402 (status = removeVirtualTunnelInterface(iface)) < 0) {
403 ALOGE("Failed to delete ipsec tunnel %s.", iface.c_str());
404 return netdutils::statusFromErrno(status, "Failed to remove ipsec tunnel.");
405 }
406 }
407 return netdutils::status::ok;
408}
409
410netdutils::Status XfrmController::flushSaDb(const XfrmSocket& s) {
411 struct xfrm_usersa_flush flushUserSa = {.proto = IPSEC_PROTO_ANY};
412
Yi Kongbdfd57e2018-07-25 13:26:10 -0700413 std::vector<iovec> iov = {{nullptr, 0}, // reserved for the eventual addition of a NLMSG_HDR
Nathan Harold21299f72018-03-16 20:13:03 -0700414 {&flushUserSa, sizeof(flushUserSa)}, // xfrm_usersa_flush structure
415 {kPadBytes, NLMSG_ALIGN(sizeof(flushUserSa)) - sizeof(flushUserSa)}};
416
417 return s.sendMessage(XFRM_MSG_FLUSHSA, NETLINK_REQUEST_FLAGS, 0, &iov);
418}
419
420netdutils::Status XfrmController::flushPolicyDb(const XfrmSocket& s) {
Yi Kongbdfd57e2018-07-25 13:26:10 -0700421 std::vector<iovec> iov = {{nullptr, 0}}; // reserved for the eventual addition of a NLMSG_HDR
Nathan Harold21299f72018-03-16 20:13:03 -0700422 return s.sendMessage(XFRM_MSG_FLUSHPOLICY, NETLINK_REQUEST_FLAGS, 0, &iov);
423}
424
Benedict Wongb2daefb2017-12-06 22:05:46 -0800425netdutils::Status XfrmController::ipSecSetEncapSocketOwner(const android::base::unique_fd& socket,
426 int newUid, uid_t callerUid) {
427 ALOGD("XfrmController:%s, line=%d", __FUNCTION__, __LINE__);
428
429 const int fd = socket.get();
430 struct stat info;
431 if (fstat(fd, &info)) {
432 return netdutils::statusFromErrno(errno, "Failed to stat socket file descriptor");
433 }
434 if (info.st_uid != callerUid) {
435 return netdutils::statusFromErrno(EPERM, "fchown disabled for non-owner calls");
436 }
Nathan Haroldda54f122018-01-09 16:42:57 -0800437 if (S_ISSOCK(info.st_mode) == 0) {
Benedict Wongb2daefb2017-12-06 22:05:46 -0800438 return netdutils::statusFromErrno(EINVAL, "File descriptor was not a socket");
439 }
440
441 int optval;
Bjoern Johansson9e604592018-07-19 12:30:55 -0700442 socklen_t optlen = sizeof(optval);
Nathan Haroldda54f122018-01-09 16:42:57 -0800443 netdutils::Status status =
444 getSyscallInstance().getsockopt(Fd(socket), IPPROTO_UDP, UDP_ENCAP, &optval, &optlen);
Benedict Wongb2daefb2017-12-06 22:05:46 -0800445 if (status != netdutils::status::ok) {
446 return status;
447 }
Nathan Haroldda54f122018-01-09 16:42:57 -0800448 if (optval != UDP_ENCAP_ESPINUDP && optval != UDP_ENCAP_ESPINUDP_NON_IKE) {
Benedict Wongb2daefb2017-12-06 22:05:46 -0800449 return netdutils::statusFromErrno(EINVAL, "Socket did not have UDP-encap sockopt set");
450 }
451 if (fchown(fd, newUid, -1)) {
452 return netdutils::statusFromErrno(errno, "Failed to fchown socket file descriptor");
453 }
454
455 return netdutils::status::ok;
456}
457
Nathan Haroldda54f122018-01-09 16:42:57 -0800458netdutils::Status XfrmController::ipSecAllocateSpi(int32_t transformId,
459 const std::string& sourceAddress,
460 const std::string& destinationAddress,
461 int32_t inSpi, int32_t* outSpi) {
Nathan Harold1a371532017-01-30 12:30:48 -0800462 ALOGD("XfrmController:%s, line=%d", __FUNCTION__, __LINE__);
463 ALOGD("transformId=%d", transformId);
Nathan Haroldda54f122018-01-09 16:42:57 -0800464 ALOGD("sourceAddress=%s", sourceAddress.c_str());
465 ALOGD("destinationAddress=%s", destinationAddress.c_str());
Nathan Harold1a371532017-01-30 12:30:48 -0800466 ALOGD("inSpi=%0.8x", inSpi);
467
468 XfrmSaInfo saInfo{};
Benedict Wonga04ffa72018-05-09 21:42:42 -0700469 netdutils::Status ret = fillXfrmCommonInfo(sourceAddress, destinationAddress, INVALID_SPI, 0, 0,
470 transformId, &saInfo);
ludi6e8eccd2017-08-14 14:40:37 -0700471 if (!isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800472 return ret;
473 }
474
475 XfrmSocketImpl sock;
ludi6e8eccd2017-08-14 14:40:37 -0700476 netdutils::Status socketStatus = sock.open();
477 if (!isOk(socketStatus)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800478 ALOGD("Sock open failed for XFRM, line=%d", __LINE__);
ludi6e8eccd2017-08-14 14:40:37 -0700479 return socketStatus;
Nathan Harold1a371532017-01-30 12:30:48 -0800480 }
481
482 int minSpi = RAND_SPI_MIN, maxSpi = RAND_SPI_MAX;
483
484 if (inSpi)
485 minSpi = maxSpi = inSpi;
ludi6e8eccd2017-08-14 14:40:37 -0700486
Nathan Harold1a371532017-01-30 12:30:48 -0800487 ret = allocateSpi(saInfo, minSpi, maxSpi, reinterpret_cast<uint32_t*>(outSpi), sock);
ludi6e8eccd2017-08-14 14:40:37 -0700488 if (!isOk(ret)) {
489 // TODO: May want to return a new Status with a modified status string
Nathan Harold1a371532017-01-30 12:30:48 -0800490 ALOGD("Failed to Allocate an SPI, line=%d", __LINE__);
491 *outSpi = INVALID_SPI;
492 }
493
494 return ret;
495}
496
ludi6e8eccd2017-08-14 14:40:37 -0700497netdutils::Status XfrmController::ipSecAddSecurityAssociation(
Nathan Haroldda54f122018-01-09 16:42:57 -0800498 int32_t transformId, int32_t mode, const std::string& sourceAddress,
manojboopathi8707f232018-01-02 14:45:47 -0800499 const std::string& destinationAddress, int32_t underlyingNetId, int32_t spi, int32_t markValue,
500 int32_t markMask, const std::string& authAlgo, const std::vector<uint8_t>& authKey,
501 int32_t authTruncBits, const std::string& cryptAlgo, const std::vector<uint8_t>& cryptKey,
502 int32_t cryptTruncBits, const std::string& aeadAlgo, const std::vector<uint8_t>& aeadKey,
503 int32_t aeadIcvBits, int32_t encapType, int32_t encapLocalPort, int32_t encapRemotePort) {
Nathan Harold1a371532017-01-30 12:30:48 -0800504 ALOGD("XfrmController::%s, line=%d", __FUNCTION__, __LINE__);
505 ALOGD("transformId=%d", transformId);
506 ALOGD("mode=%d", mode);
Nathan Haroldda54f122018-01-09 16:42:57 -0800507 ALOGD("sourceAddress=%s", sourceAddress.c_str());
508 ALOGD("destinationAddress=%s", destinationAddress.c_str());
Benedict Wong96abf482018-01-22 13:56:41 -0800509 ALOGD("underlyingNetworkId=%d", underlyingNetId);
Nathan Harold1a371532017-01-30 12:30:48 -0800510 ALOGD("spi=%0.8x", spi);
Di Lu2ccb3e52018-01-03 16:19:20 -0800511 ALOGD("markValue=%x", markValue);
512 ALOGD("markMask=%x", markMask);
Nathan Harold1a371532017-01-30 12:30:48 -0800513 ALOGD("authAlgo=%s", authAlgo.c_str());
514 ALOGD("authTruncBits=%d", authTruncBits);
515 ALOGD("cryptAlgo=%s", cryptAlgo.c_str());
516 ALOGD("cryptTruncBits=%d,", cryptTruncBits);
Benedict Wongbe65b432017-08-22 21:43:14 -0700517 ALOGD("aeadAlgo=%s", aeadAlgo.c_str());
518 ALOGD("aeadIcvBits=%d,", aeadIcvBits);
Nathan Harold1a371532017-01-30 12:30:48 -0800519 ALOGD("encapType=%d", encapType);
520 ALOGD("encapLocalPort=%d", encapLocalPort);
521 ALOGD("encapRemotePort=%d", encapRemotePort);
522
523 XfrmSaInfo saInfo{};
Benedict Wonga04ffa72018-05-09 21:42:42 -0700524 netdutils::Status ret = fillXfrmCommonInfo(sourceAddress, destinationAddress, spi, markValue,
525 markMask, transformId, &saInfo);
ludi6e8eccd2017-08-14 14:40:37 -0700526 if (!isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800527 return ret;
528 }
529
Nathan Harold1a371532017-01-30 12:30:48 -0800530 saInfo.auth = XfrmAlgo{
531 .name = authAlgo, .key = authKey, .truncLenBits = static_cast<uint16_t>(authTruncBits)};
532
533 saInfo.crypt = XfrmAlgo{
534 .name = cryptAlgo, .key = cryptKey, .truncLenBits = static_cast<uint16_t>(cryptTruncBits)};
535
Benedict Wongbe65b432017-08-22 21:43:14 -0700536 saInfo.aead = XfrmAlgo{
537 .name = aeadAlgo, .key = aeadKey, .truncLenBits = static_cast<uint16_t>(aeadIcvBits)};
538
Nathan Harold1a371532017-01-30 12:30:48 -0800539 switch (static_cast<XfrmMode>(mode)) {
540 case XfrmMode::TRANSPORT:
541 case XfrmMode::TUNNEL:
542 saInfo.mode = static_cast<XfrmMode>(mode);
543 break;
544 default:
ludi6e8eccd2017-08-14 14:40:37 -0700545 return netdutils::statusFromErrno(EINVAL, "Invalid xfrm mode");
Nathan Harold1a371532017-01-30 12:30:48 -0800546 }
547
548 XfrmSocketImpl sock;
ludi6e8eccd2017-08-14 14:40:37 -0700549 netdutils::Status socketStatus = sock.open();
550 if (!isOk(socketStatus)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800551 ALOGD("Sock open failed for XFRM, line=%d", __LINE__);
ludi6e8eccd2017-08-14 14:40:37 -0700552 return socketStatus;
Nathan Harold1a371532017-01-30 12:30:48 -0800553 }
554
Nathan Harold420ceac2017-04-05 19:36:59 -0700555 switch (static_cast<XfrmEncapType>(encapType)) {
556 case XfrmEncapType::ESPINUDP:
557 case XfrmEncapType::ESPINUDP_NON_IKE:
558 if (saInfo.addrFamily != AF_INET) {
ludi6e8eccd2017-08-14 14:40:37 -0700559 return netdutils::statusFromErrno(EAFNOSUPPORT, "IPv6 encap not supported");
Nathan Harold420ceac2017-04-05 19:36:59 -0700560 }
Nathan Haroldda54f122018-01-09 16:42:57 -0800561 // The ports are not used on input SAs, so this is OK to be wrong when
562 // direction is ultimately input.
563 saInfo.encap.srcPort = encapLocalPort;
564 saInfo.encap.dstPort = encapRemotePort;
Bernie Innocenti8bb94ba2018-10-10 22:30:12 +0900565 [[fallthrough]];
Nathan Harold420ceac2017-04-05 19:36:59 -0700566 case XfrmEncapType::NONE:
567 saInfo.encap.type = static_cast<XfrmEncapType>(encapType);
568 break;
569 default:
ludi6e8eccd2017-08-14 14:40:37 -0700570 return netdutils::statusFromErrno(EINVAL, "Invalid encap type");
Nathan Harold420ceac2017-04-05 19:36:59 -0700571 }
572
Benedict Wong96abf482018-01-22 13:56:41 -0800573 saInfo.netId = underlyingNetId;
574
Di Lu0e16b5e2018-01-12 10:37:53 -0800575 ret = updateSecurityAssociation(saInfo, sock);
ludi6e8eccd2017-08-14 14:40:37 -0700576 if (!isOk(ret)) {
Di Lu0e16b5e2018-01-12 10:37:53 -0800577 ALOGD("Failed updating a Security Association, line=%d", __LINE__);
Nathan Harold1a371532017-01-30 12:30:48 -0800578 }
579
ludi6e8eccd2017-08-14 14:40:37 -0700580 return ret;
Nathan Harold1a371532017-01-30 12:30:48 -0800581}
582
Di Lu2ccb3e52018-01-03 16:19:20 -0800583netdutils::Status XfrmController::ipSecDeleteSecurityAssociation(
584 int32_t transformId, const std::string& sourceAddress, const std::string& destinationAddress,
585 int32_t spi, int32_t markValue, int32_t markMask) {
Nathan Harold1a371532017-01-30 12:30:48 -0800586 ALOGD("XfrmController:%s, line=%d", __FUNCTION__, __LINE__);
587 ALOGD("transformId=%d", transformId);
Nathan Haroldda54f122018-01-09 16:42:57 -0800588 ALOGD("sourceAddress=%s", sourceAddress.c_str());
589 ALOGD("destinationAddress=%s", destinationAddress.c_str());
Nathan Harold1a371532017-01-30 12:30:48 -0800590 ALOGD("spi=%0.8x", spi);
Di Lu2ccb3e52018-01-03 16:19:20 -0800591 ALOGD("markValue=%x", markValue);
592 ALOGD("markMask=%x", markMask);
Nathan Harold1a371532017-01-30 12:30:48 -0800593
Benedict Wonga04ffa72018-05-09 21:42:42 -0700594 XfrmSaInfo saInfo{};
595 netdutils::Status ret = fillXfrmCommonInfo(sourceAddress, destinationAddress, spi, markValue,
596 markMask, transformId, &saInfo);
ludi6e8eccd2017-08-14 14:40:37 -0700597 if (!isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800598 return ret;
599 }
600
601 XfrmSocketImpl sock;
ludi6e8eccd2017-08-14 14:40:37 -0700602 netdutils::Status socketStatus = sock.open();
603 if (!isOk(socketStatus)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800604 ALOGD("Sock open failed for XFRM, line=%d", __LINE__);
ludi6e8eccd2017-08-14 14:40:37 -0700605 return socketStatus;
Nathan Harold1a371532017-01-30 12:30:48 -0800606 }
607
Benedict Wonga04ffa72018-05-09 21:42:42 -0700608 ret = deleteSecurityAssociation(saInfo, sock);
ludi6e8eccd2017-08-14 14:40:37 -0700609 if (!isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800610 ALOGD("Failed to delete Security Association, line=%d", __LINE__);
Nathan Harold1a371532017-01-30 12:30:48 -0800611 }
612
613 return ret;
614}
615
Benedict Wonga04ffa72018-05-09 21:42:42 -0700616netdutils::Status XfrmController::fillXfrmCommonInfo(const std::string& sourceAddress,
617 const std::string& destinationAddress,
618 int32_t spi, int32_t markValue,
619 int32_t markMask, int32_t transformId,
620 XfrmCommonInfo* info) {
Nathan Harold7441c692017-12-12 21:25:01 -0800621 // Use the addresses to determine the address family and do validation
Nathan Haroldda54f122018-01-09 16:42:57 -0800622 xfrm_address_t sourceXfrmAddr{}, destXfrmAddr{};
623 StatusOr<int> sourceFamily, destFamily;
624 sourceFamily = convertToXfrmAddr(sourceAddress, &sourceXfrmAddr);
625 destFamily = convertToXfrmAddr(destinationAddress, &destXfrmAddr);
626 if (!isOk(sourceFamily) || !isOk(destFamily)) {
627 return netdutils::statusFromErrno(EINVAL, "Invalid address " + sourceAddress + "/" +
628 destinationAddress);
Nathan Harold1a371532017-01-30 12:30:48 -0800629 }
630
Nathan Haroldda54f122018-01-09 16:42:57 -0800631 if (destFamily.value() == AF_UNSPEC ||
632 (sourceFamily.value() != AF_UNSPEC && sourceFamily.value() != destFamily.value())) {
633 ALOGD("Invalid or Mismatched Address Families, %d != %d, line=%d", sourceFamily.value(),
634 destFamily.value(), __LINE__);
ludi6e8eccd2017-08-14 14:40:37 -0700635 return netdutils::statusFromErrno(EINVAL, "Invalid or mismatched address families");
Nathan Harold1a371532017-01-30 12:30:48 -0800636 }
637
Benedict Wonga04ffa72018-05-09 21:42:42 -0700638 info->addrFamily = destFamily.value();
Nathan Harold1a371532017-01-30 12:30:48 -0800639
Benedict Wonga04ffa72018-05-09 21:42:42 -0700640 info->dstAddr = destXfrmAddr;
641 info->srcAddr = sourceXfrmAddr;
642
643 return fillXfrmCommonInfo(spi, markValue, markMask, transformId, info);
644}
645
646netdutils::Status XfrmController::fillXfrmCommonInfo(int32_t spi, int32_t markValue,
647 int32_t markMask, int32_t transformId,
648 XfrmCommonInfo* info) {
649 info->transformId = transformId;
650 info->spi = htonl(spi);
651 info->mark.v = markValue;
652 info->mark.m = markMask;
653
ludi6e8eccd2017-08-14 14:40:37 -0700654 return netdutils::status::ok;
Nathan Harold1a371532017-01-30 12:30:48 -0800655}
656
ludi6e8eccd2017-08-14 14:40:37 -0700657netdutils::Status XfrmController::ipSecApplyTransportModeTransform(
658 const android::base::unique_fd& socket, int32_t transformId, int32_t direction,
Nathan Haroldda54f122018-01-09 16:42:57 -0800659 const std::string& sourceAddress, const std::string& destinationAddress, int32_t spi) {
Nathan Harold1a371532017-01-30 12:30:48 -0800660 ALOGD("XfrmController::%s, line=%d", __FUNCTION__, __LINE__);
661 ALOGD("transformId=%d", transformId);
662 ALOGD("direction=%d", direction);
Nathan Haroldda54f122018-01-09 16:42:57 -0800663 ALOGD("sourceAddress=%s", sourceAddress.c_str());
664 ALOGD("destinationAddress=%s", destinationAddress.c_str());
Nathan Harold1a371532017-01-30 12:30:48 -0800665 ALOGD("spi=%0.8x", spi);
666
ludi4072ff22017-06-15 08:56:52 -0700667 StatusOr<sockaddr_storage> ret = getSyscallInstance().getsockname<sockaddr_storage>(Fd(socket));
668 if (!isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800669 ALOGE("Failed to get socket info in %s", __FUNCTION__);
ludi6e8eccd2017-08-14 14:40:37 -0700670 return ret;
Nathan Harold1a371532017-01-30 12:30:48 -0800671 }
Nathan Harold7441c692017-12-12 21:25:01 -0800672 struct sockaddr_storage saddr = ret.value();
ludi4072ff22017-06-15 08:56:52 -0700673
Benedict Wonga04ffa72018-05-09 21:42:42 -0700674 XfrmSpInfo spInfo{};
Nathan Harold7441c692017-12-12 21:25:01 -0800675 netdutils::Status status =
Benedict Wonga04ffa72018-05-09 21:42:42 -0700676 fillXfrmCommonInfo(sourceAddress, destinationAddress, spi, 0, 0, transformId, &spInfo);
ludi6e8eccd2017-08-14 14:40:37 -0700677 if (!isOk(status)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800678 ALOGE("Couldn't build SA ID %s", __FUNCTION__);
ludi6e8eccd2017-08-14 14:40:37 -0700679 return status;
Nathan Harold1a371532017-01-30 12:30:48 -0800680 }
681
Benedict Wonga04ffa72018-05-09 21:42:42 -0700682 spInfo.selAddrFamily = spInfo.addrFamily;
683
684 // Allow dual stack sockets. Dual stack sockets are guaranteed to never have an AF_INET source
685 // address; the source address would instead be an IPv4-mapped address. Thus, disallow AF_INET
686 // sockets with mismatched address families (All other cases are acceptable).
687 if (saddr.ss_family == AF_INET && spInfo.addrFamily != AF_INET) {
manojboopathi26f42922017-12-14 10:51:57 -0800688 ALOGE("IPV4 socket address family(%d) should match IPV4 Transform "
689 "address family(%d)!",
Benedict Wonga04ffa72018-05-09 21:42:42 -0700690 saddr.ss_family, spInfo.addrFamily);
ludi6e8eccd2017-08-14 14:40:37 -0700691 return netdutils::statusFromErrno(EINVAL, "Mismatched address family");
Nathan Harold1a371532017-01-30 12:30:48 -0800692 }
693
694 struct {
695 xfrm_userpolicy_info info;
696 xfrm_user_tmpl tmpl;
697 } policy{};
698
Benedict Wonga04ffa72018-05-09 21:42:42 -0700699 fillUserSpInfo(spInfo, static_cast<XfrmDirection>(direction), &policy.info);
700 fillUserTemplate(spInfo, &policy.tmpl);
Nathan Harold1a371532017-01-30 12:30:48 -0800701
702 LOG_HEX("XfrmUserPolicy", reinterpret_cast<char*>(&policy), sizeof(policy));
703
704 int sockOpt, sockLayer;
manojboopathi26f42922017-12-14 10:51:57 -0800705 switch (saddr.ss_family) {
Nathan Harold1a371532017-01-30 12:30:48 -0800706 case AF_INET:
707 sockOpt = IP_XFRM_POLICY;
708 sockLayer = SOL_IP;
709 break;
710 case AF_INET6:
711 sockOpt = IPV6_XFRM_POLICY;
712 sockLayer = SOL_IPV6;
713 break;
714 default:
ludi6e8eccd2017-08-14 14:40:37 -0700715 return netdutils::statusFromErrno(EAFNOSUPPORT, "Invalid address family");
Nathan Harold1a371532017-01-30 12:30:48 -0800716 }
717
ludi6e8eccd2017-08-14 14:40:37 -0700718 status = getSyscallInstance().setsockopt(Fd(socket), sockLayer, sockOpt, policy);
ludi4072ff22017-06-15 08:56:52 -0700719 if (!isOk(status)) {
720 ALOGE("Error setting socket option for XFRM! (%s)", toString(status).c_str());
Nathan Harold1a371532017-01-30 12:30:48 -0800721 }
ludi6e8eccd2017-08-14 14:40:37 -0700722
723 return status;
Nathan Harold1a371532017-01-30 12:30:48 -0800724}
725
ludi6e8eccd2017-08-14 14:40:37 -0700726netdutils::Status
727XfrmController::ipSecRemoveTransportModeTransform(const android::base::unique_fd& socket) {
ludi87991632017-10-30 15:28:11 -0700728 ALOGD("XfrmController::%s, line=%d", __FUNCTION__, __LINE__);
729
730 StatusOr<sockaddr_storage> ret = getSyscallInstance().getsockname<sockaddr_storage>(Fd(socket));
731 if (!isOk(ret)) {
732 ALOGE("Failed to get socket info in %s! (%s)", __FUNCTION__, toString(ret).c_str());
733 return ret;
734 }
735
736 int sockOpt, sockLayer;
737 switch (ret.value().ss_family) {
738 case AF_INET:
739 sockOpt = IP_XFRM_POLICY;
740 sockLayer = SOL_IP;
741 break;
742 case AF_INET6:
743 sockOpt = IPV6_XFRM_POLICY;
744 sockLayer = SOL_IPV6;
745 break;
746 default:
747 return netdutils::statusFromErrno(EAFNOSUPPORT, "Invalid address family");
748 }
749
750 // Kernel will delete the security policy on this socket for both direction
751 // if optval is set to NULL and optlen is set to 0.
752 netdutils::Status status =
Yi Kongbdfd57e2018-07-25 13:26:10 -0700753 getSyscallInstance().setsockopt(Fd(socket), sockLayer, sockOpt, nullptr, 0);
ludi87991632017-10-30 15:28:11 -0700754 if (!isOk(status)) {
755 ALOGE("Error removing socket option for XFRM! (%s)", toString(status).c_str());
756 }
757
758 return status;
Nathan Harold1a371532017-01-30 12:30:48 -0800759}
760
Benedict Wonga04ffa72018-05-09 21:42:42 -0700761netdutils::Status XfrmController::ipSecAddSecurityPolicy(int32_t transformId, int32_t selAddrFamily,
762 int32_t direction,
Benedict Wongad600cb2018-05-14 17:22:35 -0700763 const std::string& tmplSrcAddress,
764 const std::string& tmplDstAddress,
Di Lu2ccb3e52018-01-03 16:19:20 -0800765 int32_t spi, int32_t markValue,
766 int32_t markMask) {
Benedict Wonga04ffa72018-05-09 21:42:42 -0700767 return processSecurityPolicy(transformId, selAddrFamily, direction, tmplSrcAddress,
768 tmplDstAddress, spi, markValue, markMask, XFRM_MSG_NEWPOLICY);
ludi771b8002017-11-20 15:09:05 -0800769}
770
Benedict Wonga04ffa72018-05-09 21:42:42 -0700771netdutils::Status XfrmController::ipSecUpdateSecurityPolicy(
772 int32_t transformId, int32_t selAddrFamily, int32_t direction,
773 const std::string& tmplSrcAddress, const std::string& tmplDstAddress, int32_t spi,
774 int32_t markValue, int32_t markMask) {
775 return processSecurityPolicy(transformId, selAddrFamily, direction, tmplSrcAddress,
776 tmplDstAddress, spi, markValue, markMask, XFRM_MSG_UPDPOLICY);
777}
778
779netdutils::Status XfrmController::ipSecDeleteSecurityPolicy(int32_t transformId,
780 int32_t selAddrFamily,
781 int32_t direction, int32_t markValue,
Di Lu2ccb3e52018-01-03 16:19:20 -0800782 int32_t markMask) {
Benedict Wonga04ffa72018-05-09 21:42:42 -0700783 return processSecurityPolicy(transformId, selAddrFamily, direction, "", "", 0, markValue,
784 markMask, XFRM_MSG_DELPOLICY);
ludi771b8002017-11-20 15:09:05 -0800785}
786
Benedict Wonga04ffa72018-05-09 21:42:42 -0700787netdutils::Status XfrmController::processSecurityPolicy(int32_t transformId, int32_t selAddrFamily,
788 int32_t direction,
Benedict Wongad600cb2018-05-14 17:22:35 -0700789 const std::string& tmplSrcAddress,
790 const std::string& tmplDstAddress,
Di Lu2ccb3e52018-01-03 16:19:20 -0800791 int32_t spi, int32_t markValue,
792 int32_t markMask, int32_t msgType) {
ludi771b8002017-11-20 15:09:05 -0800793 ALOGD("XfrmController::%s, line=%d", __FUNCTION__, __LINE__);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700794 ALOGD("selAddrFamily=%s", selAddrFamily == AF_INET6 ? "AF_INET6" : "AF_INET");
ludi771b8002017-11-20 15:09:05 -0800795 ALOGD("transformId=%d", transformId);
796 ALOGD("direction=%d", direction);
Benedict Wongad600cb2018-05-14 17:22:35 -0700797 ALOGD("tmplSrcAddress=%s", tmplSrcAddress.c_str());
798 ALOGD("tmplDstAddress=%s", tmplDstAddress.c_str());
ludi771b8002017-11-20 15:09:05 -0800799 ALOGD("spi=%0.8x", spi);
Di Lu2ccb3e52018-01-03 16:19:20 -0800800 ALOGD("markValue=%d", markValue);
801 ALOGD("markMask=%d", markMask);
ludi771b8002017-11-20 15:09:05 -0800802 ALOGD("msgType=%d", msgType);
803
Benedict Wonga04ffa72018-05-09 21:42:42 -0700804 XfrmSpInfo spInfo{};
805 spInfo.mode = XfrmMode::TUNNEL;
ludi771b8002017-11-20 15:09:05 -0800806
807 XfrmSocketImpl sock;
808 RETURN_IF_NOT_OK(sock.open());
809
Benedict Wonga04ffa72018-05-09 21:42:42 -0700810 // Set the correct address families. Tunnel mode policies use wildcard selectors, while
811 // templates have addresses set. These may be different address families. This method is called
812 // separately for IPv4 and IPv6 policies, and thus only need to map a single inner address
813 // family to the outer address families.
814 spInfo.selAddrFamily = selAddrFamily;
ludi771b8002017-11-20 15:09:05 -0800815
816 if (msgType == XFRM_MSG_DELPOLICY) {
Benedict Wonga04ffa72018-05-09 21:42:42 -0700817 RETURN_IF_NOT_OK(fillXfrmCommonInfo(spi, markValue, markMask, transformId, &spInfo));
818
819 return deleteTunnelModeSecurityPolicy(spInfo, sock, static_cast<XfrmDirection>(direction));
ludi771b8002017-11-20 15:09:05 -0800820 } else {
Benedict Wonga04ffa72018-05-09 21:42:42 -0700821 RETURN_IF_NOT_OK(fillXfrmCommonInfo(tmplSrcAddress, tmplDstAddress, spi, markValue,
822 markMask, transformId, &spInfo));
823
824 return updateTunnelModeSecurityPolicy(spInfo, sock, static_cast<XfrmDirection>(direction),
ludi771b8002017-11-20 15:09:05 -0800825 msgType);
826 }
827}
828
Benedict Wonga04ffa72018-05-09 21:42:42 -0700829void XfrmController::fillXfrmSelector(const int selAddrFamily, xfrm_selector* selector) {
830 selector->family = selAddrFamily;
manojboopathi8707f232018-01-02 14:45:47 -0800831 selector->proto = AF_UNSPEC; // TODO: do we need to match the protocol? it's
832 // possible via the socket
Nathan Harold1a371532017-01-30 12:30:48 -0800833}
834
Di Lu0e16b5e2018-01-12 10:37:53 -0800835netdutils::Status XfrmController::updateSecurityAssociation(const XfrmSaInfo& record,
manojboopathi4d2d6f12017-12-06 11:11:31 -0800836 const XfrmSocket& sock) {
Nathan Harold1a371532017-01-30 12:30:48 -0800837 xfrm_usersa_info usersa{};
838 nlattr_algo_crypt crypt{};
839 nlattr_algo_auth auth{};
Benedict Wongbe65b432017-08-22 21:43:14 -0700840 nlattr_algo_aead aead{};
Di Lu2ccb3e52018-01-03 16:19:20 -0800841 nlattr_xfrm_mark xfrmmark{};
Benedict Wong96abf482018-01-22 13:56:41 -0800842 nlattr_xfrm_output_mark xfrmoutputmark{};
Nathan Harold420ceac2017-04-05 19:36:59 -0700843 nlattr_encap_tmpl encap{};
Nathan Harold1a371532017-01-30 12:30:48 -0800844
Benedict Wongbe65b432017-08-22 21:43:14 -0700845 enum {
846 NLMSG_HDR,
847 USERSA,
848 USERSA_PAD,
849 CRYPT,
850 CRYPT_PAD,
851 AUTH,
852 AUTH_PAD,
853 AEAD,
854 AEAD_PAD,
Di Lu2ccb3e52018-01-03 16:19:20 -0800855 MARK,
856 MARK_PAD,
Benedict Wong96abf482018-01-22 13:56:41 -0800857 OUTPUT_MARK,
858 OUTPUT_MARK_PAD,
Benedict Wongbe65b432017-08-22 21:43:14 -0700859 ENCAP,
Di Lu2ccb3e52018-01-03 16:19:20 -0800860 ENCAP_PAD,
Benedict Wongbe65b432017-08-22 21:43:14 -0700861 };
Nathan Harold1a371532017-01-30 12:30:48 -0800862
ludie51e3862017-08-15 19:28:12 -0700863 std::vector<iovec> iov = {
Yi Kongbdfd57e2018-07-25 13:26:10 -0700864 {nullptr, 0}, // reserved for the eventual addition of a NLMSG_HDR
Benedict Wong96abf482018-01-22 13:56:41 -0800865 {&usersa, 0}, // main usersa_info struct
866 {kPadBytes, 0}, // up to NLMSG_ALIGNTO pad bytes of padding
867 {&crypt, 0}, // adjust size if crypt algo is present
868 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
869 {&auth, 0}, // adjust size if auth algo is present
870 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
871 {&aead, 0}, // adjust size if aead algo is present
872 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
873 {&xfrmmark, 0}, // adjust size if xfrm mark is present
874 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
875 {&xfrmoutputmark, 0}, // adjust size if xfrm output mark is present
876 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
877 {&encap, 0}, // adjust size if encapsulating
878 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
Nathan Harold1a371532017-01-30 12:30:48 -0800879 };
880
Benedict Wongbe65b432017-08-22 21:43:14 -0700881 if (!record.aead.name.empty() && (!record.auth.name.empty() || !record.crypt.name.empty())) {
882 return netdutils::statusFromErrno(EINVAL, "Invalid xfrm algo selection; AEAD is mutually "
883 "exclusive with both Authentication and "
884 "Encryption");
885 }
886
Benedict Wong4f60ee12017-10-10 12:27:25 -0700887 if (record.aead.key.size() > MAX_KEY_LENGTH || record.auth.key.size() > MAX_KEY_LENGTH ||
888 record.crypt.key.size() > MAX_KEY_LENGTH) {
889 return netdutils::statusFromErrno(EINVAL, "Key length invalid; exceeds MAX_KEY_LENGTH");
Benedict Wongbe65b432017-08-22 21:43:14 -0700890 }
891
Nathan Harold1a371532017-01-30 12:30:48 -0800892 int len;
893 len = iov[USERSA].iov_len = fillUserSaInfo(record, &usersa);
894 iov[USERSA_PAD].iov_len = NLMSG_ALIGN(len) - len;
895
896 len = iov[CRYPT].iov_len = fillNlAttrXfrmAlgoEnc(record.crypt, &crypt);
897 iov[CRYPT_PAD].iov_len = NLA_ALIGN(len) - len;
898
899 len = iov[AUTH].iov_len = fillNlAttrXfrmAlgoAuth(record.auth, &auth);
900 iov[AUTH_PAD].iov_len = NLA_ALIGN(len) - len;
901
Benedict Wongbe65b432017-08-22 21:43:14 -0700902 len = iov[AEAD].iov_len = fillNlAttrXfrmAlgoAead(record.aead, &aead);
903 iov[AEAD_PAD].iov_len = NLA_ALIGN(len) - len;
904
Di Lu2ccb3e52018-01-03 16:19:20 -0800905 len = iov[MARK].iov_len = fillNlAttrXfrmMark(record, &xfrmmark);
906 iov[MARK_PAD].iov_len = NLA_ALIGN(len) - len;
907
Benedict Wong96abf482018-01-22 13:56:41 -0800908 len = iov[OUTPUT_MARK].iov_len = fillNlAttrXfrmOutputMark(record.netId, &xfrmoutputmark);
909 iov[OUTPUT_MARK_PAD].iov_len = NLA_ALIGN(len) - len;
910
Nathan Harold420ceac2017-04-05 19:36:59 -0700911 len = iov[ENCAP].iov_len = fillNlAttrXfrmEncapTmpl(record, &encap);
912 iov[ENCAP_PAD].iov_len = NLA_ALIGN(len) - len;
Di Lu2ccb3e52018-01-03 16:19:20 -0800913
ludie51e3862017-08-15 19:28:12 -0700914 return sock.sendMessage(XFRM_MSG_UPDSA, NETLINK_REQUEST_FLAGS, 0, &iov);
Nathan Harold1a371532017-01-30 12:30:48 -0800915}
916
917int XfrmController::fillNlAttrXfrmAlgoEnc(const XfrmAlgo& inAlgo, nlattr_algo_crypt* algo) {
Benedict Wongbe65b432017-08-22 21:43:14 -0700918 if (inAlgo.name.empty()) { // Do not fill anything if algorithm not provided
919 return 0;
920 }
921
Nathan Harold1a371532017-01-30 12:30:48 -0800922 int len = NLA_HDRLEN + sizeof(xfrm_algo);
Benedict Wongbe65b432017-08-22 21:43:14 -0700923 // Kernel always changes last char to null terminator; no safety checks needed.
Nathan Harold1a371532017-01-30 12:30:48 -0800924 strncpy(algo->crypt.alg_name, inAlgo.name.c_str(), sizeof(algo->crypt.alg_name));
Nathan Harold7441c692017-12-12 21:25:01 -0800925 algo->crypt.alg_key_len = inAlgo.key.size() * 8; // bits
Benedict Wongbe65b432017-08-22 21:43:14 -0700926 memcpy(algo->key, &inAlgo.key[0], inAlgo.key.size());
Nathan Harold1a371532017-01-30 12:30:48 -0800927 len += inAlgo.key.size();
928 fillXfrmNlaHdr(&algo->hdr, XFRMA_ALG_CRYPT, len);
929 return len;
930}
931
932int XfrmController::fillNlAttrXfrmAlgoAuth(const XfrmAlgo& inAlgo, nlattr_algo_auth* algo) {
Benedict Wongbe65b432017-08-22 21:43:14 -0700933 if (inAlgo.name.empty()) { // Do not fill anything if algorithm not provided
934 return 0;
935 }
936
Nathan Harold1a371532017-01-30 12:30:48 -0800937 int len = NLA_HDRLEN + sizeof(xfrm_algo_auth);
Benedict Wongbe65b432017-08-22 21:43:14 -0700938 // Kernel always changes last char to null terminator; no safety checks needed.
Nathan Harold1a371532017-01-30 12:30:48 -0800939 strncpy(algo->auth.alg_name, inAlgo.name.c_str(), sizeof(algo->auth.alg_name));
940 algo->auth.alg_key_len = inAlgo.key.size() * 8; // bits
941
942 // This is the extra field for ALG_AUTH_TRUNC
943 algo->auth.alg_trunc_len = inAlgo.truncLenBits;
944
Benedict Wongbe65b432017-08-22 21:43:14 -0700945 memcpy(algo->key, &inAlgo.key[0], inAlgo.key.size());
Nathan Harold1a371532017-01-30 12:30:48 -0800946 len += inAlgo.key.size();
947
948 fillXfrmNlaHdr(&algo->hdr, XFRMA_ALG_AUTH_TRUNC, len);
949 return len;
950}
951
Benedict Wongbe65b432017-08-22 21:43:14 -0700952int XfrmController::fillNlAttrXfrmAlgoAead(const XfrmAlgo& inAlgo, nlattr_algo_aead* algo) {
953 if (inAlgo.name.empty()) { // Do not fill anything if algorithm not provided
954 return 0;
955 }
956
957 int len = NLA_HDRLEN + sizeof(xfrm_algo_aead);
958 // Kernel always changes last char to null terminator; no safety checks needed.
959 strncpy(algo->aead.alg_name, inAlgo.name.c_str(), sizeof(algo->aead.alg_name));
960 algo->aead.alg_key_len = inAlgo.key.size() * 8; // bits
961
962 // This is the extra field for ALG_AEAD. ICV length is the same as truncation length
963 // for any AEAD algorithm.
964 algo->aead.alg_icv_len = inAlgo.truncLenBits;
965
966 memcpy(algo->key, &inAlgo.key[0], inAlgo.key.size());
967 len += inAlgo.key.size();
968
969 fillXfrmNlaHdr(&algo->hdr, XFRMA_ALG_AEAD, len);
970 return len;
971}
972
Nathan Harold420ceac2017-04-05 19:36:59 -0700973int XfrmController::fillNlAttrXfrmEncapTmpl(const XfrmSaInfo& record, nlattr_encap_tmpl* tmpl) {
974 if (record.encap.type == XfrmEncapType::NONE) {
975 return 0;
976 }
977
978 int len = NLA_HDRLEN + sizeof(xfrm_encap_tmpl);
979 tmpl->tmpl.encap_type = static_cast<uint16_t>(record.encap.type);
980 tmpl->tmpl.encap_sport = htons(record.encap.srcPort);
981 tmpl->tmpl.encap_dport = htons(record.encap.dstPort);
982 fillXfrmNlaHdr(&tmpl->hdr, XFRMA_ENCAP, len);
983 return len;
984}
985
Nathan Harold1a371532017-01-30 12:30:48 -0800986int XfrmController::fillUserSaInfo(const XfrmSaInfo& record, xfrm_usersa_info* usersa) {
Benedict Wonga04ffa72018-05-09 21:42:42 -0700987 // Use AF_UNSPEC for all SAs. In transport mode, kernel picks selector family based on
988 // usersa->family, while in tunnel mode, the XFRM_STATE_AF_UNSPEC flag allows dual-stack SAs.
989 fillXfrmSelector(AF_UNSPEC, &usersa->sel);
Nathan Harold1a371532017-01-30 12:30:48 -0800990
991 usersa->id.proto = IPPROTO_ESP;
992 usersa->id.spi = record.spi;
993 usersa->id.daddr = record.dstAddr;
994
995 usersa->saddr = record.srcAddr;
996
997 fillXfrmLifetimeDefaults(&usersa->lft);
998 fillXfrmCurLifetimeDefaults(&usersa->curlft);
999 memset(&usersa->stats, 0, sizeof(usersa->stats)); // leave stats zeroed out
1000 usersa->reqid = record.transformId;
1001 usersa->family = record.addrFamily;
1002 usersa->mode = static_cast<uint8_t>(record.mode);
1003 usersa->replay_window = REPLAY_WINDOW_SIZE;
manojboopathi4d2d6f12017-12-06 11:11:31 -08001004
1005 if (record.mode == XfrmMode::TRANSPORT) {
1006 usersa->flags = 0; // TODO: should we actually set flags, XFRM_SA_XFLAG_DONT_ENCAP_DSCP?
1007 } else {
1008 usersa->flags = XFRM_STATE_AF_UNSPEC;
1009 }
1010
Nathan Harold1a371532017-01-30 12:30:48 -08001011 return sizeof(*usersa);
1012}
1013
Benedict Wonga04ffa72018-05-09 21:42:42 -07001014int XfrmController::fillUserSaId(const XfrmCommonInfo& record, xfrm_usersa_id* said) {
Nathan Harold1a371532017-01-30 12:30:48 -08001015 said->daddr = record.dstAddr;
1016 said->spi = record.spi;
1017 said->family = record.addrFamily;
1018 said->proto = IPPROTO_ESP;
1019
1020 return sizeof(*said);
1021}
1022
Benedict Wonga04ffa72018-05-09 21:42:42 -07001023netdutils::Status XfrmController::deleteSecurityAssociation(const XfrmCommonInfo& record,
ludi6e8eccd2017-08-14 14:40:37 -07001024 const XfrmSocket& sock) {
Nathan Harold1a371532017-01-30 12:30:48 -08001025 xfrm_usersa_id said{};
Di Lu2ccb3e52018-01-03 16:19:20 -08001026 nlattr_xfrm_mark xfrmmark{};
Nathan Harold1a371532017-01-30 12:30:48 -08001027
Di Lu2ccb3e52018-01-03 16:19:20 -08001028 enum { NLMSG_HDR, USERSAID, USERSAID_PAD, MARK, MARK_PAD };
Nathan Harold1a371532017-01-30 12:30:48 -08001029
ludie51e3862017-08-15 19:28:12 -07001030 std::vector<iovec> iov = {
Yi Kongbdfd57e2018-07-25 13:26:10 -07001031 {nullptr, 0}, // reserved for the eventual addition of a NLMSG_HDR
Nathan Harold1a371532017-01-30 12:30:48 -08001032 {&said, 0}, // main usersa_info struct
1033 {kPadBytes, 0}, // up to NLMSG_ALIGNTO pad bytes of padding
manojboopathi8707f232018-01-02 14:45:47 -08001034 {&xfrmmark, 0}, // adjust size if xfrm mark is present
1035 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
Nathan Harold1a371532017-01-30 12:30:48 -08001036 };
1037
1038 int len;
1039 len = iov[USERSAID].iov_len = fillUserSaId(record, &said);
1040 iov[USERSAID_PAD].iov_len = NLMSG_ALIGN(len) - len;
1041
Di Lu2ccb3e52018-01-03 16:19:20 -08001042 len = iov[MARK].iov_len = fillNlAttrXfrmMark(record, &xfrmmark);
1043 iov[MARK_PAD].iov_len = NLA_ALIGN(len) - len;
1044
ludie51e3862017-08-15 19:28:12 -07001045 return sock.sendMessage(XFRM_MSG_DELSA, NETLINK_REQUEST_FLAGS, 0, &iov);
Nathan Harold1a371532017-01-30 12:30:48 -08001046}
1047
ludi6e8eccd2017-08-14 14:40:37 -07001048netdutils::Status XfrmController::allocateSpi(const XfrmSaInfo& record, uint32_t minSpi,
1049 uint32_t maxSpi, uint32_t* outSpi,
1050 const XfrmSocket& sock) {
Nathan Harold1a371532017-01-30 12:30:48 -08001051 xfrm_userspi_info spiInfo{};
1052
ludie51e3862017-08-15 19:28:12 -07001053 enum { NLMSG_HDR, USERSAID, USERSAID_PAD };
Nathan Harold1a371532017-01-30 12:30:48 -08001054
ludie51e3862017-08-15 19:28:12 -07001055 std::vector<iovec> iov = {
Yi Kongbdfd57e2018-07-25 13:26:10 -07001056 {nullptr, 0}, // reserved for the eventual addition of a NLMSG_HDR
Nathan Harold1a371532017-01-30 12:30:48 -08001057 {&spiInfo, 0}, // main userspi_info struct
1058 {kPadBytes, 0}, // up to NLMSG_ALIGNTO pad bytes of padding
1059 };
1060
1061 int len;
1062 if (fillUserSaInfo(record, &spiInfo.info) == 0) {
1063 ALOGE("Failed to fill transport SA Info");
1064 }
1065
1066 len = iov[USERSAID].iov_len = sizeof(spiInfo);
1067 iov[USERSAID_PAD].iov_len = NLMSG_ALIGN(len) - len;
1068
1069 RandomSpi spiGen = RandomSpi(minSpi, maxSpi);
ludi6e8eccd2017-08-14 14:40:37 -07001070 int spi;
1071 netdutils::Status ret;
Nathan Harold1a371532017-01-30 12:30:48 -08001072 while ((spi = spiGen.next()) != INVALID_SPI) {
1073 spiInfo.min = spi;
1074 spiInfo.max = spi;
ludie51e3862017-08-15 19:28:12 -07001075 ret = sock.sendMessage(XFRM_MSG_ALLOCSPI, NETLINK_REQUEST_FLAGS, 0, &iov);
Nathan Harold1a371532017-01-30 12:30:48 -08001076
1077 /* If the SPI is in use, we'll get ENOENT */
ludi6e8eccd2017-08-14 14:40:37 -07001078 if (netdutils::equalToErrno(ret, ENOENT))
Nathan Harold1a371532017-01-30 12:30:48 -08001079 continue;
1080
ludi6e8eccd2017-08-14 14:40:37 -07001081 if (isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -08001082 *outSpi = spi;
Nathan Harold420ceac2017-04-05 19:36:59 -07001083 ALOGD("Allocated an SPI: %x", *outSpi);
Nathan Harold1a371532017-01-30 12:30:48 -08001084 } else {
1085 *outSpi = INVALID_SPI;
ludi6e8eccd2017-08-14 14:40:37 -07001086 ALOGE("SPI Allocation Failed with error %d", ret.code());
Nathan Harold1a371532017-01-30 12:30:48 -08001087 }
1088
1089 return ret;
1090 }
1091
1092 // Should always be -ENOENT if we get here
1093 return ret;
1094}
1095
Benedict Wonga04ffa72018-05-09 21:42:42 -07001096netdutils::Status XfrmController::updateTunnelModeSecurityPolicy(const XfrmSpInfo& record,
ludi771b8002017-11-20 15:09:05 -08001097 const XfrmSocket& sock,
1098 XfrmDirection direction,
1099 uint16_t msgType) {
1100 xfrm_userpolicy_info userpolicy{};
1101 nlattr_user_tmpl usertmpl{};
Di Lu2ccb3e52018-01-03 16:19:20 -08001102 nlattr_xfrm_mark xfrmmark{};
ludi771b8002017-11-20 15:09:05 -08001103
1104 enum {
1105 NLMSG_HDR,
1106 USERPOLICY,
1107 USERPOLICY_PAD,
1108 USERTMPL,
1109 USERTMPL_PAD,
Di Lu2ccb3e52018-01-03 16:19:20 -08001110 MARK,
1111 MARK_PAD,
ludi771b8002017-11-20 15:09:05 -08001112 };
1113
1114 std::vector<iovec> iov = {
Yi Kongbdfd57e2018-07-25 13:26:10 -07001115 {nullptr, 0}, // reserved for the eventual addition of a NLMSG_HDR
ludi771b8002017-11-20 15:09:05 -08001116 {&userpolicy, 0}, // main xfrm_userpolicy_info struct
1117 {kPadBytes, 0}, // up to NLMSG_ALIGNTO pad bytes of padding
1118 {&usertmpl, 0}, // adjust size if xfrm_user_tmpl struct is present
1119 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
Di Lu2ccb3e52018-01-03 16:19:20 -08001120 {&xfrmmark, 0}, // adjust size if xfrm mark is present
1121 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
ludi771b8002017-11-20 15:09:05 -08001122 };
1123
1124 int len;
Benedict Wonga04ffa72018-05-09 21:42:42 -07001125 len = iov[USERPOLICY].iov_len = fillUserSpInfo(record, direction, &userpolicy);
ludi771b8002017-11-20 15:09:05 -08001126 iov[USERPOLICY_PAD].iov_len = NLMSG_ALIGN(len) - len;
1127
1128 len = iov[USERTMPL].iov_len = fillNlAttrUserTemplate(record, &usertmpl);
1129 iov[USERTMPL_PAD].iov_len = NLA_ALIGN(len) - len;
1130
Di Lu2ccb3e52018-01-03 16:19:20 -08001131 len = iov[MARK].iov_len = fillNlAttrXfrmMark(record, &xfrmmark);
1132 iov[MARK_PAD].iov_len = NLA_ALIGN(len) - len;
1133
ludi771b8002017-11-20 15:09:05 -08001134 return sock.sendMessage(msgType, NETLINK_REQUEST_FLAGS, 0, &iov);
1135}
1136
Benedict Wonga04ffa72018-05-09 21:42:42 -07001137netdutils::Status XfrmController::deleteTunnelModeSecurityPolicy(const XfrmSpInfo& record,
ludi771b8002017-11-20 15:09:05 -08001138 const XfrmSocket& sock,
1139 XfrmDirection direction) {
1140 xfrm_userpolicy_id policyid{};
Di Lu2ccb3e52018-01-03 16:19:20 -08001141 nlattr_xfrm_mark xfrmmark{};
ludi771b8002017-11-20 15:09:05 -08001142
1143 enum {
1144 NLMSG_HDR,
1145 USERPOLICYID,
1146 USERPOLICYID_PAD,
Di Lu2ccb3e52018-01-03 16:19:20 -08001147 MARK,
1148 MARK_PAD,
ludi771b8002017-11-20 15:09:05 -08001149 };
1150
1151 std::vector<iovec> iov = {
Yi Kongbdfd57e2018-07-25 13:26:10 -07001152 {nullptr, 0}, // reserved for the eventual addition of a NLMSG_HDR
ludi771b8002017-11-20 15:09:05 -08001153 {&policyid, 0}, // main xfrm_userpolicy_id struct
1154 {kPadBytes, 0}, // up to NLMSG_ALIGNTO pad bytes of padding
manojboopathi8707f232018-01-02 14:45:47 -08001155 {&xfrmmark, 0}, // adjust size if xfrm mark is present
1156 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
ludi771b8002017-11-20 15:09:05 -08001157 };
1158
1159 int len = iov[USERPOLICYID].iov_len = fillUserPolicyId(record, direction, &policyid);
1160 iov[USERPOLICYID_PAD].iov_len = NLMSG_ALIGN(len) - len;
1161
Di Lu2ccb3e52018-01-03 16:19:20 -08001162 len = iov[MARK].iov_len = fillNlAttrXfrmMark(record, &xfrmmark);
1163 iov[MARK_PAD].iov_len = NLA_ALIGN(len) - len;
1164
ludi771b8002017-11-20 15:09:05 -08001165 return sock.sendMessage(XFRM_MSG_DELPOLICY, NETLINK_REQUEST_FLAGS, 0, &iov);
1166}
1167
Benedict Wonga04ffa72018-05-09 21:42:42 -07001168int XfrmController::fillUserSpInfo(const XfrmSpInfo& record, XfrmDirection direction,
1169 xfrm_userpolicy_info* usersp) {
1170 fillXfrmSelector(record.selAddrFamily, &usersp->sel);
Nathan Harold1a371532017-01-30 12:30:48 -08001171 fillXfrmLifetimeDefaults(&usersp->lft);
1172 fillXfrmCurLifetimeDefaults(&usersp->curlft);
Nathan Harold420ceac2017-04-05 19:36:59 -07001173 /* if (index) index & 0x3 == dir -- must be true
1174 * xfrm_user.c:verify_newpolicy_info() */
Nathan Harold1a371532017-01-30 12:30:48 -08001175 usersp->index = 0;
Nathan Haroldda54f122018-01-09 16:42:57 -08001176 usersp->dir = static_cast<uint8_t>(direction);
Nathan Harold1a371532017-01-30 12:30:48 -08001177 usersp->action = XFRM_POLICY_ALLOW;
1178 usersp->flags = XFRM_POLICY_LOCALOK;
1179 usersp->share = XFRM_SHARE_UNIQUE;
1180 return sizeof(*usersp);
1181}
1182
Benedict Wonga04ffa72018-05-09 21:42:42 -07001183int XfrmController::fillUserTemplate(const XfrmSpInfo& record, xfrm_user_tmpl* tmpl) {
Nathan Harold1a371532017-01-30 12:30:48 -08001184 tmpl->id.daddr = record.dstAddr;
1185 tmpl->id.spi = record.spi;
1186 tmpl->id.proto = IPPROTO_ESP;
1187
1188 tmpl->family = record.addrFamily;
1189 tmpl->saddr = record.srcAddr;
1190 tmpl->reqid = record.transformId;
1191 tmpl->mode = static_cast<uint8_t>(record.mode);
1192 tmpl->share = XFRM_SHARE_UNIQUE;
1193 tmpl->optional = 0; // if this is true, then a failed state lookup will be considered OK:
1194 // http://lxr.free-electrons.com/source/net/xfrm/xfrm_policy.c#L1492
1195 tmpl->aalgos = ALGO_MASK_AUTH_ALL; // TODO: if there's a bitmask somewhere of
1196 // algos, we should find it and apply it.
1197 // I can't find one.
1198 tmpl->ealgos = ALGO_MASK_CRYPT_ALL; // TODO: if there's a bitmask somewhere...
ludi771b8002017-11-20 15:09:05 -08001199 return sizeof(xfrm_user_tmpl*);
Nathan Harold1a371532017-01-30 12:30:48 -08001200}
1201
Benedict Wonga04ffa72018-05-09 21:42:42 -07001202int XfrmController::fillNlAttrUserTemplate(const XfrmSpInfo& record, nlattr_user_tmpl* tmpl) {
ludi771b8002017-11-20 15:09:05 -08001203 fillUserTemplate(record, &tmpl->tmpl);
1204
1205 int len = NLA_HDRLEN + sizeof(xfrm_user_tmpl);
1206 fillXfrmNlaHdr(&tmpl->hdr, XFRMA_TMPL, len);
1207 return len;
1208}
1209
Benedict Wonga04ffa72018-05-09 21:42:42 -07001210int XfrmController::fillNlAttrXfrmMark(const XfrmCommonInfo& record, nlattr_xfrm_mark* mark) {
Di Lu2ccb3e52018-01-03 16:19:20 -08001211 mark->mark.v = record.mark.v; // set to 0 if it's not used
1212 mark->mark.m = record.mark.m; // set to 0 if it's not used
1213 int len = NLA_HDRLEN + sizeof(xfrm_mark);
1214 fillXfrmNlaHdr(&mark->hdr, XFRMA_MARK, len);
1215 return len;
1216}
1217
Benedict Wongd8b6a382018-09-18 17:16:10 -07001218// This function sets the output mark (or set-mark in newer kernels) to that of the underlying
1219// Network's netid. This allows outbound IPsec Tunnel mode packets to be correctly directed to a
1220// preselected underlying Network. Packet as marked as protected from VPNs and have a network
1221// explicitly selected to prevent interference or routing loops. Also set permission flag to
1222// PERMISSION_SYSTEM to ensure we can use background/restricted networks.
1223int XfrmController::fillNlAttrXfrmOutputMark(const __u32 underlyingNetId,
manojboopathi8707f232018-01-02 14:45:47 -08001224 nlattr_xfrm_output_mark* output_mark) {
Benedict Wong96abf482018-01-22 13:56:41 -08001225 // Do not set if we were not given an output mark
Benedict Wongd8b6a382018-09-18 17:16:10 -07001226 if (underlyingNetId == 0) {
Benedict Wong96abf482018-01-22 13:56:41 -08001227 return 0;
1228 }
1229
Benedict Wongd8b6a382018-09-18 17:16:10 -07001230 Fwmark fwmark;
1231 fwmark.netId = underlyingNetId;
1232
1233 // TODO: Rework this to more accurately follow the underlying network
1234 fwmark.permission = PERMISSION_SYSTEM;
1235 fwmark.explicitlySelected = true;
1236 fwmark.protectedFromVpn = true;
1237 output_mark->outputMark = fwmark.intValue;
1238
Benedict Wong96abf482018-01-22 13:56:41 -08001239 int len = NLA_HDRLEN + sizeof(__u32);
1240 fillXfrmNlaHdr(&output_mark->hdr, XFRMA_OUTPUT_MARK, len);
1241 return len;
1242}
1243
Benedict Wonga04ffa72018-05-09 21:42:42 -07001244int XfrmController::fillUserPolicyId(const XfrmSpInfo& record, XfrmDirection direction,
ludi771b8002017-11-20 15:09:05 -08001245 xfrm_userpolicy_id* usersp) {
1246 // For DELPOLICY, when index is absent, selector is needed to match the policy
Benedict Wonga04ffa72018-05-09 21:42:42 -07001247 fillXfrmSelector(record.selAddrFamily, &usersp->sel);
ludi771b8002017-11-20 15:09:05 -08001248 usersp->dir = static_cast<uint8_t>(direction);
1249 return sizeof(*usersp);
1250}
1251
manojboopathi8707f232018-01-02 14:45:47 -08001252int XfrmController::addVirtualTunnelInterface(const std::string& deviceName,
1253 const std::string& localAddress,
1254 const std::string& remoteAddress, int32_t ikey,
1255 int32_t okey, bool isUpdate) {
1256 ALOGD("XfrmController::%s, line=%d", __FUNCTION__, __LINE__);
1257 ALOGD("deviceName=%s", deviceName.c_str());
1258 ALOGD("localAddress=%s", localAddress.c_str());
1259 ALOGD("remoteAddress=%s", remoteAddress.c_str());
1260 ALOGD("ikey=%0.8x", ikey);
1261 ALOGD("okey=%0.8x", okey);
1262 ALOGD("isUpdate=%d", isUpdate);
1263
1264 if (deviceName.empty() || localAddress.empty() || remoteAddress.empty()) {
1265 return EINVAL;
1266 }
1267
1268 const char* INFO_KIND_VTI6 = "vti6";
1269 const char* INFO_KIND_VTI = "vti";
1270 uint8_t PADDING_BUFFER[] = {0, 0, 0, 0};
1271
1272 // Find address family.
1273 uint8_t remAddr[sizeof(in6_addr)];
1274
1275 StatusOr<uint16_t> statusOrRemoteFam = convertStringAddress(remoteAddress, remAddr);
1276 if (!isOk(statusOrRemoteFam)) {
1277 return statusOrRemoteFam.status().code();
1278 }
1279
1280 uint8_t locAddr[sizeof(in6_addr)];
1281 StatusOr<uint16_t> statusOrLocalFam = convertStringAddress(localAddress, locAddr);
1282 if (!isOk(statusOrLocalFam)) {
1283 return statusOrLocalFam.status().code();
1284 }
1285
1286 if (statusOrLocalFam.value() != statusOrRemoteFam.value()) {
1287 return EINVAL;
1288 }
1289
1290 uint16_t family = statusOrLocalFam.value();
1291
1292 ifinfomsg ifInfoMsg{};
1293
1294 // Construct IFLA_IFNAME
1295 nlattr iflaIfName;
1296 char iflaIfNameStrValue[deviceName.length() + 1];
1297 size_t iflaIfNameLength =
1298 strlcpy(iflaIfNameStrValue, deviceName.c_str(), sizeof(iflaIfNameStrValue));
1299 size_t iflaIfNamePad = fillNlAttr(IFLA_IFNAME, iflaIfNameLength, &iflaIfName);
1300
1301 // Construct IFLA_INFO_KIND
1302 // Constants "vti6" and "vti" enable the kernel to call different code paths,
1303 // (ip_tunnel.c, ip6_tunnel), based on the family.
1304 const std::string infoKindValue = (family == AF_INET6) ? INFO_KIND_VTI6 : INFO_KIND_VTI;
1305 nlattr iflaIfInfoKind;
1306 char infoKindValueStrValue[infoKindValue.length() + 1];
1307 size_t iflaIfInfoKindLength =
1308 strlcpy(infoKindValueStrValue, infoKindValue.c_str(), sizeof(infoKindValueStrValue));
1309 size_t iflaIfInfoKindPad = fillNlAttr(IFLA_INFO_KIND, iflaIfInfoKindLength, &iflaIfInfoKind);
1310
1311 // Construct IFLA_VTI_LOCAL
1312 nlattr iflaVtiLocal;
1313 uint8_t binaryLocalAddress[sizeof(in6_addr)];
1314 size_t iflaVtiLocalPad =
1315 fillNlAttrIpAddress(IFLA_VTI_LOCAL, family, localAddress, &iflaVtiLocal,
1316 netdutils::makeSlice(binaryLocalAddress));
1317
1318 // Construct IFLA_VTI_REMOTE
1319 nlattr iflaVtiRemote;
1320 uint8_t binaryRemoteAddress[sizeof(in6_addr)];
1321 size_t iflaVtiRemotePad =
1322 fillNlAttrIpAddress(IFLA_VTI_REMOTE, family, remoteAddress, &iflaVtiRemote,
1323 netdutils::makeSlice(binaryRemoteAddress));
1324
1325 // Construct IFLA_VTI_OKEY
1326 nlattr iflaVtiIKey;
1327 uint32_t iKeyValue;
1328 size_t iflaVtiIKeyPad = fillNlAttrU32(IFLA_VTI_IKEY, ikey, &iflaVtiIKey, &iKeyValue);
1329
1330 // Construct IFLA_VTI_IKEY
1331 nlattr iflaVtiOKey;
1332 uint32_t oKeyValue;
1333 size_t iflaVtiOKeyPad = fillNlAttrU32(IFLA_VTI_OKEY, okey, &iflaVtiOKey, &oKeyValue);
1334
1335 int iflaInfoDataPayloadLength = iflaVtiLocal.nla_len + iflaVtiLocalPad + iflaVtiRemote.nla_len +
1336 iflaVtiRemotePad + iflaVtiIKey.nla_len + iflaVtiIKeyPad +
1337 iflaVtiOKey.nla_len + iflaVtiOKeyPad;
1338
1339 // Construct IFLA_INFO_DATA
1340 nlattr iflaInfoData;
1341 size_t iflaInfoDataPad = fillNlAttr(IFLA_INFO_DATA, iflaInfoDataPayloadLength, &iflaInfoData);
1342
1343 // Construct IFLA_LINKINFO
1344 nlattr iflaLinkInfo;
1345 size_t iflaLinkInfoPad = fillNlAttr(IFLA_LINKINFO,
1346 iflaInfoData.nla_len + iflaInfoDataPad +
1347 iflaIfInfoKind.nla_len + iflaIfInfoKindPad,
1348 &iflaLinkInfo);
1349
1350 iovec iov[] = {
Yi Kongbdfd57e2018-07-25 13:26:10 -07001351 {nullptr, 0},
manojboopathi8707f232018-01-02 14:45:47 -08001352 {&ifInfoMsg, sizeof(ifInfoMsg)},
1353
1354 {&iflaIfName, sizeof(iflaIfName)},
1355 {iflaIfNameStrValue, iflaIfNameLength},
1356 {&PADDING_BUFFER, iflaIfNamePad},
1357
1358 {&iflaLinkInfo, sizeof(iflaLinkInfo)},
1359
1360 {&iflaIfInfoKind, sizeof(iflaIfInfoKind)},
1361 {infoKindValueStrValue, iflaIfInfoKindLength},
1362 {&PADDING_BUFFER, iflaIfInfoKindPad},
1363
1364 {&iflaInfoData, sizeof(iflaInfoData)},
1365
1366 {&iflaVtiLocal, sizeof(iflaVtiLocal)},
1367 {&binaryLocalAddress, (family == AF_INET) ? sizeof(in_addr) : sizeof(in6_addr)},
1368 {&PADDING_BUFFER, iflaVtiLocalPad},
1369
1370 {&iflaVtiRemote, sizeof(iflaVtiRemote)},
1371 {&binaryRemoteAddress, (family == AF_INET) ? sizeof(in_addr) : sizeof(in6_addr)},
1372 {&PADDING_BUFFER, iflaVtiRemotePad},
1373
1374 {&iflaVtiIKey, sizeof(iflaVtiIKey)},
1375 {&iKeyValue, sizeof(iKeyValue)},
1376 {&PADDING_BUFFER, iflaVtiIKeyPad},
1377
1378 {&iflaVtiOKey, sizeof(iflaVtiOKey)},
1379 {&oKeyValue, sizeof(oKeyValue)},
1380 {&PADDING_BUFFER, iflaVtiOKeyPad},
1381
1382 {&PADDING_BUFFER, iflaInfoDataPad},
1383
1384 {&PADDING_BUFFER, iflaLinkInfoPad},
1385 };
1386
1387 uint16_t action = RTM_NEWLINK;
1388 uint16_t flags = NLM_F_REQUEST | NLM_F_ACK;
1389
1390 if (!isUpdate) {
1391 flags |= NLM_F_EXCL | NLM_F_CREATE;
1392 }
1393
Nathan Harold5be66022018-05-10 14:15:36 -07001394 // sendNetlinkRequest returns -errno
1395 int ret = -1 * sendNetlinkRequest(action, flags, iov, ARRAY_SIZE(iov), nullptr);
manojboopathi8707f232018-01-02 14:45:47 -08001396 if (ret) {
1397 ALOGE("Error in %s virtual tunnel interface. Error Code: %d",
1398 isUpdate ? "updating" : "adding", ret);
1399 }
1400 return ret;
1401}
1402
1403int XfrmController::removeVirtualTunnelInterface(const std::string& deviceName) {
1404 ALOGD("XfrmController::%s, line=%d", __FUNCTION__, __LINE__);
1405 ALOGD("deviceName=%s", deviceName.c_str());
1406
1407 if (deviceName.empty()) {
1408 return EINVAL;
1409 }
1410
1411 uint8_t PADDING_BUFFER[] = {0, 0, 0, 0};
1412
1413 ifinfomsg ifInfoMsg{};
1414 nlattr iflaIfName;
1415 char iflaIfNameStrValue[deviceName.length() + 1];
1416 size_t iflaIfNameLength =
1417 strlcpy(iflaIfNameStrValue, deviceName.c_str(), sizeof(iflaIfNameStrValue));
1418 size_t iflaIfNamePad = fillNlAttr(IFLA_IFNAME, iflaIfNameLength, &iflaIfName);
1419
1420 iovec iov[] = {
Yi Kongbdfd57e2018-07-25 13:26:10 -07001421 {nullptr, 0},
manojboopathi8707f232018-01-02 14:45:47 -08001422 {&ifInfoMsg, sizeof(ifInfoMsg)},
1423
1424 {&iflaIfName, sizeof(iflaIfName)},
1425 {iflaIfNameStrValue, iflaIfNameLength},
1426 {&PADDING_BUFFER, iflaIfNamePad},
1427 };
1428
1429 uint16_t action = RTM_DELLINK;
1430 uint16_t flags = NLM_F_REQUEST | NLM_F_ACK;
1431
Nathan Harold5be66022018-05-10 14:15:36 -07001432 // sendNetlinkRequest returns -errno
1433 int ret = -1 * sendNetlinkRequest(action, flags, iov, ARRAY_SIZE(iov), nullptr);
manojboopathi8707f232018-01-02 14:45:47 -08001434 if (ret) {
1435 ALOGE("Error in removing virtual tunnel interface %s. Error Code: %d", iflaIfNameStrValue,
1436 ret);
1437 }
1438 return ret;
1439}
ludi771b8002017-11-20 15:09:05 -08001440
Nathan Harold1a371532017-01-30 12:30:48 -08001441} // namespace net
1442} // namespace android