• 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 "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 #include "netdutils/Utils.h"
70 
71 using android::netdutils::DumpWriter;
72 using android::netdutils::Fd;
73 using android::netdutils::getIfaceNames;
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 = 32;
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 = 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 
ipSecMigrate(int32_t transformId,int32_t selAddrFamily,int32_t direction,const std::string & oldSourceAddress,const std::string & oldDestinationAddress,const std::string & newSourceAddress,const std::string & newDestinationAddress,int32_t xfrmInterfaceId)650 netdutils::Status XfrmController::ipSecMigrate(int32_t transformId, int32_t selAddrFamily,
651                                                int32_t direction,
652                                                const std::string& oldSourceAddress,
653                                                const std::string& oldDestinationAddress,
654                                                const std::string& newSourceAddress,
655                                                const std::string& newDestinationAddress,
656                                                int32_t xfrmInterfaceId) {
657     ALOGD("XfrmController:%s, line=%d", __FUNCTION__, __LINE__);
658     ALOGD("transformId=%d", transformId);
659     ALOGD("selAddrFamily=%d", selAddrFamily);
660     ALOGD("direction=%d", direction);
661     ALOGD("oldSourceAddress=%s", oldSourceAddress.c_str());
662     ALOGD("oldDestinationAddress=%s", oldDestinationAddress.c_str());
663     ALOGD("newSourceAddress=%s", newSourceAddress.c_str());
664     ALOGD("newDestinationAddress=%s", newDestinationAddress.c_str());
665     ALOGD("xfrmInterfaceId=%d", xfrmInterfaceId);
666 
667     XfrmSocketImpl sock;
668     Status socketStatus = sock.open();
669     if (!socketStatus.ok()) {
670         ALOGD("Sock open failed for XFRM, line=%d", __LINE__);
671         return socketStatus;
672     }
673 
674     XfrmMigrateInfo migrateInfo{};
675     Status ret =
676             fillXfrmCommonInfo(oldSourceAddress, oldDestinationAddress, 0 /* spi */, 0 /* mark */,
677                                0 /* markMask */, transformId, xfrmInterfaceId, &migrateInfo);
678 
679     if (!ret.ok()) {
680         ALOGD("Failed to fill in XfrmCommonInfo, line=%d", __LINE__);
681         return ret;
682     }
683 
684     migrateInfo.selAddrFamily = selAddrFamily;
685     migrateInfo.direction = static_cast<XfrmDirection>(direction);
686 
687     ret = fillXfrmEndpointPair(newSourceAddress, newDestinationAddress,
688                                &migrateInfo.newEndpointInfo);
689     if (!ret.ok()) {
690         ALOGD("Failed to fill in XfrmEndpointPair, line=%d", __LINE__);
691         return ret;
692     }
693 
694     ret = migrate(migrateInfo, sock);
695 
696     if (!ret.ok()) {
697         ALOGD("Failed to migrate Security Association, line=%d", __LINE__);
698     }
699     return ret;
700 }
701 
fillXfrmEndpointPair(const std::string & sourceAddress,const std::string & destinationAddress,XfrmEndpointPair * endpointPair)702 netdutils::Status XfrmController::fillXfrmEndpointPair(const std::string& sourceAddress,
703                                                        const std::string& destinationAddress,
704                                                        XfrmEndpointPair* endpointPair) {
705     // Use the addresses to determine the address family and do validation
706     xfrm_address_t sourceXfrmAddr{}, destXfrmAddr{};
707     StatusOr<int> sourceFamily, destFamily;
708     sourceFamily = convertToXfrmAddr(sourceAddress, &sourceXfrmAddr);
709     destFamily = convertToXfrmAddr(destinationAddress, &destXfrmAddr);
710     if (!isOk(sourceFamily) || !isOk(destFamily)) {
711         return netdutils::statusFromErrno(
712                 EINVAL, "Invalid address " + sourceAddress + "/" + destinationAddress);
713     }
714 
715     if (destFamily.value() == AF_UNSPEC ||
716         (sourceFamily.value() != AF_UNSPEC && sourceFamily.value() != destFamily.value())) {
717         ALOGD("Invalid or Mismatched Address Families, %d != %d, line=%d", sourceFamily.value(),
718               destFamily.value(), __LINE__);
719         return netdutils::statusFromErrno(EINVAL, "Invalid or mismatched address families");
720     }
721 
722     endpointPair->addrFamily = destFamily.value();
723 
724     endpointPair->dstAddr = destXfrmAddr;
725     endpointPair->srcAddr = sourceXfrmAddr;
726 
727     return netdutils::status::ok;
728 }
729 
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)730 netdutils::Status XfrmController::fillXfrmCommonInfo(const std::string& sourceAddress,
731                                                      const std::string& destinationAddress,
732                                                      int32_t spi, int32_t markValue,
733                                                      int32_t markMask, int32_t transformId,
734                                                      int32_t xfrmInterfaceId,
735                                                      XfrmCommonInfo* info) {
736     Status ret = fillXfrmEndpointPair(sourceAddress, destinationAddress, info);
737     if (!isOk(ret)) {
738         return ret;
739     }
740 
741     return fillXfrmCommonInfo(spi, markValue, markMask, transformId, xfrmInterfaceId, info);
742 }
743 
fillXfrmCommonInfo(int32_t spi,int32_t markValue,int32_t markMask,int32_t transformId,int32_t xfrmInterfaceId,XfrmCommonInfo * info)744 netdutils::Status XfrmController::fillXfrmCommonInfo(int32_t spi, int32_t markValue,
745                                                      int32_t markMask, int32_t transformId,
746                                                      int32_t xfrmInterfaceId,
747                                                      XfrmCommonInfo* info) {
748     info->transformId = transformId;
749     info->spi = htonl(spi);
750 
751     if (mIsXfrmIntfSupported) {
752         info->xfrm_if_id = xfrmInterfaceId;
753     } else {
754         info->mark.v = markValue;
755         info->mark.m = markMask;
756     }
757 
758     return netdutils::status::ok;
759 }
760 
ipSecApplyTransportModeTransform(int socketFd,int32_t transformId,int32_t direction,const std::string & sourceAddress,const std::string & destinationAddress,int32_t spi)761 netdutils::Status XfrmController::ipSecApplyTransportModeTransform(
762         int socketFd, int32_t transformId, int32_t direction, const std::string& sourceAddress,
763         const std::string& destinationAddress, int32_t spi) {
764     ALOGD("XfrmController::%s, line=%d", __FUNCTION__, __LINE__);
765     ALOGD("transformId=%d", transformId);
766     ALOGD("direction=%d", direction);
767     ALOGD("sourceAddress=%s", sourceAddress.c_str());
768     ALOGD("destinationAddress=%s", destinationAddress.c_str());
769     ALOGD("spi=%0.8x", spi);
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", __FUNCTION__);
775         return ret;
776     }
777     struct sockaddr_storage saddr = ret.value();
778 
779     XfrmSpInfo spInfo{};
780     netdutils::Status status = fillXfrmCommonInfo(sourceAddress, destinationAddress, spi, 0, 0,
781                                                   transformId, 0, &spInfo);
782     if (!isOk(status)) {
783         ALOGE("Couldn't build SA ID %s", __FUNCTION__);
784         return status;
785     }
786 
787     spInfo.selAddrFamily = spInfo.addrFamily;
788     spInfo.direction = static_cast<XfrmDirection>(direction);
789 
790     // Allow dual stack sockets. Dual stack sockets are guaranteed to never have an AF_INET source
791     // address; the source address would instead be an IPv4-mapped address. Thus, disallow AF_INET
792     // sockets with mismatched address families (All other cases are acceptable).
793     if (saddr.ss_family == AF_INET && spInfo.addrFamily != AF_INET) {
794         ALOGE("IPV4 socket address family(%d) should match IPV4 Transform "
795               "address family(%d)!",
796               saddr.ss_family, spInfo.addrFamily);
797         return netdutils::statusFromErrno(EINVAL, "Mismatched address family");
798     }
799 
800     struct {
801         xfrm_userpolicy_info info;
802         xfrm_user_tmpl tmpl;
803     } policy{};
804 
805     fillUserSpInfo(spInfo, &policy.info);
806     fillUserTemplate(spInfo, &policy.tmpl);
807 
808     LOG_HEX("XfrmUserPolicy", reinterpret_cast<char*>(&policy), sizeof(policy));
809 
810     int sockOpt, sockLayer;
811     switch (saddr.ss_family) {
812         case AF_INET:
813             sockOpt = IP_XFRM_POLICY;
814             sockLayer = SOL_IP;
815             break;
816         case AF_INET6:
817             sockOpt = IPV6_XFRM_POLICY;
818             sockLayer = SOL_IPV6;
819             break;
820         default:
821             return netdutils::statusFromErrno(EAFNOSUPPORT, "Invalid address family");
822     }
823 
824     status = getSyscallInstance().setsockopt(Fd(socketFd), sockLayer, sockOpt, policy);
825     if (!isOk(status)) {
826         ALOGE("Error setting socket option for XFRM! (%s)", toString(status).c_str());
827     }
828 
829     return status;
830 }
831 
ipSecRemoveTransportModeTransform(int socketFd)832 netdutils::Status XfrmController::ipSecRemoveTransportModeTransform(int socketFd) {
833     ALOGD("XfrmController::%s, line=%d", __FUNCTION__, __LINE__);
834 
835     StatusOr<sockaddr_storage> ret =
836             getSyscallInstance().getsockname<sockaddr_storage>(Fd(socketFd));
837     if (!isOk(ret)) {
838         ALOGE("Failed to get socket info in %s! (%s)", __FUNCTION__, toString(ret).c_str());
839         return ret;
840     }
841 
842     int sockOpt, sockLayer;
843     switch (ret.value().ss_family) {
844         case AF_INET:
845             sockOpt = IP_XFRM_POLICY;
846             sockLayer = SOL_IP;
847             break;
848         case AF_INET6:
849             sockOpt = IPV6_XFRM_POLICY;
850             sockLayer = SOL_IPV6;
851             break;
852         default:
853             return netdutils::statusFromErrno(EAFNOSUPPORT, "Invalid address family");
854     }
855 
856     // Kernel will delete the security policy on this socket for both direction
857     // if optval is set to NULL and optlen is set to 0.
858     netdutils::Status status =
859             getSyscallInstance().setsockopt(Fd(socketFd), sockLayer, sockOpt, nullptr, 0);
860     if (!isOk(status)) {
861         ALOGE("Error removing socket option for XFRM! (%s)", toString(status).c_str());
862     }
863 
864     return status;
865 }
866 
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)867 netdutils::Status XfrmController::ipSecAddSecurityPolicy(
868         int32_t transformId, int32_t selAddrFamily, int32_t direction,
869         const std::string& tmplSrcAddress, const std::string& tmplDstAddress, int32_t spi,
870         int32_t markValue, int32_t markMask, int32_t xfrmInterfaceId) {
871     return processSecurityPolicy(transformId, selAddrFamily, direction, tmplSrcAddress,
872                                  tmplDstAddress, spi, markValue, markMask, xfrmInterfaceId,
873                                  XFRM_MSG_NEWPOLICY);
874 }
875 
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)876 netdutils::Status XfrmController::ipSecUpdateSecurityPolicy(
877         int32_t transformId, int32_t selAddrFamily, int32_t direction,
878         const std::string& tmplSrcAddress, const std::string& tmplDstAddress, int32_t spi,
879         int32_t markValue, int32_t markMask, int32_t xfrmInterfaceId) {
880     return processSecurityPolicy(transformId, selAddrFamily, direction, tmplSrcAddress,
881                                  tmplDstAddress, spi, markValue, markMask, xfrmInterfaceId,
882                                  XFRM_MSG_UPDPOLICY);
883 }
884 
ipSecDeleteSecurityPolicy(int32_t transformId,int32_t selAddrFamily,int32_t direction,int32_t markValue,int32_t markMask,int32_t xfrmInterfaceId)885 netdutils::Status XfrmController::ipSecDeleteSecurityPolicy(int32_t transformId,
886                                                             int32_t selAddrFamily,
887                                                             int32_t direction, int32_t markValue,
888                                                             int32_t markMask,
889                                                             int32_t xfrmInterfaceId) {
890     return processSecurityPolicy(transformId, selAddrFamily, direction, "", "", 0, markValue,
891                                  markMask, xfrmInterfaceId, XFRM_MSG_DELPOLICY);
892 }
893 
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)894 netdutils::Status XfrmController::processSecurityPolicy(
895         int32_t transformId, int32_t selAddrFamily, int32_t direction,
896         const std::string& tmplSrcAddress, const std::string& tmplDstAddress, int32_t spi,
897         int32_t markValue, int32_t markMask, int32_t xfrmInterfaceId, int32_t msgType) {
898     ALOGD("XfrmController::%s, line=%d", __FUNCTION__, __LINE__);
899     ALOGD("selAddrFamily=%s", selAddrFamily == AF_INET6 ? "AF_INET6" : "AF_INET");
900     ALOGD("transformId=%d", transformId);
901     ALOGD("direction=%d", direction);
902     ALOGD("tmplSrcAddress=%s", tmplSrcAddress.c_str());
903     ALOGD("tmplDstAddress=%s", tmplDstAddress.c_str());
904     ALOGD("spi=%0.8x", spi);
905     ALOGD("markValue=%d", markValue);
906     ALOGD("markMask=%d", markMask);
907     ALOGD("msgType=%d", msgType);
908     ALOGD("xfrmInterfaceId=%d", xfrmInterfaceId);
909 
910     XfrmSpInfo spInfo{};
911     spInfo.mode = XfrmMode::TUNNEL;
912 
913     XfrmSocketImpl sock;
914     RETURN_IF_NOT_OK(sock.open());
915 
916     // Set the correct address families. Tunnel mode policies use wildcard selectors, while
917     // templates have addresses set. These may be different address families. This method is called
918     // separately for IPv4 and IPv6 policies, and thus only need to map a single inner address
919     // family to the outer address families.
920     spInfo.selAddrFamily = selAddrFamily;
921     spInfo.direction = static_cast<XfrmDirection>(direction);
922 
923     if (msgType == XFRM_MSG_DELPOLICY) {
924         RETURN_IF_NOT_OK(fillXfrmCommonInfo(spi, markValue, markMask, transformId, xfrmInterfaceId,
925                                             &spInfo));
926 
927         return deleteTunnelModeSecurityPolicy(spInfo, sock);
928     } else {
929         RETURN_IF_NOT_OK(fillXfrmCommonInfo(tmplSrcAddress, tmplDstAddress, spi, markValue,
930                                             markMask, transformId, xfrmInterfaceId, &spInfo));
931 
932         return updateTunnelModeSecurityPolicy(spInfo, sock, msgType);
933     }
934 }
935 
fillXfrmSelector(const int selAddrFamily,xfrm_selector * selector)936 void XfrmController::fillXfrmSelector(const int selAddrFamily, xfrm_selector* selector) {
937     selector->family = selAddrFamily;
938     selector->proto = AF_UNSPEC; // TODO: do we need to match the protocol? it's
939                                  // possible via the socket
940 }
941 
updateSecurityAssociation(const XfrmSaInfo & record,const XfrmSocket & sock)942 netdutils::Status XfrmController::updateSecurityAssociation(const XfrmSaInfo& record,
943                                                             const XfrmSocket& sock) {
944     xfrm_usersa_info usersa{};
945     nlattr_algo_crypt crypt{};
946     nlattr_algo_auth auth{};
947     nlattr_algo_aead aead{};
948     nlattr_xfrm_mark xfrmmark{};
949     nlattr_xfrm_output_mark xfrmoutputmark{};
950     nlattr_encap_tmpl encap{};
951     nlattr_xfrm_interface_id xfrm_if_id{};
952 
953     enum {
954         NLMSG_HDR,
955         USERSA,
956         USERSA_PAD,
957         CRYPT,
958         CRYPT_PAD,
959         AUTH,
960         AUTH_PAD,
961         AEAD,
962         AEAD_PAD,
963         MARK,
964         MARK_PAD,
965         OUTPUT_MARK,
966         OUTPUT_MARK_PAD,
967         ENCAP,
968         ENCAP_PAD,
969         INTF_ID,
970         INTF_ID_PAD,
971     };
972 
973     std::vector<iovec> iov = {
974             {nullptr, 0},          // reserved for the eventual addition of a NLMSG_HDR
975             {&usersa, 0},          // main usersa_info struct
976             {kPadBytes, 0},        // up to NLMSG_ALIGNTO pad bytes of padding
977             {&crypt, 0},           // adjust size if crypt algo is present
978             {kPadBytes, 0},        // up to NLATTR_ALIGNTO pad bytes
979             {&auth, 0},            // adjust size if auth algo is present
980             {kPadBytes, 0},        // up to NLATTR_ALIGNTO pad bytes
981             {&aead, 0},            // adjust size if aead algo is present
982             {kPadBytes, 0},        // up to NLATTR_ALIGNTO pad bytes
983             {&xfrmmark, 0},        // adjust size if xfrm mark is present
984             {kPadBytes, 0},        // up to NLATTR_ALIGNTO pad bytes
985             {&xfrmoutputmark, 0},  // adjust size if xfrm output mark is present
986             {kPadBytes, 0},        // up to NLATTR_ALIGNTO pad bytes
987             {&encap, 0},           // adjust size if encapsulating
988             {kPadBytes, 0},        // up to NLATTR_ALIGNTO pad bytes
989             {&xfrm_if_id, 0},      // adjust size if interface ID is present
990             {kPadBytes, 0},        // up to NLATTR_ALIGNTO pad bytes
991     };
992 
993     if (!record.aead.name.empty() && (!record.auth.name.empty() || !record.crypt.name.empty())) {
994         return netdutils::statusFromErrno(EINVAL, "Invalid xfrm algo selection; AEAD is mutually "
995                                                   "exclusive with both Authentication and "
996                                                   "Encryption");
997     }
998 
999     if (record.aead.key.size() > MAX_KEY_LENGTH || record.auth.key.size() > MAX_KEY_LENGTH ||
1000         record.crypt.key.size() > MAX_KEY_LENGTH) {
1001         return netdutils::statusFromErrno(EINVAL, "Key length invalid; exceeds MAX_KEY_LENGTH");
1002     }
1003 
1004     if (record.mode != XfrmMode::TUNNEL &&
1005         (record.xfrm_if_id != 0 || record.netId != 0 || record.mark.v != 0 || record.mark.m != 0)) {
1006         return netdutils::statusFromErrno(EINVAL,
1007                                           "xfrm_if_id, mark and netid parameters invalid "
1008                                           "for non tunnel-mode transform");
1009     } else if (record.mode == XfrmMode::TUNNEL && !mIsXfrmIntfSupported && record.xfrm_if_id != 0) {
1010         return netdutils::statusFromErrno(EINVAL, "xfrm_if_id set for VTI Security Association");
1011     }
1012 
1013     int len;
1014     len = iov[USERSA].iov_len = fillUserSaInfo(record, &usersa);
1015     iov[USERSA_PAD].iov_len = NLMSG_ALIGN(len) - len;
1016 
1017     len = iov[CRYPT].iov_len = fillNlAttrXfrmAlgoEnc(record.crypt, &crypt);
1018     iov[CRYPT_PAD].iov_len = NLA_ALIGN(len) - len;
1019 
1020     len = iov[AUTH].iov_len = fillNlAttrXfrmAlgoAuth(record.auth, &auth);
1021     iov[AUTH_PAD].iov_len = NLA_ALIGN(len) - len;
1022 
1023     len = iov[AEAD].iov_len = fillNlAttrXfrmAlgoAead(record.aead, &aead);
1024     iov[AEAD_PAD].iov_len = NLA_ALIGN(len) - len;
1025 
1026     len = iov[MARK].iov_len = fillNlAttrXfrmMark(record, &xfrmmark);
1027     iov[MARK_PAD].iov_len = NLA_ALIGN(len) - len;
1028 
1029     len = iov[OUTPUT_MARK].iov_len = fillNlAttrXfrmOutputMark(record, &xfrmoutputmark);
1030     iov[OUTPUT_MARK_PAD].iov_len = NLA_ALIGN(len) - len;
1031 
1032     len = iov[ENCAP].iov_len = fillNlAttrXfrmEncapTmpl(record, &encap);
1033     iov[ENCAP_PAD].iov_len = NLA_ALIGN(len) - len;
1034 
1035     len = iov[INTF_ID].iov_len = fillNlAttrXfrmIntfId(record.xfrm_if_id, &xfrm_if_id);
1036     iov[INTF_ID_PAD].iov_len = NLA_ALIGN(len) - len;
1037 
1038     return sock.sendMessage(XFRM_MSG_UPDSA, NETLINK_REQUEST_FLAGS, 0, &iov);
1039 }
1040 
fillNlAttrXfrmAlgoEnc(const XfrmAlgo & inAlgo,nlattr_algo_crypt * algo)1041 int XfrmController::fillNlAttrXfrmAlgoEnc(const XfrmAlgo& inAlgo, nlattr_algo_crypt* algo) {
1042     if (inAlgo.name.empty()) { // Do not fill anything if algorithm not provided
1043         return 0;
1044     }
1045 
1046     int len = NLA_HDRLEN + sizeof(xfrm_algo);
1047     // Kernel always changes last char to null terminator; no safety checks needed.
1048     strncpy(algo->crypt.alg_name, inAlgo.name.c_str(), sizeof(algo->crypt.alg_name));
1049     algo->crypt.alg_key_len = inAlgo.key.size() * 8; // bits
1050     memcpy(algo->key, &inAlgo.key[0], inAlgo.key.size());
1051     len += inAlgo.key.size();
1052     fillXfrmNlaHdr(&algo->hdr, XFRMA_ALG_CRYPT, len);
1053     return len;
1054 }
1055 
fillNlAttrXfrmAlgoAuth(const XfrmAlgo & inAlgo,nlattr_algo_auth * algo)1056 int XfrmController::fillNlAttrXfrmAlgoAuth(const XfrmAlgo& inAlgo, nlattr_algo_auth* algo) {
1057     if (inAlgo.name.empty()) { // Do not fill anything if algorithm not provided
1058         return 0;
1059     }
1060 
1061     int len = NLA_HDRLEN + sizeof(xfrm_algo_auth);
1062     // Kernel always changes last char to null terminator; no safety checks needed.
1063     strncpy(algo->auth.alg_name, inAlgo.name.c_str(), sizeof(algo->auth.alg_name));
1064     algo->auth.alg_key_len = inAlgo.key.size() * 8; // bits
1065 
1066     // This is the extra field for ALG_AUTH_TRUNC
1067     algo->auth.alg_trunc_len = inAlgo.truncLenBits;
1068 
1069     memcpy(algo->key, &inAlgo.key[0], inAlgo.key.size());
1070     len += inAlgo.key.size();
1071 
1072     fillXfrmNlaHdr(&algo->hdr, XFRMA_ALG_AUTH_TRUNC, len);
1073     return len;
1074 }
1075 
fillNlAttrXfrmAlgoAead(const XfrmAlgo & inAlgo,nlattr_algo_aead * algo)1076 int XfrmController::fillNlAttrXfrmAlgoAead(const XfrmAlgo& inAlgo, nlattr_algo_aead* algo) {
1077     if (inAlgo.name.empty()) { // Do not fill anything if algorithm not provided
1078         return 0;
1079     }
1080 
1081     int len = NLA_HDRLEN + sizeof(xfrm_algo_aead);
1082     // Kernel always changes last char to null terminator; no safety checks needed.
1083     strncpy(algo->aead.alg_name, inAlgo.name.c_str(), sizeof(algo->aead.alg_name));
1084     algo->aead.alg_key_len = inAlgo.key.size() * 8; // bits
1085 
1086     // This is the extra field for ALG_AEAD. ICV length is the same as truncation length
1087     // for any AEAD algorithm.
1088     algo->aead.alg_icv_len = inAlgo.truncLenBits;
1089 
1090     memcpy(algo->key, &inAlgo.key[0], inAlgo.key.size());
1091     len += inAlgo.key.size();
1092 
1093     fillXfrmNlaHdr(&algo->hdr, XFRMA_ALG_AEAD, len);
1094     return len;
1095 }
1096 
fillNlAttrXfrmEncapTmpl(const XfrmSaInfo & record,nlattr_encap_tmpl * tmpl)1097 int XfrmController::fillNlAttrXfrmEncapTmpl(const XfrmSaInfo& record, nlattr_encap_tmpl* tmpl) {
1098     if (record.encap.type == XfrmEncapType::NONE) {
1099         return 0;
1100     }
1101 
1102     int len = NLA_HDRLEN + sizeof(xfrm_encap_tmpl);
1103     tmpl->tmpl.encap_type = static_cast<uint16_t>(record.encap.type);
1104     tmpl->tmpl.encap_sport = htons(record.encap.srcPort);
1105     tmpl->tmpl.encap_dport = htons(record.encap.dstPort);
1106     fillXfrmNlaHdr(&tmpl->hdr, XFRMA_ENCAP, len);
1107     return len;
1108 }
1109 
fillUserSaInfo(const XfrmSaInfo & record,xfrm_usersa_info * usersa)1110 int XfrmController::fillUserSaInfo(const XfrmSaInfo& record, xfrm_usersa_info* usersa) {
1111     // Use AF_UNSPEC for all SAs. In transport mode, kernel picks selector family based on
1112     // usersa->family, while in tunnel mode, the XFRM_STATE_AF_UNSPEC flag allows dual-stack SAs.
1113     fillXfrmSelector(AF_UNSPEC, &usersa->sel);
1114 
1115     usersa->id.proto = IPPROTO_ESP;
1116     usersa->id.spi = record.spi;
1117     usersa->id.daddr = record.dstAddr;
1118 
1119     usersa->saddr = record.srcAddr;
1120 
1121     fillXfrmLifetimeDefaults(&usersa->lft);
1122     fillXfrmCurLifetimeDefaults(&usersa->curlft);
1123     memset(&usersa->stats, 0, sizeof(usersa->stats)); // leave stats zeroed out
1124     usersa->reqid = record.transformId;
1125     usersa->family = record.addrFamily;
1126     usersa->mode = static_cast<uint8_t>(record.mode);
1127     usersa->replay_window = REPLAY_WINDOW_SIZE;
1128 
1129     if (record.mode == XfrmMode::TRANSPORT) {
1130         usersa->flags = 0; // TODO: should we actually set flags, XFRM_SA_XFLAG_DONT_ENCAP_DSCP?
1131     } else {
1132         usersa->flags = XFRM_STATE_AF_UNSPEC;
1133     }
1134 
1135     return sizeof(*usersa);
1136 }
1137 
fillUserSaId(const XfrmCommonInfo & record,xfrm_usersa_id * said)1138 int XfrmController::fillUserSaId(const XfrmCommonInfo& record, xfrm_usersa_id* said) {
1139     said->daddr = record.dstAddr;
1140     said->spi = record.spi;
1141     said->family = record.addrFamily;
1142     said->proto = IPPROTO_ESP;
1143 
1144     return sizeof(*said);
1145 }
1146 
deleteSecurityAssociation(const XfrmCommonInfo & record,const XfrmSocket & sock)1147 netdutils::Status XfrmController::deleteSecurityAssociation(const XfrmCommonInfo& record,
1148                                                             const XfrmSocket& sock) {
1149     xfrm_usersa_id said{};
1150     nlattr_xfrm_mark xfrmmark{};
1151     nlattr_xfrm_interface_id xfrm_if_id{};
1152 
1153     enum { NLMSG_HDR, USERSAID, USERSAID_PAD, MARK, MARK_PAD, INTF_ID, INTF_ID_PAD };
1154 
1155     std::vector<iovec> iov = {
1156             {nullptr, 0},      // reserved for the eventual addition of a NLMSG_HDR
1157             {&said, 0},        // main usersa_info struct
1158             {kPadBytes, 0},    // up to NLMSG_ALIGNTO pad bytes of padding
1159             {&xfrmmark, 0},    // adjust size if xfrm mark is present
1160             {kPadBytes, 0},    // up to NLATTR_ALIGNTO pad bytes
1161             {&xfrm_if_id, 0},  // adjust size if interface ID is present
1162             {kPadBytes, 0},    // up to NLATTR_ALIGNTO pad bytes
1163     };
1164 
1165     int len;
1166     len = iov[USERSAID].iov_len = fillUserSaId(record, &said);
1167     iov[USERSAID_PAD].iov_len = NLMSG_ALIGN(len) - len;
1168 
1169     len = iov[MARK].iov_len = fillNlAttrXfrmMark(record, &xfrmmark);
1170     iov[MARK_PAD].iov_len = NLA_ALIGN(len) - len;
1171 
1172     len = iov[INTF_ID].iov_len = fillNlAttrXfrmIntfId(record.xfrm_if_id, &xfrm_if_id);
1173     iov[INTF_ID_PAD].iov_len = NLA_ALIGN(len) - len;
1174 
1175     return sock.sendMessage(XFRM_MSG_DELSA, NETLINK_REQUEST_FLAGS, 0, &iov);
1176 }
1177 
migrate(const XfrmMigrateInfo & record,const XfrmSocket & sock)1178 netdutils::Status XfrmController::migrate(const XfrmMigrateInfo& record, const XfrmSocket& sock) {
1179     xfrm_userpolicy_id xfrm_policyid{};
1180     nlattr_xfrm_user_migrate xfrm_migrate{};
1181 
1182     __kernel_size_t lenPolicyId = fillUserPolicyId(record, &xfrm_policyid);
1183     __kernel_size_t lenXfrmMigrate = fillNlAttrXfrmMigrate(record, &xfrm_migrate);
1184 
1185     std::vector<iovec> iov = {
1186             {nullptr, 0},  // reserved for the eventual addition of a NLMSG_HDR
1187             {&xfrm_policyid, lenPolicyId},
1188             {kPadBytes, NLMSG_ALIGN(lenPolicyId) - lenPolicyId},
1189             {&xfrm_migrate, lenXfrmMigrate},
1190             {kPadBytes, NLMSG_ALIGN(lenXfrmMigrate) - lenXfrmMigrate},
1191     };
1192 
1193     return sock.sendMessage(XFRM_MSG_MIGRATE, NETLINK_REQUEST_FLAGS, 0, &iov);
1194 }
1195 
allocateSpi(const XfrmSaInfo & record,uint32_t minSpi,uint32_t maxSpi,uint32_t * outSpi,const XfrmSocket & sock)1196 netdutils::Status XfrmController::allocateSpi(const XfrmSaInfo& record, uint32_t minSpi,
1197                                               uint32_t maxSpi, uint32_t* outSpi,
1198                                               const XfrmSocket& sock) {
1199     xfrm_userspi_info spiInfo{};
1200 
1201     enum { NLMSG_HDR, USERSAID, USERSAID_PAD };
1202 
1203     std::vector<iovec> iov = {
1204         {nullptr, 0},      // reserved for the eventual addition of a NLMSG_HDR
1205         {&spiInfo, 0},  // main userspi_info struct
1206         {kPadBytes, 0}, // up to NLMSG_ALIGNTO pad bytes of padding
1207     };
1208 
1209     int len;
1210     if (fillUserSaInfo(record, &spiInfo.info) == 0) {
1211         ALOGE("Failed to fill transport SA Info");
1212     }
1213 
1214     len = iov[USERSAID].iov_len = sizeof(spiInfo);
1215     iov[USERSAID_PAD].iov_len = NLMSG_ALIGN(len) - len;
1216 
1217     RandomSpi spiGen = RandomSpi(minSpi, maxSpi);
1218     int spi;
1219     netdutils::Status ret;
1220     while ((spi = spiGen.next()) != INVALID_SPI) {
1221         spiInfo.min = spi;
1222         spiInfo.max = spi;
1223         ret = sock.sendMessage(XFRM_MSG_ALLOCSPI, NETLINK_REQUEST_FLAGS, 0, &iov);
1224 
1225         /* If the SPI is in use, we'll get ENOENT */
1226         if (netdutils::equalToErrno(ret, ENOENT))
1227             continue;
1228 
1229         if (isOk(ret)) {
1230             *outSpi = spi;
1231             ALOGD("Allocated an SPI: %x", *outSpi);
1232         } else {
1233             *outSpi = INVALID_SPI;
1234             ALOGE("SPI Allocation Failed with error %d", ret.code());
1235         }
1236 
1237         return ret;
1238     }
1239 
1240     // Should always be -ENOENT if we get here
1241     return ret;
1242 }
1243 
updateTunnelModeSecurityPolicy(const XfrmSpInfo & record,const XfrmSocket & sock,uint16_t msgType)1244 netdutils::Status XfrmController::updateTunnelModeSecurityPolicy(const XfrmSpInfo& record,
1245                                                                  const XfrmSocket& sock,
1246                                                                  uint16_t msgType) {
1247     xfrm_userpolicy_info userpolicy{};
1248     nlattr_user_tmpl usertmpl{};
1249     nlattr_xfrm_mark xfrmmark{};
1250     nlattr_xfrm_interface_id xfrm_if_id{};
1251 
1252     enum {
1253         NLMSG_HDR,
1254         USERPOLICY,
1255         USERPOLICY_PAD,
1256         USERTMPL,
1257         USERTMPL_PAD,
1258         MARK,
1259         MARK_PAD,
1260         INTF_ID,
1261         INTF_ID_PAD,
1262     };
1263 
1264     std::vector<iovec> iov = {
1265             {nullptr, 0},      // reserved for the eventual addition of a NLMSG_HDR
1266             {&userpolicy, 0},  // main xfrm_userpolicy_info struct
1267             {kPadBytes, 0},    // up to NLMSG_ALIGNTO pad bytes of padding
1268             {&usertmpl, 0},    // adjust size if xfrm_user_tmpl struct is present
1269             {kPadBytes, 0},    // up to NLATTR_ALIGNTO pad bytes
1270             {&xfrmmark, 0},    // adjust size if xfrm mark is present
1271             {kPadBytes, 0},    // up to NLATTR_ALIGNTO pad bytes
1272             {&xfrm_if_id, 0},  // adjust size if interface ID is present
1273             {kPadBytes, 0},    // up to NLATTR_ALIGNTO pad bytes
1274     };
1275 
1276     int len;
1277     len = iov[USERPOLICY].iov_len = fillUserSpInfo(record, &userpolicy);
1278     iov[USERPOLICY_PAD].iov_len = NLMSG_ALIGN(len) - len;
1279 
1280     len = iov[USERTMPL].iov_len = fillNlAttrUserTemplate(record, &usertmpl);
1281     iov[USERTMPL_PAD].iov_len = NLA_ALIGN(len) - len;
1282 
1283     len = iov[MARK].iov_len = fillNlAttrXfrmMark(record, &xfrmmark);
1284     iov[MARK_PAD].iov_len = NLA_ALIGN(len) - len;
1285 
1286     len = iov[INTF_ID].iov_len = fillNlAttrXfrmIntfId(record.xfrm_if_id, &xfrm_if_id);
1287     iov[INTF_ID_PAD].iov_len = NLA_ALIGN(len) - len;
1288 
1289     return sock.sendMessage(msgType, NETLINK_REQUEST_FLAGS, 0, &iov);
1290 }
1291 
deleteTunnelModeSecurityPolicy(const XfrmSpInfo & record,const XfrmSocket & sock)1292 netdutils::Status XfrmController::deleteTunnelModeSecurityPolicy(const XfrmSpInfo& record,
1293                                                                  const XfrmSocket& sock) {
1294     xfrm_userpolicy_id policyid{};
1295     nlattr_xfrm_mark xfrmmark{};
1296     nlattr_xfrm_interface_id xfrm_if_id{};
1297 
1298     enum {
1299         NLMSG_HDR,
1300         USERPOLICYID,
1301         USERPOLICYID_PAD,
1302         MARK,
1303         MARK_PAD,
1304         INTF_ID,
1305         INTF_ID_PAD,
1306     };
1307 
1308     std::vector<iovec> iov = {
1309             {nullptr, 0},      // reserved for the eventual addition of a NLMSG_HDR
1310             {&policyid, 0},    // main xfrm_userpolicy_id struct
1311             {kPadBytes, 0},    // up to NLMSG_ALIGNTO pad bytes of padding
1312             {&xfrmmark, 0},    // adjust size if xfrm mark is present
1313             {kPadBytes, 0},    // up to NLATTR_ALIGNTO pad bytes
1314             {&xfrm_if_id, 0},  // adjust size if interface ID is present
1315             {kPadBytes, 0},    // up to NLATTR_ALIGNTO pad bytes
1316     };
1317 
1318     int len = iov[USERPOLICYID].iov_len = fillUserPolicyId(record, &policyid);
1319     iov[USERPOLICYID_PAD].iov_len = NLMSG_ALIGN(len) - len;
1320 
1321     len = iov[MARK].iov_len = fillNlAttrXfrmMark(record, &xfrmmark);
1322     iov[MARK_PAD].iov_len = NLA_ALIGN(len) - len;
1323 
1324     len = iov[INTF_ID].iov_len = fillNlAttrXfrmIntfId(record.xfrm_if_id, &xfrm_if_id);
1325     iov[INTF_ID_PAD].iov_len = NLA_ALIGN(len) - len;
1326 
1327     return sock.sendMessage(XFRM_MSG_DELPOLICY, NETLINK_REQUEST_FLAGS, 0, &iov);
1328 }
1329 
fillUserSpInfo(const XfrmSpInfo & record,xfrm_userpolicy_info * usersp)1330 int XfrmController::fillUserSpInfo(const XfrmSpInfo& record, xfrm_userpolicy_info* usersp) {
1331     fillXfrmSelector(record.selAddrFamily, &usersp->sel);
1332     fillXfrmLifetimeDefaults(&usersp->lft);
1333     fillXfrmCurLifetimeDefaults(&usersp->curlft);
1334     /* if (index) index & 0x3 == dir -- must be true
1335      * xfrm_user.c:verify_newpolicy_info() */
1336     usersp->index = 0;
1337     usersp->dir = static_cast<uint8_t>(record.direction);
1338     usersp->action = XFRM_POLICY_ALLOW;
1339     usersp->flags = XFRM_POLICY_LOCALOK;
1340     usersp->share = XFRM_SHARE_UNIQUE;
1341     return sizeof(*usersp);
1342 }
1343 
fillUserTemplate(const XfrmSpInfo & record,xfrm_user_tmpl * tmpl)1344 void XfrmController::fillUserTemplate(const XfrmSpInfo& record, xfrm_user_tmpl* tmpl) {
1345     tmpl->id.daddr = record.dstAddr;
1346     tmpl->id.spi = record.spi;
1347     tmpl->id.proto = IPPROTO_ESP;
1348 
1349     tmpl->family = record.addrFamily;
1350     tmpl->saddr = record.srcAddr;
1351     tmpl->reqid = record.transformId;
1352     tmpl->mode = static_cast<uint8_t>(record.mode);
1353     tmpl->share = XFRM_SHARE_UNIQUE;
1354     tmpl->optional = 0; // if this is true, then a failed state lookup will be considered OK:
1355                         // http://lxr.free-electrons.com/source/net/xfrm/xfrm_policy.c#L1492
1356     tmpl->aalgos = ALGO_MASK_AUTH_ALL;  // TODO: if there's a bitmask somewhere of
1357                                         // algos, we should find it and apply it.
1358                                         // I can't find one.
1359     tmpl->ealgos = ALGO_MASK_CRYPT_ALL; // TODO: if there's a bitmask somewhere...
1360 }
1361 
fillNlAttrUserTemplate(const XfrmSpInfo & record,nlattr_user_tmpl * tmpl)1362 int XfrmController::fillNlAttrUserTemplate(const XfrmSpInfo& record, nlattr_user_tmpl* tmpl) {
1363     fillUserTemplate(record, &tmpl->tmpl);
1364 
1365     int len = NLA_HDRLEN + sizeof(xfrm_user_tmpl);
1366     fillXfrmNlaHdr(&tmpl->hdr, XFRMA_TMPL, len);
1367     return len;
1368 }
1369 
fillNlAttrXfrmMark(const XfrmCommonInfo & record,nlattr_xfrm_mark * mark)1370 int XfrmController::fillNlAttrXfrmMark(const XfrmCommonInfo& record, nlattr_xfrm_mark* mark) {
1371     // Do not set if we were not given a mark
1372     if (record.mark.v == 0 && record.mark.m == 0) {
1373         return 0;
1374     }
1375 
1376     mark->mark.v = record.mark.v; // set to 0 if it's not used
1377     mark->mark.m = record.mark.m; // set to 0 if it's not used
1378     int len = NLA_HDRLEN + sizeof(xfrm_mark);
1379     fillXfrmNlaHdr(&mark->hdr, XFRMA_MARK, len);
1380     return len;
1381 }
1382 
1383 // This function sets the output mark (or set-mark in newer kernels) to that of the underlying
1384 // Network's netid. This allows outbound IPsec Tunnel mode packets to be correctly directed to a
1385 // preselected underlying Network. Outbound packets are marked as protected from VPNs and have a
1386 // network explicitly selected to prevent interference or routing loops. Also sets permission flag
1387 // to PERMISSION_SYSTEM to allow use of background/restricted networks. Inbound packets have all
1388 // the flags and fields cleared to simulate the decapsulated packet being a fresh, unseen packet.
fillNlAttrXfrmOutputMark(const XfrmSaInfo & record,nlattr_xfrm_output_mark * output_mark)1389 int XfrmController::fillNlAttrXfrmOutputMark(const XfrmSaInfo& record,
1390                                              nlattr_xfrm_output_mark* output_mark) {
1391     // Only set for tunnel mode transforms
1392     if (record.mode != XfrmMode::TUNNEL) {
1393         return 0;
1394     }
1395 
1396     Fwmark fwmark;
1397 
1398     // Only outbound transforms have an underlying network set.
1399     if (record.netId != 0) {
1400         fwmark.netId = record.netId;
1401         fwmark.permission = PERMISSION_SYSTEM;
1402         fwmark.explicitlySelected = true;
1403         fwmark.protectedFromVpn = true;
1404     }
1405 
1406     // Else (inbound transforms), reset to default mark (empty); UID billing for inbound tunnel mode
1407     // transforms are exclusively done on inner packet, and therefore can never have been set.
1408 
1409     output_mark->outputMark = fwmark.intValue;
1410 
1411     int len = NLA_HDRLEN + sizeof(__u32);
1412     fillXfrmNlaHdr(&output_mark->hdr, XFRMA_OUTPUT_MARK, len);
1413     return len;
1414 }
1415 
fillNlAttrXfrmIntfId(const uint32_t intfIdValue,nlattr_xfrm_interface_id * intf_id)1416 int XfrmController::fillNlAttrXfrmIntfId(const uint32_t intfIdValue,
1417                                          nlattr_xfrm_interface_id* intf_id) {
1418     // Do not set if we were not given an interface id
1419     if (intfIdValue == 0) {
1420         return 0;
1421     }
1422 
1423     intf_id->if_id = intfIdValue;
1424     int len = NLA_HDRLEN + sizeof(__u32);
1425     fillXfrmNlaHdr(&intf_id->hdr, XFRMA_IF_ID, len);
1426     return len;
1427 }
1428 
fillNlAttrXfrmMigrate(const XfrmMigrateInfo & record,nlattr_xfrm_user_migrate * migrate)1429 int XfrmController::fillNlAttrXfrmMigrate(const XfrmMigrateInfo& record,
1430                                           nlattr_xfrm_user_migrate* migrate) {
1431     migrate->migrate.old_daddr = record.dstAddr;
1432     migrate->migrate.old_saddr = record.srcAddr;
1433     migrate->migrate.new_daddr = record.newEndpointInfo.dstAddr;
1434     migrate->migrate.new_saddr = record.newEndpointInfo.srcAddr;
1435     migrate->migrate.proto = IPPROTO_ESP;
1436     migrate->migrate.mode = static_cast<uint8_t>(XfrmMode::TUNNEL);
1437     migrate->migrate.reqid = record.transformId;
1438     migrate->migrate.old_family = record.addrFamily;
1439     migrate->migrate.new_family = record.newEndpointInfo.addrFamily;
1440 
1441     int len = NLA_HDRLEN + sizeof(xfrm_user_migrate);
1442     fillXfrmNlaHdr(&migrate->hdr, XFRMA_MIGRATE, len);
1443 
1444     return len;
1445 }
1446 
fillUserPolicyId(const XfrmSpInfo & record,xfrm_userpolicy_id * usersp)1447 int XfrmController::fillUserPolicyId(const XfrmSpInfo& record, xfrm_userpolicy_id* usersp) {
1448     // For DELPOLICY, when index is absent, selector is needed to match the policy
1449     fillXfrmSelector(record.selAddrFamily, &usersp->sel);
1450     usersp->dir = static_cast<uint8_t>(record.direction);
1451     return sizeof(*usersp);
1452 }
1453 
ipSecAddTunnelInterface(const std::string & deviceName,const std::string & localAddress,const std::string & remoteAddress,int32_t ikey,int32_t okey,int32_t interfaceId,bool isUpdate)1454 netdutils::Status XfrmController::ipSecAddTunnelInterface(const std::string& deviceName,
1455                                                           const std::string& localAddress,
1456                                                           const std::string& remoteAddress,
1457                                                           int32_t ikey, int32_t okey,
1458                                                           int32_t interfaceId, bool isUpdate) {
1459     ALOGD("XfrmController::%s, line=%d", __FUNCTION__, __LINE__);
1460     ALOGD("deviceName=%s", deviceName.c_str());
1461     ALOGD("localAddress=%s", localAddress.c_str());
1462     ALOGD("remoteAddress=%s", remoteAddress.c_str());
1463     ALOGD("ikey=%0.8x", ikey);
1464     ALOGD("okey=%0.8x", okey);
1465     ALOGD("interfaceId=%0.8x", interfaceId);
1466     ALOGD("isUpdate=%d", isUpdate);
1467 
1468     uint16_t flags = isUpdate ? NETLINK_REQUEST_FLAGS : NETLINK_ROUTE_CREATE_FLAGS;
1469 
1470     if (mIsXfrmIntfSupported) {
1471         return ipSecAddXfrmInterface(deviceName, interfaceId, flags);
1472     } else {
1473         return ipSecAddVirtualTunnelInterface(deviceName, localAddress, remoteAddress, ikey, okey,
1474                                               flags);
1475     }
1476 }
1477 
ipSecAddXfrmInterface(const std::string & deviceName,int32_t interfaceId,uint16_t flags)1478 netdutils::Status XfrmController::ipSecAddXfrmInterface(const std::string& deviceName,
1479                                                         int32_t interfaceId, uint16_t flags) {
1480     ALOGD("XfrmController::%s, line=%d", __FUNCTION__, __LINE__);
1481 
1482     if (deviceName.empty()) {
1483         return netdutils::statusFromErrno(EINVAL, "XFRM Interface deviceName empty");
1484     }
1485 
1486     ifinfomsg ifInfoMsg{};
1487 
1488     struct XfrmIntfCreateReq {
1489         nlattr ifNameNla;
1490         char ifName[IFNAMSIZ];  // Already aligned
1491 
1492         nlattr linkInfoNla;
1493         struct LinkInfo {
1494             nlattr infoKindNla;
1495             char infoKind[INFO_KIND_MAX_LEN];  // Already aligned
1496 
1497             nlattr infoDataNla;
1498             struct InfoData {
1499                 nlattr xfrmLinkNla;
1500                 uint32_t xfrmLink;
1501 
1502                 nlattr xfrmIfIdNla;
1503                 uint32_t xfrmIfId;
1504             } infoData;  // Already aligned
1505 
1506         } linkInfo;  // Already aligned
1507     } xfrmIntfCreateReq{
1508             .ifNameNla =
1509                     {
1510                             .nla_len = RTA_LENGTH(IFNAMSIZ),
1511                             .nla_type = IFLA_IFNAME,
1512                     },
1513             // Update .ifName via strlcpy
1514 
1515             .linkInfoNla =
1516                     {
1517                             .nla_len = RTA_LENGTH(sizeof(XfrmIntfCreateReq::LinkInfo)),
1518                             .nla_type = IFLA_LINKINFO,
1519                     },
1520             .linkInfo = {.infoKindNla =
1521                                  {
1522                                          .nla_len = RTA_LENGTH(INFO_KIND_MAX_LEN),
1523                                          .nla_type = IFLA_INFO_KIND,
1524                                  },
1525                          // Update .infoKind via strlcpy
1526 
1527                          .infoDataNla =
1528                                  {
1529                                          .nla_len = RTA_LENGTH(
1530                                                  sizeof(XfrmIntfCreateReq::LinkInfo::InfoData)),
1531                                          .nla_type = IFLA_INFO_DATA,
1532                                  },
1533                          .infoData = {
1534                                  .xfrmLinkNla =
1535                                          {
1536                                                  .nla_len = RTA_LENGTH(sizeof(uint32_t)),
1537                                                  .nla_type = IFLA_XFRM_LINK,
1538                                          },
1539                                  //   Always use LOOPBACK_IFINDEX, since we use output marks for
1540                                  //   route lookup instead. The use case of having a Network with
1541                                  //   loopback in it is unsupported in tunnel mode.
1542                                  .xfrmLink = static_cast<uint32_t>(LOOPBACK_IFINDEX),
1543 
1544                                  .xfrmIfIdNla =
1545                                          {
1546                                                  .nla_len = RTA_LENGTH(sizeof(uint32_t)),
1547                                                  .nla_type = IFLA_XFRM_IF_ID,
1548                                          },
1549                                  .xfrmIfId = static_cast<uint32_t>(interfaceId),
1550                          }}};
1551 
1552     strlcpy(xfrmIntfCreateReq.ifName, deviceName.c_str(), IFNAMSIZ);
1553     strlcpy(xfrmIntfCreateReq.linkInfo.infoKind, INFO_KIND_XFRMI, INFO_KIND_MAX_LEN);
1554 
1555     iovec iov[] = {
1556             {NULL, 0},  // reserved for the eventual addition of a NLMSG_HDR
1557             {&ifInfoMsg, sizeof(ifInfoMsg)},
1558 
1559             {&xfrmIntfCreateReq, sizeof(xfrmIntfCreateReq)},
1560     };
1561 
1562     // sendNetlinkRequest returns -errno
1563     int ret = -sendNetlinkRequest(RTM_NEWLINK, flags, iov, ARRAY_SIZE(iov), nullptr);
1564     return netdutils::statusFromErrno(ret, "Add/update xfrm interface");
1565 }
1566 
ipSecAddVirtualTunnelInterface(const std::string & deviceName,const std::string & localAddress,const std::string & remoteAddress,int32_t ikey,int32_t okey,uint16_t flags)1567 netdutils::Status XfrmController::ipSecAddVirtualTunnelInterface(const std::string& deviceName,
1568                                                                  const std::string& localAddress,
1569                                                                  const std::string& remoteAddress,
1570                                                                  int32_t ikey, int32_t okey,
1571                                                                  uint16_t flags) {
1572     ALOGD("XfrmController::%s, line=%d", __FUNCTION__, __LINE__);
1573 
1574     if (deviceName.empty() || localAddress.empty() || remoteAddress.empty()) {
1575         return netdutils::statusFromErrno(EINVAL, "Required VTI creation parameter not provided");
1576     }
1577 
1578     uint8_t PADDING_BUFFER[] = {0, 0, 0, 0};
1579 
1580     // Find address family.
1581     uint8_t remAddr[sizeof(in6_addr)];
1582 
1583     StatusOr<uint16_t> statusOrRemoteFam = convertStringAddress(remoteAddress, remAddr);
1584     RETURN_IF_NOT_OK(statusOrRemoteFam);
1585 
1586     uint8_t locAddr[sizeof(in6_addr)];
1587     StatusOr<uint16_t> statusOrLocalFam = convertStringAddress(localAddress, locAddr);
1588     RETURN_IF_NOT_OK(statusOrLocalFam);
1589 
1590     if (statusOrLocalFam.value() != statusOrRemoteFam.value()) {
1591         return netdutils::statusFromErrno(EINVAL, "Local and remote address families do not match");
1592     }
1593 
1594     uint16_t family = statusOrLocalFam.value();
1595 
1596     ifinfomsg ifInfoMsg{};
1597 
1598     // Construct IFLA_IFNAME
1599     nlattr iflaIfName;
1600     char iflaIfNameStrValue[deviceName.length() + 1];
1601     size_t iflaIfNameLength =
1602         strlcpy(iflaIfNameStrValue, deviceName.c_str(), sizeof(iflaIfNameStrValue));
1603     size_t iflaIfNamePad = fillNlAttr(IFLA_IFNAME, iflaIfNameLength, &iflaIfName);
1604 
1605     // Construct IFLA_INFO_KIND
1606     // Constants "vti6" and "vti" enable the kernel to call different code paths,
1607     // (ip_tunnel.c, ip6_tunnel), based on the family.
1608     const std::string infoKindValue = (family == AF_INET6) ? INFO_KIND_VTI6 : INFO_KIND_VTI;
1609     nlattr iflaIfInfoKind;
1610     char infoKindValueStrValue[infoKindValue.length() + 1];
1611     size_t iflaIfInfoKindLength =
1612         strlcpy(infoKindValueStrValue, infoKindValue.c_str(), sizeof(infoKindValueStrValue));
1613     size_t iflaIfInfoKindPad = fillNlAttr(IFLA_INFO_KIND, iflaIfInfoKindLength, &iflaIfInfoKind);
1614 
1615     // Construct IFLA_VTI_LOCAL
1616     nlattr iflaVtiLocal;
1617     uint8_t binaryLocalAddress[sizeof(in6_addr)];
1618     size_t iflaVtiLocalPad =
1619         fillNlAttrIpAddress(IFLA_VTI_LOCAL, family, localAddress, &iflaVtiLocal,
1620                             netdutils::makeSlice(binaryLocalAddress));
1621 
1622     // Construct IFLA_VTI_REMOTE
1623     nlattr iflaVtiRemote;
1624     uint8_t binaryRemoteAddress[sizeof(in6_addr)];
1625     size_t iflaVtiRemotePad =
1626         fillNlAttrIpAddress(IFLA_VTI_REMOTE, family, remoteAddress, &iflaVtiRemote,
1627                             netdutils::makeSlice(binaryRemoteAddress));
1628 
1629     // Construct IFLA_VTI_OKEY
1630     nlattr_payload_u32 iflaVtiIKey;
1631     size_t iflaVtiIKeyPad = fillNlAttrU32(IFLA_VTI_IKEY, htonl(ikey), &iflaVtiIKey);
1632 
1633     // Construct IFLA_VTI_IKEY
1634     nlattr_payload_u32 iflaVtiOKey;
1635     size_t iflaVtiOKeyPad = fillNlAttrU32(IFLA_VTI_OKEY, htonl(okey), &iflaVtiOKey);
1636 
1637     int iflaInfoDataPayloadLength = iflaVtiLocal.nla_len + iflaVtiLocalPad + iflaVtiRemote.nla_len +
1638                                     iflaVtiRemotePad + iflaVtiIKey.hdr.nla_len + iflaVtiIKeyPad +
1639                                     iflaVtiOKey.hdr.nla_len + iflaVtiOKeyPad;
1640 
1641     // Construct IFLA_INFO_DATA
1642     nlattr iflaInfoData;
1643     size_t iflaInfoDataPad = fillNlAttr(IFLA_INFO_DATA, iflaInfoDataPayloadLength, &iflaInfoData);
1644 
1645     // Construct IFLA_LINKINFO
1646     nlattr iflaLinkInfo;
1647     size_t iflaLinkInfoPad = fillNlAttr(IFLA_LINKINFO,
1648                                         iflaInfoData.nla_len + iflaInfoDataPad +
1649                                             iflaIfInfoKind.nla_len + iflaIfInfoKindPad,
1650                                         &iflaLinkInfo);
1651 
1652     iovec iov[] = {
1653             {nullptr, 0},
1654             {&ifInfoMsg, sizeof(ifInfoMsg)},
1655 
1656             {&iflaIfName, sizeof(iflaIfName)},
1657             {iflaIfNameStrValue, iflaIfNameLength},
1658             {&PADDING_BUFFER, iflaIfNamePad},
1659 
1660             {&iflaLinkInfo, sizeof(iflaLinkInfo)},
1661 
1662             {&iflaIfInfoKind, sizeof(iflaIfInfoKind)},
1663             {infoKindValueStrValue, iflaIfInfoKindLength},
1664             {&PADDING_BUFFER, iflaIfInfoKindPad},
1665 
1666             {&iflaInfoData, sizeof(iflaInfoData)},
1667 
1668             {&iflaVtiLocal, sizeof(iflaVtiLocal)},
1669             {&binaryLocalAddress, (family == AF_INET) ? sizeof(in_addr) : sizeof(in6_addr)},
1670             {&PADDING_BUFFER, iflaVtiLocalPad},
1671 
1672             {&iflaVtiRemote, sizeof(iflaVtiRemote)},
1673             {&binaryRemoteAddress, (family == AF_INET) ? sizeof(in_addr) : sizeof(in6_addr)},
1674             {&PADDING_BUFFER, iflaVtiRemotePad},
1675 
1676             {&iflaVtiIKey, iflaVtiIKey.hdr.nla_len},
1677             {&PADDING_BUFFER, iflaVtiIKeyPad},
1678 
1679             {&iflaVtiOKey, iflaVtiOKey.hdr.nla_len},
1680             {&PADDING_BUFFER, iflaVtiOKeyPad},
1681 
1682             {&PADDING_BUFFER, iflaInfoDataPad},
1683 
1684             {&PADDING_BUFFER, iflaLinkInfoPad},
1685     };
1686 
1687     // sendNetlinkRequest returns -errno
1688     int ret = -1 * sendNetlinkRequest(RTM_NEWLINK, flags, iov, ARRAY_SIZE(iov), nullptr);
1689     return netdutils::statusFromErrno(ret, "Failed to add/update virtual tunnel interface");
1690 }
1691 
ipSecRemoveTunnelInterface(const std::string & deviceName)1692 netdutils::Status XfrmController::ipSecRemoveTunnelInterface(const std::string& deviceName) {
1693     ALOGD("XfrmController::%s, line=%d", __FUNCTION__, __LINE__);
1694     ALOGD("deviceName=%s", deviceName.c_str());
1695 
1696     if (deviceName.empty()) {
1697         return netdutils::statusFromErrno(EINVAL, "Required parameter not provided");
1698     }
1699 
1700     uint8_t PADDING_BUFFER[] = {0, 0, 0, 0};
1701 
1702     ifinfomsg ifInfoMsg{};
1703     nlattr iflaIfName;
1704     char iflaIfNameStrValue[deviceName.length() + 1];
1705     size_t iflaIfNameLength =
1706         strlcpy(iflaIfNameStrValue, deviceName.c_str(), sizeof(iflaIfNameStrValue));
1707     size_t iflaIfNamePad = fillNlAttr(IFLA_IFNAME, iflaIfNameLength, &iflaIfName);
1708 
1709     iovec iov[] = {
1710         {nullptr, 0},
1711         {&ifInfoMsg, sizeof(ifInfoMsg)},
1712 
1713         {&iflaIfName, sizeof(iflaIfName)},
1714         {iflaIfNameStrValue, iflaIfNameLength},
1715         {&PADDING_BUFFER, iflaIfNamePad},
1716     };
1717 
1718     uint16_t action = RTM_DELLINK;
1719     uint16_t flags = NLM_F_REQUEST | NLM_F_ACK;
1720 
1721     // sendNetlinkRequest returns -errno
1722     int ret = -1 * sendNetlinkRequest(action, flags, iov, ARRAY_SIZE(iov), nullptr);
1723     return netdutils::statusFromErrno(ret, "Error in deleting IpSec interface " + deviceName);
1724 }
1725 
dump(DumpWriter & dw)1726 void XfrmController::dump(DumpWriter& dw) {
1727     ScopedIndent indentForXfrmController(dw);
1728     dw.println("XfrmController");
1729 
1730     ScopedIndent indentForXfrmISupport(dw);
1731     dw.println("XFRM-I support: %d", mIsXfrmIntfSupported);
1732 }
1733 
1734 } // namespace net
1735 } // namespace android
1736