1 /*
2  *
3  * Copyright (C) 2017 The Android Open Source Project
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17 
18 #include <random>
19 #include <string>
20 #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>
29 
30 #define __STDC_FORMAT_MACROS
31 #include <inttypes.h>
32 
33 #include <arpa/inet.h>
34 #include <net/if.h>
35 #include <netinet/in.h>
36 
37 #include <sys/socket.h>
38 #include <sys/stat.h>
39 #include <sys/types.h>
40 #include <sys/wait.h>
41 
42 #include <linux/in.h>
43 #include <linux/ipsec.h>
44 #include <linux/netlink.h>
45 #include <linux/xfrm.h>
46 
47 #define LOG_TAG "XfrmController"
48 #include <android-base/properties.h>
49 #include <android-base/stringprintf.h>
50 #include <android-base/strings.h>
51 #include <android-base/unique_fd.h>
52 #include <android/net/INetd.h>
53 #include <cutils/properties.h>
54 #include <log/log.h>
55 #include <log/log_properties.h>
56 #include "Fwmark.h"
57 #include "InterfaceController.h"
58 #include "NetdConstants.h"
59 #include "NetlinkCommands.h"
60 #include "Permission.h"
61 #include "XfrmController.h"
62 #include "android-base/stringprintf.h"
63 #include "android-base/strings.h"
64 #include "android-base/unique_fd.h"
65 #include "netdutils/DumpWriter.h"
66 #include "netdutils/Fd.h"
67 #include "netdutils/Slice.h"
68 #include "netdutils/Syscalls.h"
69 
70 using android::net::INetd;
71 using android::netdutils::DumpWriter;
72 using android::netdutils::Fd;
73 using android::netdutils::ScopedIndent;
74 using android::netdutils::Slice;
75 using android::netdutils::Status;
76 using android::netdutils::StatusOr;
77 using android::netdutils::Syscalls;
78 
79 namespace android {
80 namespace net {
81 
82 // Exposed for testing
83 constexpr uint32_t ALGO_MASK_AUTH_ALL = ~0;
84 // Exposed for testing
85 constexpr uint32_t ALGO_MASK_CRYPT_ALL = ~0;
86 // Exposed for testing
87 constexpr uint32_t ALGO_MASK_AEAD_ALL = ~0;
88 // Exposed for testing
89 constexpr uint8_t REPLAY_WINDOW_SIZE = 32;
90 
91 namespace {
92 
93 constexpr uint32_t RAND_SPI_MIN = 256;
94 constexpr uint32_t RAND_SPI_MAX = 0xFFFFFFFE;
95 
96 constexpr uint32_t INVALID_SPI = 0;
97 constexpr const char* INFO_KIND_VTI = "vti";
98 constexpr const char* INFO_KIND_VTI6 = "vti6";
99 constexpr const char* INFO_KIND_XFRMI = "xfrm";
100 constexpr int INFO_KIND_MAX_LEN = 8;
101 constexpr int LOOPBACK_IFINDEX = 1;
102 
103 bool mIsXfrmIntfSupported = false;
104 
isEngBuild()105 static inline bool isEngBuild() {
106     static const std::string sBuildType = android::base::GetProperty("ro.build.type", "user");
107     return sBuildType == "eng";
108 }
109 
110 #define XFRM_MSG_TRANS(x)                                                                          \
111     case x:                                                                                        \
112         return #x;
113 
xfrmMsgTypeToString(uint16_t msg)114 const char* xfrmMsgTypeToString(uint16_t msg) {
115     switch (msg) {
116         XFRM_MSG_TRANS(XFRM_MSG_NEWSA)
117         XFRM_MSG_TRANS(XFRM_MSG_DELSA)
118         XFRM_MSG_TRANS(XFRM_MSG_GETSA)
119         XFRM_MSG_TRANS(XFRM_MSG_NEWPOLICY)
120         XFRM_MSG_TRANS(XFRM_MSG_DELPOLICY)
121         XFRM_MSG_TRANS(XFRM_MSG_GETPOLICY)
122         XFRM_MSG_TRANS(XFRM_MSG_ALLOCSPI)
123         XFRM_MSG_TRANS(XFRM_MSG_ACQUIRE)
124         XFRM_MSG_TRANS(XFRM_MSG_EXPIRE)
125         XFRM_MSG_TRANS(XFRM_MSG_UPDPOLICY)
126         XFRM_MSG_TRANS(XFRM_MSG_UPDSA)
127         XFRM_MSG_TRANS(XFRM_MSG_POLEXPIRE)
128         XFRM_MSG_TRANS(XFRM_MSG_FLUSHSA)
129         XFRM_MSG_TRANS(XFRM_MSG_FLUSHPOLICY)
130         XFRM_MSG_TRANS(XFRM_MSG_NEWAE)
131         XFRM_MSG_TRANS(XFRM_MSG_GETAE)
132         XFRM_MSG_TRANS(XFRM_MSG_REPORT)
133         XFRM_MSG_TRANS(XFRM_MSG_MIGRATE)
134         XFRM_MSG_TRANS(XFRM_MSG_NEWSADINFO)
135         XFRM_MSG_TRANS(XFRM_MSG_GETSADINFO)
136         XFRM_MSG_TRANS(XFRM_MSG_GETSPDINFO)
137         XFRM_MSG_TRANS(XFRM_MSG_NEWSPDINFO)
138         XFRM_MSG_TRANS(XFRM_MSG_MAPPING)
139         default:
140             return "XFRM_MSG UNKNOWN";
141     }
142 }
143 
144 // actually const but cannot be declared as such for reasons
145 uint8_t kPadBytesArray[] = {0, 0, 0};
146 void* kPadBytes = static_cast<void*>(kPadBytesArray);
147 
148 #define LOG_HEX(__desc16__, __buf__, __len__)                                                      \
149     do {                                                                                           \
150         if (isEngBuild()) {                                                                        \
151             logHex(__desc16__, __buf__, __len__);                                                  \
152         }                                                                                          \
153     } while (0)
154 
155 #define LOG_IOV(__iov__)                                                                           \
156     do {                                                                                           \
157         if (isEngBuild()) {                                                                        \
158             logIov(__iov__);                                                                       \
159         }                                                                                          \
160     } while (0)
161 
logHex(const char * desc16,const char * buf,size_t len)162 void logHex(const char* desc16, const char* buf, size_t len) {
163     char* printBuf = new char[len * 2 + 1 + 26]; // len->ascii, +newline, +prefix strlen
164     int offset = 0;
165     if (desc16) {
166         sprintf(printBuf, "{%-16s}", desc16);
167         offset += 18; // prefix string length
168     }
169     sprintf(printBuf + offset, "[%4.4u]: ", (len > 9999) ? 9999 : (unsigned)len);
170     offset += 8;
171 
172     for (uint32_t j = 0; j < (uint32_t)len; j++) {
173         sprintf(&printBuf[j * 2 + offset], "%0.2x", (unsigned char)buf[j]);
174     }
175     ALOGD("%s", printBuf);
176     delete[] printBuf;
177 }
178 
logIov(const std::vector<iovec> & iov)179 void logIov(const std::vector<iovec>& iov) {
180     for (const iovec& row : iov) {
181         logHex(nullptr, reinterpret_cast<char*>(row.iov_base), row.iov_len);
182     }
183 }
184 
fillNlAttr(__u16 nlaType,size_t valueSize,nlattr * nlAttr)185 size_t fillNlAttr(__u16 nlaType, size_t valueSize, nlattr* nlAttr) {
186     size_t dataLen = valueSize;
187     int padLength = NLMSG_ALIGN(dataLen) - dataLen;
188     nlAttr->nla_len = (__u16)(dataLen + sizeof(nlattr));
189     nlAttr->nla_type = nlaType;
190     return padLength;
191 }
192 
fillNlAttrIpAddress(__u16 nlaType,int family,const std::string & value,nlattr * nlAttr,Slice ipAddress)193 size_t fillNlAttrIpAddress(__u16 nlaType, int family, const std::string& value, nlattr* nlAttr,
194                            Slice ipAddress) {
195     inet_pton(family, value.c_str(), ipAddress.base());
196     return fillNlAttr(nlaType, (family == AF_INET) ? sizeof(in_addr) : sizeof(in6_addr), nlAttr);
197 }
198 
fillNlAttrU32(__u16 nlaType,uint32_t value,XfrmController::nlattr_payload_u32 * nlAttr)199 size_t fillNlAttrU32(__u16 nlaType, uint32_t value, XfrmController::nlattr_payload_u32* nlAttr) {
200     nlAttr->value = value;
201     return fillNlAttr(nlaType, sizeof(value), &nlAttr->hdr);
202 }
203 
204 // returns the address family, placing the string in the provided buffer
convertStringAddress(const std::string & addr,uint8_t * buffer)205 StatusOr<uint16_t> convertStringAddress(const std::string& addr, uint8_t* buffer) {
206     if (inet_pton(AF_INET, addr.c_str(), buffer) == 1) {
207         return AF_INET;
208     } else if (inet_pton(AF_INET6, addr.c_str(), buffer) == 1) {
209         return AF_INET6;
210     } else {
211         return Status(EAFNOSUPPORT);
212     }
213 }
214 
215 // TODO: Need to consider a way to refer to the sSycalls instance
getSyscallInstance()216 inline Syscalls& getSyscallInstance() { return netdutils::sSyscalls.get(); }
217 
218 class XfrmSocketImpl : public XfrmSocket {
219 private:
220     static constexpr int NLMSG_DEFAULTSIZE = 8192;
221 
222     union NetlinkResponse {
223         nlmsghdr hdr;
224         struct _err_ {
225             nlmsghdr hdr;
226             nlmsgerr err;
227         } err;
228 
229         struct _buf_ {
230             nlmsghdr hdr;
231             char buf[NLMSG_DEFAULTSIZE];
232         } buf;
233     };
234 
235 public:
open()236     netdutils::Status open() override {
237         mSock = openNetlinkSocket(NETLINK_XFRM);
238         if (mSock < 0) {
239             ALOGW("Could not get a new socket, line=%d", __LINE__);
240             return netdutils::statusFromErrno(-mSock, "Could not open netlink socket");
241         }
242 
243         return netdutils::status::ok;
244     }
245 
validateResponse(NetlinkResponse response,size_t len)246     static netdutils::Status validateResponse(NetlinkResponse response, size_t len) {
247         if (len < sizeof(nlmsghdr)) {
248             ALOGW("Invalid response message received over netlink");
249             return netdutils::statusFromErrno(EBADMSG, "Invalid message");
250         }
251 
252         switch (response.hdr.nlmsg_type) {
253             case NLMSG_NOOP:
254             case NLMSG_DONE:
255                 return netdutils::status::ok;
256             case NLMSG_OVERRUN:
257                 ALOGD("Netlink request overran kernel buffer");
258                 return netdutils::statusFromErrno(EBADMSG, "Kernel buffer overrun");
259             case NLMSG_ERROR:
260                 if (len < sizeof(NetlinkResponse::_err_)) {
261                     ALOGD("Netlink message received malformed error response");
262                     return netdutils::statusFromErrno(EBADMSG, "Malformed error response");
263                 }
264                 return netdutils::statusFromErrno(
265                     -response.err.err.error,
266                     "Error netlink message"); // Netlink errors are negative errno.
267             case XFRM_MSG_NEWSA:
268                 break;
269         }
270 
271         if (response.hdr.nlmsg_type < XFRM_MSG_BASE /*== NLMSG_MIN_TYPE*/ ||
272             response.hdr.nlmsg_type > XFRM_MSG_MAX) {
273             ALOGD("Netlink message responded with an out-of-range message ID");
274             return netdutils::statusFromErrno(EBADMSG, "Invalid message ID");
275         }
276 
277         // TODO Add more message validation here
278         return netdutils::status::ok;
279     }
280 
sendMessage(uint16_t nlMsgType,uint16_t nlMsgFlags,uint16_t nlMsgSeqNum,std::vector<iovec> * iovecs) const281     netdutils::Status sendMessage(uint16_t nlMsgType, uint16_t nlMsgFlags, uint16_t nlMsgSeqNum,
282                                   std::vector<iovec>* iovecs) const override {
283         nlmsghdr nlMsg = {
284             .nlmsg_type = nlMsgType,
285             .nlmsg_flags = nlMsgFlags,
286             .nlmsg_seq = nlMsgSeqNum,
287         };
288 
289         (*iovecs)[0].iov_base = &nlMsg;
290         (*iovecs)[0].iov_len = NLMSG_HDRLEN;
291         for (const iovec& iov : *iovecs) {
292             nlMsg.nlmsg_len += iov.iov_len;
293         }
294 
295         ALOGD("Sending Netlink XFRM Message: %s", xfrmMsgTypeToString(nlMsgType));
296         LOG_IOV(*iovecs);
297 
298         StatusOr<size_t> writeResult = getSyscallInstance().writev(mSock, *iovecs);
299         if (!isOk(writeResult)) {
300             ALOGE("netlink socket writev failed (%s)", toString(writeResult).c_str());
301             return writeResult;
302         }
303 
304         if (nlMsg.nlmsg_len != writeResult.value()) {
305             ALOGE("Invalid netlink message length sent %d", static_cast<int>(writeResult.value()));
306             return netdutils::statusFromErrno(EBADMSG, "Invalid message length");
307         }
308 
309         NetlinkResponse response = {};
310 
311         StatusOr<Slice> readResult =
312             getSyscallInstance().read(Fd(mSock), netdutils::makeSlice(response));
313         if (!isOk(readResult)) {
314             ALOGE("netlink response error (%s)", toString(readResult).c_str());
315             return readResult;
316         }
317 
318         LOG_HEX("netlink msg resp", reinterpret_cast<char*>(readResult.value().base()),
319                 readResult.value().size());
320 
321         Status validateStatus = validateResponse(response, readResult.value().size());
322         if (!isOk(validateStatus)) {
323             ALOGE("netlink response contains error (%s)", toString(validateStatus).c_str());
324         }
325 
326         return validateStatus;
327     }
328 };
329 
convertToXfrmAddr(const std::string & strAddr,xfrm_address_t * xfrmAddr)330 StatusOr<int> convertToXfrmAddr(const std::string& strAddr, xfrm_address_t* xfrmAddr) {
331     if (strAddr.length() == 0) {
332         memset(xfrmAddr, 0, sizeof(*xfrmAddr));
333         return AF_UNSPEC;
334     }
335 
336     if (inet_pton(AF_INET6, strAddr.c_str(), reinterpret_cast<void*>(xfrmAddr))) {
337         return AF_INET6;
338     } else if (inet_pton(AF_INET, strAddr.c_str(), reinterpret_cast<void*>(xfrmAddr))) {
339         return AF_INET;
340     } else {
341         return netdutils::statusFromErrno(EAFNOSUPPORT, "Invalid address family");
342     }
343 }
344 
fillXfrmNlaHdr(nlattr * hdr,uint16_t type,uint16_t len)345 void fillXfrmNlaHdr(nlattr* hdr, uint16_t type, uint16_t len) {
346     hdr->nla_type = type;
347     hdr->nla_len = len;
348 }
349 
fillXfrmCurLifetimeDefaults(xfrm_lifetime_cur * cur)350 void fillXfrmCurLifetimeDefaults(xfrm_lifetime_cur* cur) {
351     memset(reinterpret_cast<char*>(cur), 0, sizeof(*cur));
352 }
fillXfrmLifetimeDefaults(xfrm_lifetime_cfg * cfg)353 void fillXfrmLifetimeDefaults(xfrm_lifetime_cfg* cfg) {
354     cfg->soft_byte_limit = XFRM_INF;
355     cfg->hard_byte_limit = XFRM_INF;
356     cfg->soft_packet_limit = XFRM_INF;
357     cfg->hard_packet_limit = XFRM_INF;
358 }
359 
360 /*
361  * Allocate SPIs within an (inclusive) range of min-max.
362  * returns 0 (INVALID_SPI) once the entire range has been parsed.
363  */
364 class RandomSpi {
365 public:
RandomSpi(int min,int max)366     RandomSpi(int min, int max) : mMin(min) {
367         // Re-seeding should be safe because the seed itself is
368         // sufficiently random and we don't need secure random
369         std::mt19937 rnd = std::mt19937(std::random_device()());
370         mNext = std::uniform_int_distribution<>(1, INT_MAX)(rnd);
371         mSize = max - min + 1;
372         mCount = mSize;
373     }
374 
next()375     uint32_t next() {
376         if (!mCount)
377             return 0;
378         mCount--;
379         return (mNext++ % mSize) + mMin;
380     }
381 
382 private:
383     uint32_t mNext;
384     uint32_t mSize;
385     uint32_t mMin;
386     uint32_t mCount;
387 };
388 
389 } // namespace
390 
391 //
392 // Begin XfrmController Impl
393 //
394 //
XfrmController(void)395 XfrmController::XfrmController(void) {}
396 
397 // Test-only constructor allowing override of XFRM Interface support checks
XfrmController(bool xfrmIntfSupport)398 XfrmController::XfrmController(bool xfrmIntfSupport) {
399     mIsXfrmIntfSupported = xfrmIntfSupport;
400 }
401 
Init()402 netdutils::Status XfrmController::Init() {
403     RETURN_IF_NOT_OK(flushInterfaces());
404     mIsXfrmIntfSupported = isXfrmIntfSupported();
405 
406     XfrmSocketImpl sock;
407     RETURN_IF_NOT_OK(sock.open());
408     RETURN_IF_NOT_OK(flushSaDb(sock));
409     return flushPolicyDb(sock);
410 }
411 
flushInterfaces()412 netdutils::Status XfrmController::flushInterfaces() {
413     const auto& ifaces = InterfaceController::getIfaceNames();
414     RETURN_IF_NOT_OK(ifaces);
415     const String8 ifPrefix8 = String8(INetd::IPSEC_INTERFACE_PREFIX().string());
416 
417     for (const std::string& iface : ifaces.value()) {
418         netdutils::Status status;
419         // Look for the reserved interface prefix, which must be in the name at position 0
420         if (android::base::StartsWith(iface.c_str(), ifPrefix8.c_str())) {
421             RETURN_IF_NOT_OK(ipSecRemoveTunnelInterface(iface));
422         }
423     }
424     return netdutils::status::ok;
425 }
426 
flushSaDb(const XfrmSocket & s)427 netdutils::Status XfrmController::flushSaDb(const XfrmSocket& s) {
428     struct xfrm_usersa_flush flushUserSa = {.proto = IPSEC_PROTO_ANY};
429 
430     std::vector<iovec> iov = {{nullptr, 0}, // reserved for the eventual addition of a NLMSG_HDR
431                               {&flushUserSa, sizeof(flushUserSa)}, // xfrm_usersa_flush structure
432                               {kPadBytes, NLMSG_ALIGN(sizeof(flushUserSa)) - sizeof(flushUserSa)}};
433 
434     return s.sendMessage(XFRM_MSG_FLUSHSA, NETLINK_REQUEST_FLAGS, 0, &iov);
435 }
436 
flushPolicyDb(const XfrmSocket & s)437 netdutils::Status XfrmController::flushPolicyDb(const XfrmSocket& s) {
438     std::vector<iovec> iov = {{nullptr, 0}}; // reserved for the eventual addition of a NLMSG_HDR
439     return s.sendMessage(XFRM_MSG_FLUSHPOLICY, NETLINK_REQUEST_FLAGS, 0, &iov);
440 }
441 
isXfrmIntfSupported()442 bool XfrmController::isXfrmIntfSupported() {
443     const char* IPSEC_TEST_INTF_NAME = "ipsec_test";
444     const int32_t XFRM_TEST_IF_ID = 0xFFFF;
445 
446     bool errored = false;
447     errored |=
448             ipSecAddXfrmInterface(IPSEC_TEST_INTF_NAME, XFRM_TEST_IF_ID, NETLINK_ROUTE_CREATE_FLAGS)
449                     .code();
450     errored |= ipSecRemoveTunnelInterface(IPSEC_TEST_INTF_NAME).code();
451     return !errored;
452 }
453 
ipSecSetEncapSocketOwner(int socketFd,int newUid,uid_t callerUid)454 netdutils::Status XfrmController::ipSecSetEncapSocketOwner(int socketFd, int newUid,
455                                                            uid_t callerUid) {
456     ALOGD("XfrmController:%s, line=%d", __FUNCTION__, __LINE__);
457 
458     const int fd = socketFd;
459     struct stat info;
460     if (fstat(fd, &info)) {
461         return netdutils::statusFromErrno(errno, "Failed to stat socket file descriptor");
462     }
463     if (info.st_uid != callerUid) {
464         return netdutils::statusFromErrno(EPERM, "fchown disabled for non-owner calls");
465     }
466     if (S_ISSOCK(info.st_mode) == 0) {
467         return netdutils::statusFromErrno(EINVAL, "File descriptor was not a socket");
468     }
469 
470     int optval;
471     socklen_t optlen = sizeof(optval);
472     netdutils::Status status =
473             getSyscallInstance().getsockopt(Fd(fd), IPPROTO_UDP, UDP_ENCAP, &optval, &optlen);
474     if (status != netdutils::status::ok) {
475         return status;
476     }
477     if (optval != UDP_ENCAP_ESPINUDP && optval != UDP_ENCAP_ESPINUDP_NON_IKE) {
478         return netdutils::statusFromErrno(EINVAL, "Socket did not have UDP-encap sockopt set");
479     }
480     if (fchown(fd, newUid, -1)) {
481         return netdutils::statusFromErrno(errno, "Failed to fchown socket file descriptor");
482     }
483 
484     return netdutils::status::ok;
485 }
486 
ipSecAllocateSpi(int32_t transformId,const std::string & sourceAddress,const std::string & destinationAddress,int32_t inSpi,int32_t * outSpi)487 netdutils::Status XfrmController::ipSecAllocateSpi(int32_t transformId,
488                                                    const std::string& sourceAddress,
489                                                    const std::string& destinationAddress,
490                                                    int32_t inSpi, int32_t* outSpi) {
491     ALOGD("XfrmController:%s, line=%d", __FUNCTION__, __LINE__);
492     ALOGD("transformId=%d", transformId);
493     ALOGD("sourceAddress=%s", sourceAddress.c_str());
494     ALOGD("destinationAddress=%s", destinationAddress.c_str());
495     ALOGD("inSpi=%0.8x", inSpi);
496 
497     XfrmSaInfo saInfo{};
498     netdutils::Status ret = fillXfrmCommonInfo(sourceAddress, destinationAddress, INVALID_SPI, 0, 0,
499                                                transformId, 0, &saInfo);
500     if (!isOk(ret)) {
501         return ret;
502     }
503 
504     XfrmSocketImpl sock;
505     netdutils::Status socketStatus = sock.open();
506     if (!isOk(socketStatus)) {
507         ALOGD("Sock open failed for XFRM, line=%d", __LINE__);
508         return socketStatus;
509     }
510 
511     int minSpi = RAND_SPI_MIN, maxSpi = RAND_SPI_MAX;
512 
513     if (inSpi)
514         minSpi = maxSpi = inSpi;
515 
516     ret = allocateSpi(saInfo, minSpi, maxSpi, reinterpret_cast<uint32_t*>(outSpi), sock);
517     if (!isOk(ret)) {
518         // TODO: May want to return a new Status with a modified status string
519         ALOGD("Failed to Allocate an SPI, line=%d", __LINE__);
520         *outSpi = INVALID_SPI;
521     }
522 
523     return ret;
524 }
525 
ipSecAddSecurityAssociation(int32_t transformId,int32_t mode,const std::string & sourceAddress,const std::string & destinationAddress,int32_t underlyingNetId,int32_t spi,int32_t markValue,int32_t markMask,const std::string & authAlgo,const std::vector<uint8_t> & authKey,int32_t authTruncBits,const std::string & cryptAlgo,const std::vector<uint8_t> & cryptKey,int32_t cryptTruncBits,const std::string & aeadAlgo,const std::vector<uint8_t> & aeadKey,int32_t aeadIcvBits,int32_t encapType,int32_t encapLocalPort,int32_t encapRemotePort,int32_t xfrmInterfaceId)526 netdutils::Status XfrmController::ipSecAddSecurityAssociation(
527         int32_t transformId, int32_t mode, const std::string& sourceAddress,
528         const std::string& destinationAddress, int32_t underlyingNetId, int32_t spi,
529         int32_t markValue, int32_t markMask, const std::string& authAlgo,
530         const std::vector<uint8_t>& authKey, int32_t authTruncBits, const std::string& cryptAlgo,
531         const std::vector<uint8_t>& cryptKey, int32_t cryptTruncBits, const std::string& aeadAlgo,
532         const std::vector<uint8_t>& aeadKey, int32_t aeadIcvBits, int32_t encapType,
533         int32_t encapLocalPort, int32_t encapRemotePort, int32_t xfrmInterfaceId) {
534     ALOGD("XfrmController::%s, line=%d", __FUNCTION__, __LINE__);
535     ALOGD("transformId=%d", transformId);
536     ALOGD("mode=%d", mode);
537     ALOGD("sourceAddress=%s", sourceAddress.c_str());
538     ALOGD("destinationAddress=%s", destinationAddress.c_str());
539     ALOGD("underlyingNetworkId=%d", underlyingNetId);
540     ALOGD("spi=%0.8x", spi);
541     ALOGD("markValue=%x", markValue);
542     ALOGD("markMask=%x", markMask);
543     ALOGD("authAlgo=%s", authAlgo.c_str());
544     ALOGD("authTruncBits=%d", authTruncBits);
545     ALOGD("cryptAlgo=%s", cryptAlgo.c_str());
546     ALOGD("cryptTruncBits=%d,", cryptTruncBits);
547     ALOGD("aeadAlgo=%s", aeadAlgo.c_str());
548     ALOGD("aeadIcvBits=%d,", aeadIcvBits);
549     ALOGD("encapType=%d", encapType);
550     ALOGD("encapLocalPort=%d", encapLocalPort);
551     ALOGD("encapRemotePort=%d", encapRemotePort);
552     ALOGD("xfrmInterfaceId=%d", xfrmInterfaceId);
553 
554     XfrmSaInfo saInfo{};
555     netdutils::Status ret = fillXfrmCommonInfo(sourceAddress, destinationAddress, spi, markValue,
556                                                markMask, transformId, xfrmInterfaceId, &saInfo);
557     if (!isOk(ret)) {
558         return ret;
559     }
560 
561     saInfo.auth = XfrmAlgo{
562         .name = authAlgo, .key = authKey, .truncLenBits = static_cast<uint16_t>(authTruncBits)};
563 
564     saInfo.crypt = XfrmAlgo{
565         .name = cryptAlgo, .key = cryptKey, .truncLenBits = static_cast<uint16_t>(cryptTruncBits)};
566 
567     saInfo.aead = XfrmAlgo{
568         .name = aeadAlgo, .key = aeadKey, .truncLenBits = static_cast<uint16_t>(aeadIcvBits)};
569 
570     switch (static_cast<XfrmMode>(mode)) {
571         case XfrmMode::TRANSPORT:
572         case XfrmMode::TUNNEL:
573             saInfo.mode = static_cast<XfrmMode>(mode);
574             break;
575         default:
576             return netdutils::statusFromErrno(EINVAL, "Invalid xfrm mode");
577     }
578 
579     XfrmSocketImpl sock;
580     netdutils::Status socketStatus = sock.open();
581     if (!isOk(socketStatus)) {
582         ALOGD("Sock open failed for XFRM, line=%d", __LINE__);
583         return socketStatus;
584     }
585 
586     switch (static_cast<XfrmEncapType>(encapType)) {
587         case XfrmEncapType::ESPINUDP:
588         case XfrmEncapType::ESPINUDP_NON_IKE:
589             if (saInfo.addrFamily != AF_INET) {
590                 return netdutils::statusFromErrno(EAFNOSUPPORT, "IPv6 encap not supported");
591             }
592             // The ports are not used on input SAs, so this is OK to be wrong when
593             // direction is ultimately input.
594             saInfo.encap.srcPort = encapLocalPort;
595             saInfo.encap.dstPort = encapRemotePort;
596             [[fallthrough]];
597         case XfrmEncapType::NONE:
598             saInfo.encap.type = static_cast<XfrmEncapType>(encapType);
599             break;
600         default:
601             return netdutils::statusFromErrno(EINVAL, "Invalid encap type");
602     }
603 
604     saInfo.netId = underlyingNetId;
605 
606     ret = updateSecurityAssociation(saInfo, sock);
607     if (!isOk(ret)) {
608         ALOGD("Failed updating a Security Association, line=%d", __LINE__);
609     }
610 
611     return ret;
612 }
613 
ipSecDeleteSecurityAssociation(int32_t transformId,const std::string & sourceAddress,const std::string & destinationAddress,int32_t spi,int32_t markValue,int32_t markMask,int32_t xfrmInterfaceId)614 netdutils::Status XfrmController::ipSecDeleteSecurityAssociation(
615         int32_t transformId, const std::string& sourceAddress,
616         const std::string& destinationAddress, int32_t spi, int32_t markValue, int32_t markMask,
617         int32_t xfrmInterfaceId) {
618     ALOGD("XfrmController:%s, line=%d", __FUNCTION__, __LINE__);
619     ALOGD("transformId=%d", transformId);
620     ALOGD("sourceAddress=%s", sourceAddress.c_str());
621     ALOGD("destinationAddress=%s", destinationAddress.c_str());
622     ALOGD("spi=%0.8x", spi);
623     ALOGD("markValue=%x", markValue);
624     ALOGD("markMask=%x", markMask);
625     ALOGD("xfrmInterfaceId=%d", xfrmInterfaceId);
626 
627     XfrmSaInfo saInfo{};
628     netdutils::Status ret = fillXfrmCommonInfo(sourceAddress, destinationAddress, spi, markValue,
629                                                markMask, transformId, xfrmInterfaceId, &saInfo);
630     if (!isOk(ret)) {
631         return ret;
632     }
633 
634     XfrmSocketImpl sock;
635     netdutils::Status socketStatus = sock.open();
636     if (!isOk(socketStatus)) {
637         ALOGD("Sock open failed for XFRM, line=%d", __LINE__);
638         return socketStatus;
639     }
640 
641     ret = deleteSecurityAssociation(saInfo, sock);
642     if (!isOk(ret)) {
643         ALOGD("Failed to delete Security Association, line=%d", __LINE__);
644     }
645 
646     return ret;
647 }
648 
fillXfrmCommonInfo(const std::string & sourceAddress,const std::string & destinationAddress,int32_t spi,int32_t markValue,int32_t markMask,int32_t transformId,int32_t xfrmInterfaceId,XfrmCommonInfo * info)649 netdutils::Status XfrmController::fillXfrmCommonInfo(const std::string& sourceAddress,
650                                                      const std::string& destinationAddress,
651                                                      int32_t spi, int32_t markValue,
652                                                      int32_t markMask, int32_t transformId,
653                                                      int32_t xfrmInterfaceId,
654                                                      XfrmCommonInfo* info) {
655     // Use the addresses to determine the address family and do validation
656     xfrm_address_t sourceXfrmAddr{}, destXfrmAddr{};
657     StatusOr<int> sourceFamily, destFamily;
658     sourceFamily = convertToXfrmAddr(sourceAddress, &sourceXfrmAddr);
659     destFamily = convertToXfrmAddr(destinationAddress, &destXfrmAddr);
660     if (!isOk(sourceFamily) || !isOk(destFamily)) {
661         return netdutils::statusFromErrno(EINVAL, "Invalid address " + sourceAddress + "/" +
662                                                       destinationAddress);
663     }
664 
665     if (destFamily.value() == AF_UNSPEC ||
666         (sourceFamily.value() != AF_UNSPEC && sourceFamily.value() != destFamily.value())) {
667         ALOGD("Invalid or Mismatched Address Families, %d != %d, line=%d", sourceFamily.value(),
668               destFamily.value(), __LINE__);
669         return netdutils::statusFromErrno(EINVAL, "Invalid or mismatched address families");
670     }
671 
672     info->addrFamily = destFamily.value();
673 
674     info->dstAddr = destXfrmAddr;
675     info->srcAddr = sourceXfrmAddr;
676 
677     return fillXfrmCommonInfo(spi, markValue, markMask, transformId, xfrmInterfaceId, info);
678 }
679 
fillXfrmCommonInfo(int32_t spi,int32_t markValue,int32_t markMask,int32_t transformId,int32_t xfrmInterfaceId,XfrmCommonInfo * info)680 netdutils::Status XfrmController::fillXfrmCommonInfo(int32_t spi, int32_t markValue,
681                                                      int32_t markMask, int32_t transformId,
682                                                      int32_t xfrmInterfaceId,
683                                                      XfrmCommonInfo* info) {
684     info->transformId = transformId;
685     info->spi = htonl(spi);
686 
687     if (mIsXfrmIntfSupported) {
688         info->xfrm_if_id = xfrmInterfaceId;
689     } else {
690         info->mark.v = markValue;
691         info->mark.m = markMask;
692     }
693 
694     return netdutils::status::ok;
695 }
696 
ipSecApplyTransportModeTransform(int socketFd,int32_t transformId,int32_t direction,const std::string & sourceAddress,const std::string & destinationAddress,int32_t spi)697 netdutils::Status XfrmController::ipSecApplyTransportModeTransform(
698         int socketFd, int32_t transformId, int32_t direction, const std::string& sourceAddress,
699         const std::string& destinationAddress, int32_t spi) {
700     ALOGD("XfrmController::%s, line=%d", __FUNCTION__, __LINE__);
701     ALOGD("transformId=%d", transformId);
702     ALOGD("direction=%d", direction);
703     ALOGD("sourceAddress=%s", sourceAddress.c_str());
704     ALOGD("destinationAddress=%s", destinationAddress.c_str());
705     ALOGD("spi=%0.8x", spi);
706 
707     StatusOr<sockaddr_storage> ret =
708             getSyscallInstance().getsockname<sockaddr_storage>(Fd(socketFd));
709     if (!isOk(ret)) {
710         ALOGE("Failed to get socket info in %s", __FUNCTION__);
711         return ret;
712     }
713     struct sockaddr_storage saddr = ret.value();
714 
715     XfrmSpInfo spInfo{};
716     netdutils::Status status = fillXfrmCommonInfo(sourceAddress, destinationAddress, spi, 0, 0,
717                                                   transformId, 0, &spInfo);
718     if (!isOk(status)) {
719         ALOGE("Couldn't build SA ID %s", __FUNCTION__);
720         return status;
721     }
722 
723     spInfo.selAddrFamily = spInfo.addrFamily;
724 
725     // Allow dual stack sockets. Dual stack sockets are guaranteed to never have an AF_INET source
726     // address; the source address would instead be an IPv4-mapped address. Thus, disallow AF_INET
727     // sockets with mismatched address families (All other cases are acceptable).
728     if (saddr.ss_family == AF_INET && spInfo.addrFamily != AF_INET) {
729         ALOGE("IPV4 socket address family(%d) should match IPV4 Transform "
730               "address family(%d)!",
731               saddr.ss_family, spInfo.addrFamily);
732         return netdutils::statusFromErrno(EINVAL, "Mismatched address family");
733     }
734 
735     struct {
736         xfrm_userpolicy_info info;
737         xfrm_user_tmpl tmpl;
738     } policy{};
739 
740     fillUserSpInfo(spInfo, static_cast<XfrmDirection>(direction), &policy.info);
741     fillUserTemplate(spInfo, &policy.tmpl);
742 
743     LOG_HEX("XfrmUserPolicy", reinterpret_cast<char*>(&policy), sizeof(policy));
744 
745     int sockOpt, sockLayer;
746     switch (saddr.ss_family) {
747         case AF_INET:
748             sockOpt = IP_XFRM_POLICY;
749             sockLayer = SOL_IP;
750             break;
751         case AF_INET6:
752             sockOpt = IPV6_XFRM_POLICY;
753             sockLayer = SOL_IPV6;
754             break;
755         default:
756             return netdutils::statusFromErrno(EAFNOSUPPORT, "Invalid address family");
757     }
758 
759     status = getSyscallInstance().setsockopt(Fd(socketFd), sockLayer, sockOpt, policy);
760     if (!isOk(status)) {
761         ALOGE("Error setting socket option for XFRM! (%s)", toString(status).c_str());
762     }
763 
764     return status;
765 }
766 
ipSecRemoveTransportModeTransform(int socketFd)767 netdutils::Status XfrmController::ipSecRemoveTransportModeTransform(int socketFd) {
768     ALOGD("XfrmController::%s, line=%d", __FUNCTION__, __LINE__);
769 
770     StatusOr<sockaddr_storage> ret =
771             getSyscallInstance().getsockname<sockaddr_storage>(Fd(socketFd));
772     if (!isOk(ret)) {
773         ALOGE("Failed to get socket info in %s! (%s)", __FUNCTION__, toString(ret).c_str());
774         return ret;
775     }
776 
777     int sockOpt, sockLayer;
778     switch (ret.value().ss_family) {
779         case AF_INET:
780             sockOpt = IP_XFRM_POLICY;
781             sockLayer = SOL_IP;
782             break;
783         case AF_INET6:
784             sockOpt = IPV6_XFRM_POLICY;
785             sockLayer = SOL_IPV6;
786             break;
787         default:
788             return netdutils::statusFromErrno(EAFNOSUPPORT, "Invalid address family");
789     }
790 
791     // Kernel will delete the security policy on this socket for both direction
792     // if optval is set to NULL and optlen is set to 0.
793     netdutils::Status status =
794             getSyscallInstance().setsockopt(Fd(socketFd), sockLayer, sockOpt, nullptr, 0);
795     if (!isOk(status)) {
796         ALOGE("Error removing socket option for XFRM! (%s)", toString(status).c_str());
797     }
798 
799     return status;
800 }
801 
ipSecAddSecurityPolicy(int32_t transformId,int32_t selAddrFamily,int32_t direction,const std::string & tmplSrcAddress,const std::string & tmplDstAddress,int32_t spi,int32_t markValue,int32_t markMask,int32_t xfrmInterfaceId)802 netdutils::Status XfrmController::ipSecAddSecurityPolicy(
803         int32_t transformId, int32_t selAddrFamily, int32_t direction,
804         const std::string& tmplSrcAddress, const std::string& tmplDstAddress, int32_t spi,
805         int32_t markValue, int32_t markMask, int32_t xfrmInterfaceId) {
806     return processSecurityPolicy(transformId, selAddrFamily, direction, tmplSrcAddress,
807                                  tmplDstAddress, spi, markValue, markMask, xfrmInterfaceId,
808                                  XFRM_MSG_NEWPOLICY);
809 }
810 
ipSecUpdateSecurityPolicy(int32_t transformId,int32_t selAddrFamily,int32_t direction,const std::string & tmplSrcAddress,const std::string & tmplDstAddress,int32_t spi,int32_t markValue,int32_t markMask,int32_t xfrmInterfaceId)811 netdutils::Status XfrmController::ipSecUpdateSecurityPolicy(
812         int32_t transformId, int32_t selAddrFamily, int32_t direction,
813         const std::string& tmplSrcAddress, const std::string& tmplDstAddress, int32_t spi,
814         int32_t markValue, int32_t markMask, int32_t xfrmInterfaceId) {
815     return processSecurityPolicy(transformId, selAddrFamily, direction, tmplSrcAddress,
816                                  tmplDstAddress, spi, markValue, markMask, xfrmInterfaceId,
817                                  XFRM_MSG_UPDPOLICY);
818 }
819 
ipSecDeleteSecurityPolicy(int32_t transformId,int32_t selAddrFamily,int32_t direction,int32_t markValue,int32_t markMask,int32_t xfrmInterfaceId)820 netdutils::Status XfrmController::ipSecDeleteSecurityPolicy(int32_t transformId,
821                                                             int32_t selAddrFamily,
822                                                             int32_t direction, int32_t markValue,
823                                                             int32_t markMask,
824                                                             int32_t xfrmInterfaceId) {
825     return processSecurityPolicy(transformId, selAddrFamily, direction, "", "", 0, markValue,
826                                  markMask, xfrmInterfaceId, XFRM_MSG_DELPOLICY);
827 }
828 
processSecurityPolicy(int32_t transformId,int32_t selAddrFamily,int32_t direction,const std::string & tmplSrcAddress,const std::string & tmplDstAddress,int32_t spi,int32_t markValue,int32_t markMask,int32_t xfrmInterfaceId,int32_t msgType)829 netdutils::Status XfrmController::processSecurityPolicy(
830         int32_t transformId, int32_t selAddrFamily, int32_t direction,
831         const std::string& tmplSrcAddress, const std::string& tmplDstAddress, int32_t spi,
832         int32_t markValue, int32_t markMask, int32_t xfrmInterfaceId, int32_t msgType) {
833     ALOGD("XfrmController::%s, line=%d", __FUNCTION__, __LINE__);
834     ALOGD("selAddrFamily=%s", selAddrFamily == AF_INET6 ? "AF_INET6" : "AF_INET");
835     ALOGD("transformId=%d", transformId);
836     ALOGD("direction=%d", direction);
837     ALOGD("tmplSrcAddress=%s", tmplSrcAddress.c_str());
838     ALOGD("tmplDstAddress=%s", tmplDstAddress.c_str());
839     ALOGD("spi=%0.8x", spi);
840     ALOGD("markValue=%d", markValue);
841     ALOGD("markMask=%d", markMask);
842     ALOGD("msgType=%d", msgType);
843     ALOGD("xfrmInterfaceId=%d", xfrmInterfaceId);
844 
845     XfrmSpInfo spInfo{};
846     spInfo.mode = XfrmMode::TUNNEL;
847 
848     XfrmSocketImpl sock;
849     RETURN_IF_NOT_OK(sock.open());
850 
851     // Set the correct address families. Tunnel mode policies use wildcard selectors, while
852     // templates have addresses set. These may be different address families. This method is called
853     // separately for IPv4 and IPv6 policies, and thus only need to map a single inner address
854     // family to the outer address families.
855     spInfo.selAddrFamily = selAddrFamily;
856 
857     if (msgType == XFRM_MSG_DELPOLICY) {
858         RETURN_IF_NOT_OK(fillXfrmCommonInfo(spi, markValue, markMask, transformId, xfrmInterfaceId,
859                                             &spInfo));
860 
861         return deleteTunnelModeSecurityPolicy(spInfo, sock, static_cast<XfrmDirection>(direction));
862     } else {
863         RETURN_IF_NOT_OK(fillXfrmCommonInfo(tmplSrcAddress, tmplDstAddress, spi, markValue,
864                                             markMask, transformId, xfrmInterfaceId, &spInfo));
865 
866         return updateTunnelModeSecurityPolicy(spInfo, sock, static_cast<XfrmDirection>(direction),
867                                               msgType);
868     }
869 }
870 
fillXfrmSelector(const int selAddrFamily,xfrm_selector * selector)871 void XfrmController::fillXfrmSelector(const int selAddrFamily, xfrm_selector* selector) {
872     selector->family = selAddrFamily;
873     selector->proto = AF_UNSPEC; // TODO: do we need to match the protocol? it's
874                                  // possible via the socket
875 }
876 
updateSecurityAssociation(const XfrmSaInfo & record,const XfrmSocket & sock)877 netdutils::Status XfrmController::updateSecurityAssociation(const XfrmSaInfo& record,
878                                                             const XfrmSocket& sock) {
879     xfrm_usersa_info usersa{};
880     nlattr_algo_crypt crypt{};
881     nlattr_algo_auth auth{};
882     nlattr_algo_aead aead{};
883     nlattr_xfrm_mark xfrmmark{};
884     nlattr_xfrm_output_mark xfrmoutputmark{};
885     nlattr_encap_tmpl encap{};
886     nlattr_xfrm_interface_id xfrm_if_id{};
887 
888     enum {
889         NLMSG_HDR,
890         USERSA,
891         USERSA_PAD,
892         CRYPT,
893         CRYPT_PAD,
894         AUTH,
895         AUTH_PAD,
896         AEAD,
897         AEAD_PAD,
898         MARK,
899         MARK_PAD,
900         OUTPUT_MARK,
901         OUTPUT_MARK_PAD,
902         ENCAP,
903         ENCAP_PAD,
904         INTF_ID,
905         INTF_ID_PAD,
906     };
907 
908     std::vector<iovec> iov = {
909             {nullptr, 0},          // reserved for the eventual addition of a NLMSG_HDR
910             {&usersa, 0},          // main usersa_info struct
911             {kPadBytes, 0},        // up to NLMSG_ALIGNTO pad bytes of padding
912             {&crypt, 0},           // adjust size if crypt algo is present
913             {kPadBytes, 0},        // up to NLATTR_ALIGNTO pad bytes
914             {&auth, 0},            // adjust size if auth algo is present
915             {kPadBytes, 0},        // up to NLATTR_ALIGNTO pad bytes
916             {&aead, 0},            // adjust size if aead algo is present
917             {kPadBytes, 0},        // up to NLATTR_ALIGNTO pad bytes
918             {&xfrmmark, 0},        // adjust size if xfrm mark is present
919             {kPadBytes, 0},        // up to NLATTR_ALIGNTO pad bytes
920             {&xfrmoutputmark, 0},  // adjust size if xfrm output mark is present
921             {kPadBytes, 0},        // up to NLATTR_ALIGNTO pad bytes
922             {&encap, 0},           // adjust size if encapsulating
923             {kPadBytes, 0},        // up to NLATTR_ALIGNTO pad bytes
924             {&xfrm_if_id, 0},      // adjust size if interface ID is present
925             {kPadBytes, 0},        // up to NLATTR_ALIGNTO pad bytes
926     };
927 
928     if (!record.aead.name.empty() && (!record.auth.name.empty() || !record.crypt.name.empty())) {
929         return netdutils::statusFromErrno(EINVAL, "Invalid xfrm algo selection; AEAD is mutually "
930                                                   "exclusive with both Authentication and "
931                                                   "Encryption");
932     }
933 
934     if (record.aead.key.size() > MAX_KEY_LENGTH || record.auth.key.size() > MAX_KEY_LENGTH ||
935         record.crypt.key.size() > MAX_KEY_LENGTH) {
936         return netdutils::statusFromErrno(EINVAL, "Key length invalid; exceeds MAX_KEY_LENGTH");
937     }
938 
939     if (record.mode != XfrmMode::TUNNEL &&
940         (record.xfrm_if_id != 0 || record.netId != 0 || record.mark.v != 0 || record.mark.m != 0)) {
941         return netdutils::statusFromErrno(EINVAL,
942                                           "xfrm_if_id, mark and netid parameters invalid "
943                                           "for non tunnel-mode transform");
944     } else if (record.mode == XfrmMode::TUNNEL && !mIsXfrmIntfSupported && record.xfrm_if_id != 0) {
945         return netdutils::statusFromErrno(EINVAL, "xfrm_if_id set for VTI Security Association");
946     }
947 
948     int len;
949     len = iov[USERSA].iov_len = fillUserSaInfo(record, &usersa);
950     iov[USERSA_PAD].iov_len = NLMSG_ALIGN(len) - len;
951 
952     len = iov[CRYPT].iov_len = fillNlAttrXfrmAlgoEnc(record.crypt, &crypt);
953     iov[CRYPT_PAD].iov_len = NLA_ALIGN(len) - len;
954 
955     len = iov[AUTH].iov_len = fillNlAttrXfrmAlgoAuth(record.auth, &auth);
956     iov[AUTH_PAD].iov_len = NLA_ALIGN(len) - len;
957 
958     len = iov[AEAD].iov_len = fillNlAttrXfrmAlgoAead(record.aead, &aead);
959     iov[AEAD_PAD].iov_len = NLA_ALIGN(len) - len;
960 
961     len = iov[MARK].iov_len = fillNlAttrXfrmMark(record, &xfrmmark);
962     iov[MARK_PAD].iov_len = NLA_ALIGN(len) - len;
963 
964     len = iov[OUTPUT_MARK].iov_len = fillNlAttrXfrmOutputMark(record.netId, &xfrmoutputmark);
965     iov[OUTPUT_MARK_PAD].iov_len = NLA_ALIGN(len) - len;
966 
967     len = iov[ENCAP].iov_len = fillNlAttrXfrmEncapTmpl(record, &encap);
968     iov[ENCAP_PAD].iov_len = NLA_ALIGN(len) - len;
969 
970     len = iov[INTF_ID].iov_len = fillNlAttrXfrmIntfId(record.xfrm_if_id, &xfrm_if_id);
971     iov[INTF_ID_PAD].iov_len = NLA_ALIGN(len) - len;
972 
973     return sock.sendMessage(XFRM_MSG_UPDSA, NETLINK_REQUEST_FLAGS, 0, &iov);
974 }
975 
fillNlAttrXfrmAlgoEnc(const XfrmAlgo & inAlgo,nlattr_algo_crypt * algo)976 int XfrmController::fillNlAttrXfrmAlgoEnc(const XfrmAlgo& inAlgo, nlattr_algo_crypt* algo) {
977     if (inAlgo.name.empty()) { // Do not fill anything if algorithm not provided
978         return 0;
979     }
980 
981     int len = NLA_HDRLEN + sizeof(xfrm_algo);
982     // Kernel always changes last char to null terminator; no safety checks needed.
983     strncpy(algo->crypt.alg_name, inAlgo.name.c_str(), sizeof(algo->crypt.alg_name));
984     algo->crypt.alg_key_len = inAlgo.key.size() * 8; // bits
985     memcpy(algo->key, &inAlgo.key[0], inAlgo.key.size());
986     len += inAlgo.key.size();
987     fillXfrmNlaHdr(&algo->hdr, XFRMA_ALG_CRYPT, len);
988     return len;
989 }
990 
fillNlAttrXfrmAlgoAuth(const XfrmAlgo & inAlgo,nlattr_algo_auth * algo)991 int XfrmController::fillNlAttrXfrmAlgoAuth(const XfrmAlgo& inAlgo, nlattr_algo_auth* algo) {
992     if (inAlgo.name.empty()) { // Do not fill anything if algorithm not provided
993         return 0;
994     }
995 
996     int len = NLA_HDRLEN + sizeof(xfrm_algo_auth);
997     // Kernel always changes last char to null terminator; no safety checks needed.
998     strncpy(algo->auth.alg_name, inAlgo.name.c_str(), sizeof(algo->auth.alg_name));
999     algo->auth.alg_key_len = inAlgo.key.size() * 8; // bits
1000 
1001     // This is the extra field for ALG_AUTH_TRUNC
1002     algo->auth.alg_trunc_len = inAlgo.truncLenBits;
1003 
1004     memcpy(algo->key, &inAlgo.key[0], inAlgo.key.size());
1005     len += inAlgo.key.size();
1006 
1007     fillXfrmNlaHdr(&algo->hdr, XFRMA_ALG_AUTH_TRUNC, len);
1008     return len;
1009 }
1010 
fillNlAttrXfrmAlgoAead(const XfrmAlgo & inAlgo,nlattr_algo_aead * algo)1011 int XfrmController::fillNlAttrXfrmAlgoAead(const XfrmAlgo& inAlgo, nlattr_algo_aead* algo) {
1012     if (inAlgo.name.empty()) { // Do not fill anything if algorithm not provided
1013         return 0;
1014     }
1015 
1016     int len = NLA_HDRLEN + sizeof(xfrm_algo_aead);
1017     // Kernel always changes last char to null terminator; no safety checks needed.
1018     strncpy(algo->aead.alg_name, inAlgo.name.c_str(), sizeof(algo->aead.alg_name));
1019     algo->aead.alg_key_len = inAlgo.key.size() * 8; // bits
1020 
1021     // This is the extra field for ALG_AEAD. ICV length is the same as truncation length
1022     // for any AEAD algorithm.
1023     algo->aead.alg_icv_len = inAlgo.truncLenBits;
1024 
1025     memcpy(algo->key, &inAlgo.key[0], inAlgo.key.size());
1026     len += inAlgo.key.size();
1027 
1028     fillXfrmNlaHdr(&algo->hdr, XFRMA_ALG_AEAD, len);
1029     return len;
1030 }
1031 
fillNlAttrXfrmEncapTmpl(const XfrmSaInfo & record,nlattr_encap_tmpl * tmpl)1032 int XfrmController::fillNlAttrXfrmEncapTmpl(const XfrmSaInfo& record, nlattr_encap_tmpl* tmpl) {
1033     if (record.encap.type == XfrmEncapType::NONE) {
1034         return 0;
1035     }
1036 
1037     int len = NLA_HDRLEN + sizeof(xfrm_encap_tmpl);
1038     tmpl->tmpl.encap_type = static_cast<uint16_t>(record.encap.type);
1039     tmpl->tmpl.encap_sport = htons(record.encap.srcPort);
1040     tmpl->tmpl.encap_dport = htons(record.encap.dstPort);
1041     fillXfrmNlaHdr(&tmpl->hdr, XFRMA_ENCAP, len);
1042     return len;
1043 }
1044 
fillUserSaInfo(const XfrmSaInfo & record,xfrm_usersa_info * usersa)1045 int XfrmController::fillUserSaInfo(const XfrmSaInfo& record, xfrm_usersa_info* usersa) {
1046     // Use AF_UNSPEC for all SAs. In transport mode, kernel picks selector family based on
1047     // usersa->family, while in tunnel mode, the XFRM_STATE_AF_UNSPEC flag allows dual-stack SAs.
1048     fillXfrmSelector(AF_UNSPEC, &usersa->sel);
1049 
1050     usersa->id.proto = IPPROTO_ESP;
1051     usersa->id.spi = record.spi;
1052     usersa->id.daddr = record.dstAddr;
1053 
1054     usersa->saddr = record.srcAddr;
1055 
1056     fillXfrmLifetimeDefaults(&usersa->lft);
1057     fillXfrmCurLifetimeDefaults(&usersa->curlft);
1058     memset(&usersa->stats, 0, sizeof(usersa->stats)); // leave stats zeroed out
1059     usersa->reqid = record.transformId;
1060     usersa->family = record.addrFamily;
1061     usersa->mode = static_cast<uint8_t>(record.mode);
1062     usersa->replay_window = REPLAY_WINDOW_SIZE;
1063 
1064     if (record.mode == XfrmMode::TRANSPORT) {
1065         usersa->flags = 0; // TODO: should we actually set flags, XFRM_SA_XFLAG_DONT_ENCAP_DSCP?
1066     } else {
1067         usersa->flags = XFRM_STATE_AF_UNSPEC;
1068     }
1069 
1070     return sizeof(*usersa);
1071 }
1072 
fillUserSaId(const XfrmCommonInfo & record,xfrm_usersa_id * said)1073 int XfrmController::fillUserSaId(const XfrmCommonInfo& record, xfrm_usersa_id* said) {
1074     said->daddr = record.dstAddr;
1075     said->spi = record.spi;
1076     said->family = record.addrFamily;
1077     said->proto = IPPROTO_ESP;
1078 
1079     return sizeof(*said);
1080 }
1081 
deleteSecurityAssociation(const XfrmCommonInfo & record,const XfrmSocket & sock)1082 netdutils::Status XfrmController::deleteSecurityAssociation(const XfrmCommonInfo& record,
1083                                                             const XfrmSocket& sock) {
1084     xfrm_usersa_id said{};
1085     nlattr_xfrm_mark xfrmmark{};
1086     nlattr_xfrm_interface_id xfrm_if_id{};
1087 
1088     enum { NLMSG_HDR, USERSAID, USERSAID_PAD, MARK, MARK_PAD, INTF_ID, INTF_ID_PAD };
1089 
1090     std::vector<iovec> iov = {
1091             {nullptr, 0},      // reserved for the eventual addition of a NLMSG_HDR
1092             {&said, 0},        // main usersa_info struct
1093             {kPadBytes, 0},    // up to NLMSG_ALIGNTO pad bytes of padding
1094             {&xfrmmark, 0},    // adjust size if xfrm mark is present
1095             {kPadBytes, 0},    // up to NLATTR_ALIGNTO pad bytes
1096             {&xfrm_if_id, 0},  // adjust size if interface ID is present
1097             {kPadBytes, 0},    // up to NLATTR_ALIGNTO pad bytes
1098     };
1099 
1100     int len;
1101     len = iov[USERSAID].iov_len = fillUserSaId(record, &said);
1102     iov[USERSAID_PAD].iov_len = NLMSG_ALIGN(len) - len;
1103 
1104     len = iov[MARK].iov_len = fillNlAttrXfrmMark(record, &xfrmmark);
1105     iov[MARK_PAD].iov_len = NLA_ALIGN(len) - len;
1106 
1107     len = iov[INTF_ID].iov_len = fillNlAttrXfrmIntfId(record.xfrm_if_id, &xfrm_if_id);
1108     iov[INTF_ID_PAD].iov_len = NLA_ALIGN(len) - len;
1109 
1110     return sock.sendMessage(XFRM_MSG_DELSA, NETLINK_REQUEST_FLAGS, 0, &iov);
1111 }
1112 
allocateSpi(const XfrmSaInfo & record,uint32_t minSpi,uint32_t maxSpi,uint32_t * outSpi,const XfrmSocket & sock)1113 netdutils::Status XfrmController::allocateSpi(const XfrmSaInfo& record, uint32_t minSpi,
1114                                               uint32_t maxSpi, uint32_t* outSpi,
1115                                               const XfrmSocket& sock) {
1116     xfrm_userspi_info spiInfo{};
1117 
1118     enum { NLMSG_HDR, USERSAID, USERSAID_PAD };
1119 
1120     std::vector<iovec> iov = {
1121         {nullptr, 0},      // reserved for the eventual addition of a NLMSG_HDR
1122         {&spiInfo, 0},  // main userspi_info struct
1123         {kPadBytes, 0}, // up to NLMSG_ALIGNTO pad bytes of padding
1124     };
1125 
1126     int len;
1127     if (fillUserSaInfo(record, &spiInfo.info) == 0) {
1128         ALOGE("Failed to fill transport SA Info");
1129     }
1130 
1131     len = iov[USERSAID].iov_len = sizeof(spiInfo);
1132     iov[USERSAID_PAD].iov_len = NLMSG_ALIGN(len) - len;
1133 
1134     RandomSpi spiGen = RandomSpi(minSpi, maxSpi);
1135     int spi;
1136     netdutils::Status ret;
1137     while ((spi = spiGen.next()) != INVALID_SPI) {
1138         spiInfo.min = spi;
1139         spiInfo.max = spi;
1140         ret = sock.sendMessage(XFRM_MSG_ALLOCSPI, NETLINK_REQUEST_FLAGS, 0, &iov);
1141 
1142         /* If the SPI is in use, we'll get ENOENT */
1143         if (netdutils::equalToErrno(ret, ENOENT))
1144             continue;
1145 
1146         if (isOk(ret)) {
1147             *outSpi = spi;
1148             ALOGD("Allocated an SPI: %x", *outSpi);
1149         } else {
1150             *outSpi = INVALID_SPI;
1151             ALOGE("SPI Allocation Failed with error %d", ret.code());
1152         }
1153 
1154         return ret;
1155     }
1156 
1157     // Should always be -ENOENT if we get here
1158     return ret;
1159 }
1160 
updateTunnelModeSecurityPolicy(const XfrmSpInfo & record,const XfrmSocket & sock,XfrmDirection direction,uint16_t msgType)1161 netdutils::Status XfrmController::updateTunnelModeSecurityPolicy(const XfrmSpInfo& record,
1162                                                                  const XfrmSocket& sock,
1163                                                                  XfrmDirection direction,
1164                                                                  uint16_t msgType) {
1165     xfrm_userpolicy_info userpolicy{};
1166     nlattr_user_tmpl usertmpl{};
1167     nlattr_xfrm_mark xfrmmark{};
1168     nlattr_xfrm_interface_id xfrm_if_id{};
1169 
1170     enum {
1171         NLMSG_HDR,
1172         USERPOLICY,
1173         USERPOLICY_PAD,
1174         USERTMPL,
1175         USERTMPL_PAD,
1176         MARK,
1177         MARK_PAD,
1178         INTF_ID,
1179         INTF_ID_PAD,
1180     };
1181 
1182     std::vector<iovec> iov = {
1183             {nullptr, 0},      // reserved for the eventual addition of a NLMSG_HDR
1184             {&userpolicy, 0},  // main xfrm_userpolicy_info struct
1185             {kPadBytes, 0},    // up to NLMSG_ALIGNTO pad bytes of padding
1186             {&usertmpl, 0},    // adjust size if xfrm_user_tmpl struct is present
1187             {kPadBytes, 0},    // up to NLATTR_ALIGNTO pad bytes
1188             {&xfrmmark, 0},    // adjust size if xfrm mark is present
1189             {kPadBytes, 0},    // up to NLATTR_ALIGNTO pad bytes
1190             {&xfrm_if_id, 0},  // adjust size if interface ID is present
1191             {kPadBytes, 0},    // up to NLATTR_ALIGNTO pad bytes
1192     };
1193 
1194     int len;
1195     len = iov[USERPOLICY].iov_len = fillUserSpInfo(record, direction, &userpolicy);
1196     iov[USERPOLICY_PAD].iov_len = NLMSG_ALIGN(len) - len;
1197 
1198     len = iov[USERTMPL].iov_len = fillNlAttrUserTemplate(record, &usertmpl);
1199     iov[USERTMPL_PAD].iov_len = NLA_ALIGN(len) - len;
1200 
1201     len = iov[MARK].iov_len = fillNlAttrXfrmMark(record, &xfrmmark);
1202     iov[MARK_PAD].iov_len = NLA_ALIGN(len) - len;
1203 
1204     len = iov[INTF_ID].iov_len = fillNlAttrXfrmIntfId(record.xfrm_if_id, &xfrm_if_id);
1205     iov[INTF_ID_PAD].iov_len = NLA_ALIGN(len) - len;
1206 
1207     return sock.sendMessage(msgType, NETLINK_REQUEST_FLAGS, 0, &iov);
1208 }
1209 
deleteTunnelModeSecurityPolicy(const XfrmSpInfo & record,const XfrmSocket & sock,XfrmDirection direction)1210 netdutils::Status XfrmController::deleteTunnelModeSecurityPolicy(const XfrmSpInfo& record,
1211                                                                  const XfrmSocket& sock,
1212                                                                  XfrmDirection direction) {
1213     xfrm_userpolicy_id policyid{};
1214     nlattr_xfrm_mark xfrmmark{};
1215     nlattr_xfrm_interface_id xfrm_if_id{};
1216 
1217     enum {
1218         NLMSG_HDR,
1219         USERPOLICYID,
1220         USERPOLICYID_PAD,
1221         MARK,
1222         MARK_PAD,
1223         INTF_ID,
1224         INTF_ID_PAD,
1225     };
1226 
1227     std::vector<iovec> iov = {
1228             {nullptr, 0},      // reserved for the eventual addition of a NLMSG_HDR
1229             {&policyid, 0},    // main xfrm_userpolicy_id struct
1230             {kPadBytes, 0},    // up to NLMSG_ALIGNTO pad bytes of padding
1231             {&xfrmmark, 0},    // adjust size if xfrm mark is present
1232             {kPadBytes, 0},    // up to NLATTR_ALIGNTO pad bytes
1233             {&xfrm_if_id, 0},  // adjust size if interface ID is present
1234             {kPadBytes, 0},    // up to NLATTR_ALIGNTO pad bytes
1235     };
1236 
1237     int len = iov[USERPOLICYID].iov_len = fillUserPolicyId(record, direction, &policyid);
1238     iov[USERPOLICYID_PAD].iov_len = NLMSG_ALIGN(len) - len;
1239 
1240     len = iov[MARK].iov_len = fillNlAttrXfrmMark(record, &xfrmmark);
1241     iov[MARK_PAD].iov_len = NLA_ALIGN(len) - len;
1242 
1243     len = iov[INTF_ID].iov_len = fillNlAttrXfrmIntfId(record.xfrm_if_id, &xfrm_if_id);
1244     iov[INTF_ID_PAD].iov_len = NLA_ALIGN(len) - len;
1245 
1246     return sock.sendMessage(XFRM_MSG_DELPOLICY, NETLINK_REQUEST_FLAGS, 0, &iov);
1247 }
1248 
fillUserSpInfo(const XfrmSpInfo & record,XfrmDirection direction,xfrm_userpolicy_info * usersp)1249 int XfrmController::fillUserSpInfo(const XfrmSpInfo& record, XfrmDirection direction,
1250                                    xfrm_userpolicy_info* usersp) {
1251     fillXfrmSelector(record.selAddrFamily, &usersp->sel);
1252     fillXfrmLifetimeDefaults(&usersp->lft);
1253     fillXfrmCurLifetimeDefaults(&usersp->curlft);
1254     /* if (index) index & 0x3 == dir -- must be true
1255      * xfrm_user.c:verify_newpolicy_info() */
1256     usersp->index = 0;
1257     usersp->dir = static_cast<uint8_t>(direction);
1258     usersp->action = XFRM_POLICY_ALLOW;
1259     usersp->flags = XFRM_POLICY_LOCALOK;
1260     usersp->share = XFRM_SHARE_UNIQUE;
1261     return sizeof(*usersp);
1262 }
1263 
fillUserTemplate(const XfrmSpInfo & record,xfrm_user_tmpl * tmpl)1264 void XfrmController::fillUserTemplate(const XfrmSpInfo& record, xfrm_user_tmpl* tmpl) {
1265     tmpl->id.daddr = record.dstAddr;
1266     tmpl->id.spi = record.spi;
1267     tmpl->id.proto = IPPROTO_ESP;
1268 
1269     tmpl->family = record.addrFamily;
1270     tmpl->saddr = record.srcAddr;
1271     tmpl->reqid = record.transformId;
1272     tmpl->mode = static_cast<uint8_t>(record.mode);
1273     tmpl->share = XFRM_SHARE_UNIQUE;
1274     tmpl->optional = 0; // if this is true, then a failed state lookup will be considered OK:
1275                         // http://lxr.free-electrons.com/source/net/xfrm/xfrm_policy.c#L1492
1276     tmpl->aalgos = ALGO_MASK_AUTH_ALL;  // TODO: if there's a bitmask somewhere of
1277                                         // algos, we should find it and apply it.
1278                                         // I can't find one.
1279     tmpl->ealgos = ALGO_MASK_CRYPT_ALL; // TODO: if there's a bitmask somewhere...
1280 }
1281 
fillNlAttrUserTemplate(const XfrmSpInfo & record,nlattr_user_tmpl * tmpl)1282 int XfrmController::fillNlAttrUserTemplate(const XfrmSpInfo& record, nlattr_user_tmpl* tmpl) {
1283     fillUserTemplate(record, &tmpl->tmpl);
1284 
1285     int len = NLA_HDRLEN + sizeof(xfrm_user_tmpl);
1286     fillXfrmNlaHdr(&tmpl->hdr, XFRMA_TMPL, len);
1287     return len;
1288 }
1289 
fillNlAttrXfrmMark(const XfrmCommonInfo & record,nlattr_xfrm_mark * mark)1290 int XfrmController::fillNlAttrXfrmMark(const XfrmCommonInfo& record, nlattr_xfrm_mark* mark) {
1291     // Do not set if we were not given a mark
1292     if (record.mark.v == 0 && record.mark.m == 0) {
1293         return 0;
1294     }
1295 
1296     mark->mark.v = record.mark.v; // set to 0 if it's not used
1297     mark->mark.m = record.mark.m; // set to 0 if it's not used
1298     int len = NLA_HDRLEN + sizeof(xfrm_mark);
1299     fillXfrmNlaHdr(&mark->hdr, XFRMA_MARK, len);
1300     return len;
1301 }
1302 
1303 // This function sets the output mark (or set-mark in newer kernels) to that of the underlying
1304 // Network's netid. This allows outbound IPsec Tunnel mode packets to be correctly directed to a
1305 // preselected underlying Network. Packet as marked as protected from VPNs and have a network
1306 // explicitly selected to prevent interference or routing loops. Also set permission flag to
1307 // PERMISSION_SYSTEM to ensure we can use background/restricted networks. Permission to use
1308 // restricted networks is checked in IpSecService.
fillNlAttrXfrmOutputMark(const __u32 underlyingNetId,nlattr_xfrm_output_mark * output_mark)1309 int XfrmController::fillNlAttrXfrmOutputMark(const __u32 underlyingNetId,
1310                                              nlattr_xfrm_output_mark* output_mark) {
1311     // Do not set if we were not given an output mark
1312     if (underlyingNetId == 0) {
1313         return 0;
1314     }
1315 
1316     Fwmark fwmark;
1317     fwmark.netId = underlyingNetId;
1318 
1319     // TODO: Rework this to more accurately follow the underlying network
1320     fwmark.permission = PERMISSION_SYSTEM;
1321     fwmark.explicitlySelected = true;
1322     fwmark.protectedFromVpn = true;
1323     output_mark->outputMark = fwmark.intValue;
1324 
1325     int len = NLA_HDRLEN + sizeof(__u32);
1326     fillXfrmNlaHdr(&output_mark->hdr, XFRMA_OUTPUT_MARK, len);
1327     return len;
1328 }
1329 
fillNlAttrXfrmIntfId(const uint32_t intfIdValue,nlattr_xfrm_interface_id * intf_id)1330 int XfrmController::fillNlAttrXfrmIntfId(const uint32_t intfIdValue,
1331                                          nlattr_xfrm_interface_id* intf_id) {
1332     // Do not set if we were not given an interface id
1333     if (intfIdValue == 0) {
1334         return 0;
1335     }
1336 
1337     intf_id->if_id = intfIdValue;
1338     int len = NLA_HDRLEN + sizeof(__u32);
1339     fillXfrmNlaHdr(&intf_id->hdr, XFRMA_IF_ID, len);
1340     return len;
1341 }
1342 
fillUserPolicyId(const XfrmSpInfo & record,XfrmDirection direction,xfrm_userpolicy_id * usersp)1343 int XfrmController::fillUserPolicyId(const XfrmSpInfo& record, XfrmDirection direction,
1344                                      xfrm_userpolicy_id* usersp) {
1345     // For DELPOLICY, when index is absent, selector is needed to match the policy
1346     fillXfrmSelector(record.selAddrFamily, &usersp->sel);
1347     usersp->dir = static_cast<uint8_t>(direction);
1348     return sizeof(*usersp);
1349 }
1350 
ipSecAddTunnelInterface(const std::string & deviceName,const std::string & localAddress,const std::string & remoteAddress,int32_t ikey,int32_t okey,int32_t interfaceId,bool isUpdate)1351 netdutils::Status XfrmController::ipSecAddTunnelInterface(const std::string& deviceName,
1352                                                           const std::string& localAddress,
1353                                                           const std::string& remoteAddress,
1354                                                           int32_t ikey, int32_t okey,
1355                                                           int32_t interfaceId, bool isUpdate) {
1356     ALOGD("XfrmController::%s, line=%d", __FUNCTION__, __LINE__);
1357     ALOGD("deviceName=%s", deviceName.c_str());
1358     ALOGD("localAddress=%s", localAddress.c_str());
1359     ALOGD("remoteAddress=%s", remoteAddress.c_str());
1360     ALOGD("ikey=%0.8x", ikey);
1361     ALOGD("okey=%0.8x", okey);
1362     ALOGD("interfaceId=%0.8x", interfaceId);
1363     ALOGD("isUpdate=%d", isUpdate);
1364 
1365     uint16_t flags = isUpdate ? NETLINK_REQUEST_FLAGS : NETLINK_ROUTE_CREATE_FLAGS;
1366 
1367     if (mIsXfrmIntfSupported) {
1368         return ipSecAddXfrmInterface(deviceName, interfaceId, flags);
1369     } else {
1370         return ipSecAddVirtualTunnelInterface(deviceName, localAddress, remoteAddress, ikey, okey,
1371                                               flags);
1372     }
1373 }
1374 
ipSecAddXfrmInterface(const std::string & deviceName,int32_t interfaceId,uint16_t flags)1375 netdutils::Status XfrmController::ipSecAddXfrmInterface(const std::string& deviceName,
1376                                                         int32_t interfaceId, uint16_t flags) {
1377     ALOGD("XfrmController::%s, line=%d", __FUNCTION__, __LINE__);
1378 
1379     if (deviceName.empty()) {
1380         return netdutils::statusFromErrno(EINVAL, "XFRM Interface deviceName empty");
1381     }
1382 
1383     ifinfomsg ifInfoMsg{};
1384 
1385     struct XfrmIntfCreateReq {
1386         nlattr ifNameNla;
1387         char ifName[IFNAMSIZ];  // Already aligned
1388 
1389         nlattr linkInfoNla;
1390         struct LinkInfo {
1391             nlattr infoKindNla;
1392             char infoKind[INFO_KIND_MAX_LEN];  // Already aligned
1393 
1394             nlattr infoDataNla;
1395             struct InfoData {
1396                 nlattr xfrmLinkNla;
1397                 uint32_t xfrmLink;
1398 
1399                 nlattr xfrmIfIdNla;
1400                 uint32_t xfrmIfId;
1401             } infoData;  // Already aligned
1402 
1403         } linkInfo;  // Already aligned
1404     } xfrmIntfCreateReq{
1405             .ifNameNla =
1406                     {
1407                             .nla_len = RTA_LENGTH(IFNAMSIZ),
1408                             .nla_type = IFLA_IFNAME,
1409                     },
1410             // Update .ifName via strlcpy
1411 
1412             .linkInfoNla =
1413                     {
1414                             .nla_len = RTA_LENGTH(sizeof(XfrmIntfCreateReq::LinkInfo)),
1415                             .nla_type = IFLA_LINKINFO,
1416                     },
1417             .linkInfo = {.infoKindNla =
1418                                  {
1419                                          .nla_len = RTA_LENGTH(INFO_KIND_MAX_LEN),
1420                                          .nla_type = IFLA_INFO_KIND,
1421                                  },
1422                          // Update .infoKind via strlcpy
1423 
1424                          .infoDataNla =
1425                                  {
1426                                          .nla_len = RTA_LENGTH(
1427                                                  sizeof(XfrmIntfCreateReq::LinkInfo::InfoData)),
1428                                          .nla_type = IFLA_INFO_DATA,
1429                                  },
1430                          .infoData = {
1431                                  .xfrmLinkNla =
1432                                          {
1433                                                  .nla_len = RTA_LENGTH(sizeof(uint32_t)),
1434                                                  .nla_type = IFLA_XFRM_LINK,
1435                                          },
1436                                  //   Always use LOOPBACK_IFINDEX, since we use output marks for
1437                                  //   route lookup instead. The use case of having a Network with
1438                                  //   loopback in it is unsupported in tunnel mode.
1439                                  .xfrmLink = static_cast<uint32_t>(LOOPBACK_IFINDEX),
1440 
1441                                  .xfrmIfIdNla =
1442                                          {
1443                                                  .nla_len = RTA_LENGTH(sizeof(uint32_t)),
1444                                                  .nla_type = IFLA_XFRM_IF_ID,
1445                                          },
1446                                  .xfrmIfId = static_cast<uint32_t>(interfaceId),
1447                          }}};
1448 
1449     strlcpy(xfrmIntfCreateReq.ifName, deviceName.c_str(), IFNAMSIZ);
1450     strlcpy(xfrmIntfCreateReq.linkInfo.infoKind, INFO_KIND_XFRMI, INFO_KIND_MAX_LEN);
1451 
1452     iovec iov[] = {
1453             {NULL, 0},  // reserved for the eventual addition of a NLMSG_HDR
1454             {&ifInfoMsg, sizeof(ifInfoMsg)},
1455 
1456             {&xfrmIntfCreateReq, sizeof(xfrmIntfCreateReq)},
1457     };
1458 
1459     // sendNetlinkRequest returns -errno
1460     int ret = -sendNetlinkRequest(RTM_NEWLINK, flags, iov, ARRAY_SIZE(iov), nullptr);
1461     return netdutils::statusFromErrno(ret, "Add/update xfrm interface");
1462 }
1463 
ipSecAddVirtualTunnelInterface(const std::string & deviceName,const std::string & localAddress,const std::string & remoteAddress,int32_t ikey,int32_t okey,uint16_t flags)1464 netdutils::Status XfrmController::ipSecAddVirtualTunnelInterface(const std::string& deviceName,
1465                                                                  const std::string& localAddress,
1466                                                                  const std::string& remoteAddress,
1467                                                                  int32_t ikey, int32_t okey,
1468                                                                  uint16_t flags) {
1469     ALOGD("XfrmController::%s, line=%d", __FUNCTION__, __LINE__);
1470 
1471     if (deviceName.empty() || localAddress.empty() || remoteAddress.empty()) {
1472         return netdutils::statusFromErrno(EINVAL, "Required VTI creation parameter not provided");
1473     }
1474 
1475     uint8_t PADDING_BUFFER[] = {0, 0, 0, 0};
1476 
1477     // Find address family.
1478     uint8_t remAddr[sizeof(in6_addr)];
1479 
1480     StatusOr<uint16_t> statusOrRemoteFam = convertStringAddress(remoteAddress, remAddr);
1481     RETURN_IF_NOT_OK(statusOrRemoteFam);
1482 
1483     uint8_t locAddr[sizeof(in6_addr)];
1484     StatusOr<uint16_t> statusOrLocalFam = convertStringAddress(localAddress, locAddr);
1485     RETURN_IF_NOT_OK(statusOrLocalFam);
1486 
1487     if (statusOrLocalFam.value() != statusOrRemoteFam.value()) {
1488         return netdutils::statusFromErrno(EINVAL, "Local and remote address families do not match");
1489     }
1490 
1491     uint16_t family = statusOrLocalFam.value();
1492 
1493     ifinfomsg ifInfoMsg{};
1494 
1495     // Construct IFLA_IFNAME
1496     nlattr iflaIfName;
1497     char iflaIfNameStrValue[deviceName.length() + 1];
1498     size_t iflaIfNameLength =
1499         strlcpy(iflaIfNameStrValue, deviceName.c_str(), sizeof(iflaIfNameStrValue));
1500     size_t iflaIfNamePad = fillNlAttr(IFLA_IFNAME, iflaIfNameLength, &iflaIfName);
1501 
1502     // Construct IFLA_INFO_KIND
1503     // Constants "vti6" and "vti" enable the kernel to call different code paths,
1504     // (ip_tunnel.c, ip6_tunnel), based on the family.
1505     const std::string infoKindValue = (family == AF_INET6) ? INFO_KIND_VTI6 : INFO_KIND_VTI;
1506     nlattr iflaIfInfoKind;
1507     char infoKindValueStrValue[infoKindValue.length() + 1];
1508     size_t iflaIfInfoKindLength =
1509         strlcpy(infoKindValueStrValue, infoKindValue.c_str(), sizeof(infoKindValueStrValue));
1510     size_t iflaIfInfoKindPad = fillNlAttr(IFLA_INFO_KIND, iflaIfInfoKindLength, &iflaIfInfoKind);
1511 
1512     // Construct IFLA_VTI_LOCAL
1513     nlattr iflaVtiLocal;
1514     uint8_t binaryLocalAddress[sizeof(in6_addr)];
1515     size_t iflaVtiLocalPad =
1516         fillNlAttrIpAddress(IFLA_VTI_LOCAL, family, localAddress, &iflaVtiLocal,
1517                             netdutils::makeSlice(binaryLocalAddress));
1518 
1519     // Construct IFLA_VTI_REMOTE
1520     nlattr iflaVtiRemote;
1521     uint8_t binaryRemoteAddress[sizeof(in6_addr)];
1522     size_t iflaVtiRemotePad =
1523         fillNlAttrIpAddress(IFLA_VTI_REMOTE, family, remoteAddress, &iflaVtiRemote,
1524                             netdutils::makeSlice(binaryRemoteAddress));
1525 
1526     // Construct IFLA_VTI_OKEY
1527     nlattr_payload_u32 iflaVtiIKey;
1528     size_t iflaVtiIKeyPad = fillNlAttrU32(IFLA_VTI_IKEY, htonl(ikey), &iflaVtiIKey);
1529 
1530     // Construct IFLA_VTI_IKEY
1531     nlattr_payload_u32 iflaVtiOKey;
1532     size_t iflaVtiOKeyPad = fillNlAttrU32(IFLA_VTI_OKEY, htonl(okey), &iflaVtiOKey);
1533 
1534     int iflaInfoDataPayloadLength = iflaVtiLocal.nla_len + iflaVtiLocalPad + iflaVtiRemote.nla_len +
1535                                     iflaVtiRemotePad + iflaVtiIKey.hdr.nla_len + iflaVtiIKeyPad +
1536                                     iflaVtiOKey.hdr.nla_len + iflaVtiOKeyPad;
1537 
1538     // Construct IFLA_INFO_DATA
1539     nlattr iflaInfoData;
1540     size_t iflaInfoDataPad = fillNlAttr(IFLA_INFO_DATA, iflaInfoDataPayloadLength, &iflaInfoData);
1541 
1542     // Construct IFLA_LINKINFO
1543     nlattr iflaLinkInfo;
1544     size_t iflaLinkInfoPad = fillNlAttr(IFLA_LINKINFO,
1545                                         iflaInfoData.nla_len + iflaInfoDataPad +
1546                                             iflaIfInfoKind.nla_len + iflaIfInfoKindPad,
1547                                         &iflaLinkInfo);
1548 
1549     iovec iov[] = {
1550             {nullptr, 0},
1551             {&ifInfoMsg, sizeof(ifInfoMsg)},
1552 
1553             {&iflaIfName, sizeof(iflaIfName)},
1554             {iflaIfNameStrValue, iflaIfNameLength},
1555             {&PADDING_BUFFER, iflaIfNamePad},
1556 
1557             {&iflaLinkInfo, sizeof(iflaLinkInfo)},
1558 
1559             {&iflaIfInfoKind, sizeof(iflaIfInfoKind)},
1560             {infoKindValueStrValue, iflaIfInfoKindLength},
1561             {&PADDING_BUFFER, iflaIfInfoKindPad},
1562 
1563             {&iflaInfoData, sizeof(iflaInfoData)},
1564 
1565             {&iflaVtiLocal, sizeof(iflaVtiLocal)},
1566             {&binaryLocalAddress, (family == AF_INET) ? sizeof(in_addr) : sizeof(in6_addr)},
1567             {&PADDING_BUFFER, iflaVtiLocalPad},
1568 
1569             {&iflaVtiRemote, sizeof(iflaVtiRemote)},
1570             {&binaryRemoteAddress, (family == AF_INET) ? sizeof(in_addr) : sizeof(in6_addr)},
1571             {&PADDING_BUFFER, iflaVtiRemotePad},
1572 
1573             {&iflaVtiIKey, iflaVtiIKey.hdr.nla_len},
1574             {&PADDING_BUFFER, iflaVtiIKeyPad},
1575 
1576             {&iflaVtiOKey, iflaVtiOKey.hdr.nla_len},
1577             {&PADDING_BUFFER, iflaVtiOKeyPad},
1578 
1579             {&PADDING_BUFFER, iflaInfoDataPad},
1580 
1581             {&PADDING_BUFFER, iflaLinkInfoPad},
1582     };
1583 
1584     // sendNetlinkRequest returns -errno
1585     int ret = -1 * sendNetlinkRequest(RTM_NEWLINK, flags, iov, ARRAY_SIZE(iov), nullptr);
1586     return netdutils::statusFromErrno(ret, "Failed to add/update virtual tunnel interface");
1587 }
1588 
ipSecRemoveTunnelInterface(const std::string & deviceName)1589 netdutils::Status XfrmController::ipSecRemoveTunnelInterface(const std::string& deviceName) {
1590     ALOGD("XfrmController::%s, line=%d", __FUNCTION__, __LINE__);
1591     ALOGD("deviceName=%s", deviceName.c_str());
1592 
1593     if (deviceName.empty()) {
1594         return netdutils::statusFromErrno(EINVAL, "Required parameter not provided");
1595     }
1596 
1597     uint8_t PADDING_BUFFER[] = {0, 0, 0, 0};
1598 
1599     ifinfomsg ifInfoMsg{};
1600     nlattr iflaIfName;
1601     char iflaIfNameStrValue[deviceName.length() + 1];
1602     size_t iflaIfNameLength =
1603         strlcpy(iflaIfNameStrValue, deviceName.c_str(), sizeof(iflaIfNameStrValue));
1604     size_t iflaIfNamePad = fillNlAttr(IFLA_IFNAME, iflaIfNameLength, &iflaIfName);
1605 
1606     iovec iov[] = {
1607         {nullptr, 0},
1608         {&ifInfoMsg, sizeof(ifInfoMsg)},
1609 
1610         {&iflaIfName, sizeof(iflaIfName)},
1611         {iflaIfNameStrValue, iflaIfNameLength},
1612         {&PADDING_BUFFER, iflaIfNamePad},
1613     };
1614 
1615     uint16_t action = RTM_DELLINK;
1616     uint16_t flags = NLM_F_REQUEST | NLM_F_ACK;
1617 
1618     // sendNetlinkRequest returns -errno
1619     int ret = -1 * sendNetlinkRequest(action, flags, iov, ARRAY_SIZE(iov), nullptr);
1620     return netdutils::statusFromErrno(ret, "Error in deleting IpSec interface " + deviceName);
1621 }
1622 
dump(DumpWriter & dw)1623 void XfrmController::dump(DumpWriter& dw) {
1624     ScopedIndent indentForXfrmController(dw);
1625     dw.println("XfrmController");
1626 
1627     ScopedIndent indentForXfrmISupport(dw);
1628     dw.println("XFRM-I support: %d", mIsXfrmIntfSupported);
1629 }
1630 
1631 } // namespace net
1632 } // namespace android
1633