XfrmController.cpp 63 KB

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