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