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