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