blob: 996c9ec544fd9c2cce7e17ebd65d7ff3d48fa127 [file] [log] [blame]
Nathan Harold1a371532017-01-30 12:30:48 -08001/*
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 <string>
Nathan Harold1e284452017-10-10 13:31:19 -070019#include <random>
Nathan Harold1a371532017-01-30 12:30:48 -080020#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>
Nathan Harold420ceac2017-04-05 19:36:59 -070029
30#define __STDC_FORMAT_MACROS
Nathan Harold1a371532017-01-30 12:30:48 -080031#include <inttypes.h>
32
33#include <arpa/inet.h>
34#include <netinet/in.h>
35
36#include <sys/socket.h>
37#include <sys/stat.h>
38#include <sys/types.h>
39#include <sys/wait.h>
40
41#include <linux/in.h>
42#include <linux/netlink.h>
43#include <linux/xfrm.h>
44
45#include "android-base/stringprintf.h"
46#include "android-base/strings.h"
47#include "android-base/unique_fd.h"
Manojd9c93c22017-10-19 13:40:26 -070048#include <log/log_properties.h>
Nathan Harold1a371532017-01-30 12:30:48 -080049#define LOG_TAG "XfrmController"
50#include "NetdConstants.h"
51#include "NetlinkCommands.h"
52#include "ResponseCode.h"
53#include "XfrmController.h"
ludi4072ff22017-06-15 08:56:52 -070054#include "netdutils/Fd.h"
55#include "netdutils/Slice.h"
56#include "netdutils/Syscalls.h"
Nathan Harold1a371532017-01-30 12:30:48 -080057#include <cutils/log.h>
58#include <cutils/properties.h>
59#include <logwrap/logwrap.h>
60
ludi4072ff22017-06-15 08:56:52 -070061using android::netdutils::Fd;
62using android::netdutils::Slice;
63using android::netdutils::Status;
64using android::netdutils::StatusOr;
65using android::netdutils::Syscalls;
66
Nathan Harold1a371532017-01-30 12:30:48 -080067namespace android {
68namespace net {
69
Nathan Harold39b5df42017-08-02 18:45:25 -070070// Exposed for testing
Nathan Harold1a371532017-01-30 12:30:48 -080071constexpr uint32_t ALGO_MASK_AUTH_ALL = ~0;
Nathan Harold39b5df42017-08-02 18:45:25 -070072// Exposed for testing
Nathan Harold1a371532017-01-30 12:30:48 -080073constexpr uint32_t ALGO_MASK_CRYPT_ALL = ~0;
Nathan Harold39b5df42017-08-02 18:45:25 -070074// Exposed for testing
Benedict Wongbe65b432017-08-22 21:43:14 -070075constexpr uint32_t ALGO_MASK_AEAD_ALL = ~0;
76// Exposed for testing
Nathan Harold1a371532017-01-30 12:30:48 -080077constexpr uint8_t REPLAY_WINDOW_SIZE = 4;
78
Nathan Harold39b5df42017-08-02 18:45:25 -070079namespace {
80
Nathan Harold1a371532017-01-30 12:30:48 -080081constexpr uint32_t RAND_SPI_MIN = 1;
82constexpr uint32_t RAND_SPI_MAX = 0xFFFFFFFE;
83
84constexpr uint32_t INVALID_SPI = 0;
85
86#define XFRM_MSG_TRANS(x) \
87 case x: \
88 return #x;
89
90const char* xfrmMsgTypeToString(uint16_t msg) {
91 switch (msg) {
92 XFRM_MSG_TRANS(XFRM_MSG_NEWSA)
93 XFRM_MSG_TRANS(XFRM_MSG_DELSA)
94 XFRM_MSG_TRANS(XFRM_MSG_GETSA)
95 XFRM_MSG_TRANS(XFRM_MSG_NEWPOLICY)
96 XFRM_MSG_TRANS(XFRM_MSG_DELPOLICY)
97 XFRM_MSG_TRANS(XFRM_MSG_GETPOLICY)
98 XFRM_MSG_TRANS(XFRM_MSG_ALLOCSPI)
99 XFRM_MSG_TRANS(XFRM_MSG_ACQUIRE)
100 XFRM_MSG_TRANS(XFRM_MSG_EXPIRE)
101 XFRM_MSG_TRANS(XFRM_MSG_UPDPOLICY)
102 XFRM_MSG_TRANS(XFRM_MSG_UPDSA)
103 XFRM_MSG_TRANS(XFRM_MSG_POLEXPIRE)
104 XFRM_MSG_TRANS(XFRM_MSG_FLUSHSA)
105 XFRM_MSG_TRANS(XFRM_MSG_FLUSHPOLICY)
106 XFRM_MSG_TRANS(XFRM_MSG_NEWAE)
107 XFRM_MSG_TRANS(XFRM_MSG_GETAE)
108 XFRM_MSG_TRANS(XFRM_MSG_REPORT)
109 XFRM_MSG_TRANS(XFRM_MSG_MIGRATE)
110 XFRM_MSG_TRANS(XFRM_MSG_NEWSADINFO)
111 XFRM_MSG_TRANS(XFRM_MSG_GETSADINFO)
112 XFRM_MSG_TRANS(XFRM_MSG_GETSPDINFO)
113 XFRM_MSG_TRANS(XFRM_MSG_NEWSPDINFO)
114 XFRM_MSG_TRANS(XFRM_MSG_MAPPING)
115 default:
116 return "XFRM_MSG UNKNOWN";
117 }
118}
119
120// actually const but cannot be declared as such for reasons
121uint8_t kPadBytesArray[] = {0, 0, 0};
122void* kPadBytes = static_cast<void*>(kPadBytesArray);
123
Nathan Harold420ceac2017-04-05 19:36:59 -0700124#define LOG_HEX(__desc16__, __buf__, __len__) \
Manojd9c93c22017-10-19 13:40:26 -0700125 if (__android_log_is_debuggable()) { \
126 do { \
127 logHex(__desc16__, __buf__, __len__); \
128 } while (0); \
129 }
130
ludie51e3862017-08-15 19:28:12 -0700131#define LOG_IOV(__iov__) \
Manojd9c93c22017-10-19 13:40:26 -0700132 if (__android_log_is_debuggable()) { \
133 do { \
134 logIov(__iov__); \
135 } while (0); \
136 }
Nathan Harold1a371532017-01-30 12:30:48 -0800137
138void logHex(const char* desc16, const char* buf, size_t len) {
139 char* printBuf = new char[len * 2 + 1 + 26]; // len->ascii, +newline, +prefix strlen
140 int offset = 0;
141 if (desc16) {
142 sprintf(printBuf, "{%-16s}", desc16);
143 offset += 18; // prefix string length
144 }
145 sprintf(printBuf + offset, "[%4.4u]: ", (len > 9999) ? 9999 : (unsigned)len);
146 offset += 8;
147
148 for (uint32_t j = 0; j < (uint32_t)len; j++) {
149 sprintf(&printBuf[j * 2 + offset], "%0.2x", buf[j]);
150 }
151 ALOGD("%s", printBuf);
152 delete[] printBuf;
153}
154
ludie51e3862017-08-15 19:28:12 -0700155void logIov(const std::vector<iovec>& iov) {
156 for (const iovec& row : iov) {
157 logHex(0, reinterpret_cast<char*>(row.iov_base), row.iov_len);
Nathan Harold1a371532017-01-30 12:30:48 -0800158 }
159}
160
ludi6e8eccd2017-08-14 14:40:37 -0700161// TODO: Need to consider a way to refer to the sSycalls instance
ludi4072ff22017-06-15 08:56:52 -0700162inline Syscalls& getSyscallInstance() { return netdutils::sSyscalls.get(); }
163
Nathan Harold1a371532017-01-30 12:30:48 -0800164class XfrmSocketImpl : public XfrmSocket {
165private:
166 static constexpr int NLMSG_DEFAULTSIZE = 8192;
167
168 union NetlinkResponse {
169 nlmsghdr hdr;
170 struct _err_ {
171 nlmsghdr hdr;
172 nlmsgerr err;
173 } err;
174
175 struct _buf_ {
176 nlmsghdr hdr;
177 char buf[NLMSG_DEFAULTSIZE];
178 } buf;
179 };
180
181public:
ludi6e8eccd2017-08-14 14:40:37 -0700182 netdutils::Status open() override {
Nathan Harold1a371532017-01-30 12:30:48 -0800183 mSock = openNetlinkSocket(NETLINK_XFRM);
ludi6e8eccd2017-08-14 14:40:37 -0700184 if (mSock < 0) {
Nathan Harold1a371532017-01-30 12:30:48 -0800185 ALOGW("Could not get a new socket, line=%d", __LINE__);
ludi6e8eccd2017-08-14 14:40:37 -0700186 return netdutils::statusFromErrno(-mSock, "Could not open netlink socket");
Nathan Harold1a371532017-01-30 12:30:48 -0800187 }
188
ludi6e8eccd2017-08-14 14:40:37 -0700189 return netdutils::status::ok;
Nathan Harold1a371532017-01-30 12:30:48 -0800190 }
191
ludi6e8eccd2017-08-14 14:40:37 -0700192 static netdutils::Status validateResponse(NetlinkResponse response, size_t len) {
Nathan Harold1a371532017-01-30 12:30:48 -0800193 if (len < sizeof(nlmsghdr)) {
194 ALOGW("Invalid response message received over netlink");
ludi6e8eccd2017-08-14 14:40:37 -0700195 return netdutils::statusFromErrno(EBADMSG, "Invalid message");
Nathan Harold1a371532017-01-30 12:30:48 -0800196 }
197
198 switch (response.hdr.nlmsg_type) {
199 case NLMSG_NOOP:
200 case NLMSG_DONE:
ludi6e8eccd2017-08-14 14:40:37 -0700201 return netdutils::status::ok;
Nathan Harold1a371532017-01-30 12:30:48 -0800202 case NLMSG_OVERRUN:
203 ALOGD("Netlink request overran kernel buffer");
ludi6e8eccd2017-08-14 14:40:37 -0700204 return netdutils::statusFromErrno(EBADMSG, "Kernel buffer overrun");
Nathan Harold1a371532017-01-30 12:30:48 -0800205 case NLMSG_ERROR:
206 if (len < sizeof(NetlinkResponse::_err_)) {
207 ALOGD("Netlink message received malformed error response");
ludi6e8eccd2017-08-14 14:40:37 -0700208 return netdutils::statusFromErrno(EBADMSG, "Malformed error response");
Nathan Harold1a371532017-01-30 12:30:48 -0800209 }
ludi6e8eccd2017-08-14 14:40:37 -0700210 return netdutils::statusFromErrno(
211 -response.err.err.error,
212 "Error netlink message"); // Netlink errors are negative errno.
Nathan Harold1a371532017-01-30 12:30:48 -0800213 case XFRM_MSG_NEWSA:
214 break;
215 }
216
217 if (response.hdr.nlmsg_type < XFRM_MSG_BASE /*== NLMSG_MIN_TYPE*/ ||
218 response.hdr.nlmsg_type > XFRM_MSG_MAX) {
219 ALOGD("Netlink message responded with an out-of-range message ID");
ludi6e8eccd2017-08-14 14:40:37 -0700220 return netdutils::statusFromErrno(EBADMSG, "Invalid message ID");
Nathan Harold1a371532017-01-30 12:30:48 -0800221 }
222
223 // TODO Add more message validation here
ludi6e8eccd2017-08-14 14:40:37 -0700224 return netdutils::status::ok;
Nathan Harold1a371532017-01-30 12:30:48 -0800225 }
226
ludi6e8eccd2017-08-14 14:40:37 -0700227 netdutils::Status sendMessage(uint16_t nlMsgType, uint16_t nlMsgFlags, uint16_t nlMsgSeqNum,
228 std::vector<iovec>* iovecs) const override {
Nathan Harold1a371532017-01-30 12:30:48 -0800229 nlmsghdr nlMsg = {
230 .nlmsg_type = nlMsgType, .nlmsg_flags = nlMsgFlags, .nlmsg_seq = nlMsgSeqNum,
231 };
232
ludie51e3862017-08-15 19:28:12 -0700233 (*iovecs)[0].iov_base = &nlMsg;
234 (*iovecs)[0].iov_len = NLMSG_HDRLEN;
235 for (const iovec& iov : *iovecs) {
236 nlMsg.nlmsg_len += iov.iov_len;
Nathan Harold1a371532017-01-30 12:30:48 -0800237 }
238
239 ALOGD("Sending Netlink XFRM Message: %s", xfrmMsgTypeToString(nlMsgType));
Manojd9c93c22017-10-19 13:40:26 -0700240 LOG_IOV(*iovecs);
Nathan Harold1a371532017-01-30 12:30:48 -0800241
ludie51e3862017-08-15 19:28:12 -0700242 StatusOr<size_t> writeResult = getSyscallInstance().writev(mSock, *iovecs);
ludi4072ff22017-06-15 08:56:52 -0700243 if (!isOk(writeResult)) {
244 ALOGE("netlink socket writev failed (%s)", toString(writeResult).c_str());
ludi6e8eccd2017-08-14 14:40:37 -0700245 return writeResult;
Nathan Harold1a371532017-01-30 12:30:48 -0800246 }
247
ludi4072ff22017-06-15 08:56:52 -0700248 if (nlMsg.nlmsg_len != writeResult.value()) {
249 ALOGE("Invalid netlink message length sent %d", static_cast<int>(writeResult.value()));
ludi6e8eccd2017-08-14 14:40:37 -0700250 return netdutils::statusFromErrno(EBADMSG, "Invalid message length");
Nathan Harold1a371532017-01-30 12:30:48 -0800251 }
252
ludi4072ff22017-06-15 08:56:52 -0700253 NetlinkResponse response = {};
Nathan Harold1a371532017-01-30 12:30:48 -0800254
ludi4072ff22017-06-15 08:56:52 -0700255 StatusOr<Slice> readResult =
256 getSyscallInstance().read(Fd(mSock), netdutils::makeSlice(response));
257 if (!isOk(readResult)) {
258 ALOGE("netlink response error (%s)", toString(readResult).c_str());
ludi6e8eccd2017-08-14 14:40:37 -0700259 return readResult;
ludi4072ff22017-06-15 08:56:52 -0700260 }
261
262 LOG_HEX("netlink msg resp", reinterpret_cast<char*>(readResult.value().base()),
263 readResult.value().size());
264
ludi6e8eccd2017-08-14 14:40:37 -0700265 Status validateStatus = validateResponse(response, readResult.value().size());
266 if (!isOk(validateStatus)) {
267 ALOGE("netlink response contains error (%s)", toString(validateStatus).c_str());
268 }
269
270 return validateStatus;
Nathan Harold1a371532017-01-30 12:30:48 -0800271 }
272};
273
ludi6e8eccd2017-08-14 14:40:37 -0700274StatusOr<int> convertToXfrmAddr(const std::string& strAddr, xfrm_address_t* xfrmAddr) {
Nathan Harold1a371532017-01-30 12:30:48 -0800275 if (strAddr.length() == 0) {
276 memset(xfrmAddr, 0, sizeof(*xfrmAddr));
277 return AF_UNSPEC;
278 }
279
280 if (inet_pton(AF_INET6, strAddr.c_str(), reinterpret_cast<void*>(xfrmAddr))) {
281 return AF_INET6;
282 } else if (inet_pton(AF_INET, strAddr.c_str(), reinterpret_cast<void*>(xfrmAddr))) {
283 return AF_INET;
284 } else {
ludi6e8eccd2017-08-14 14:40:37 -0700285 return netdutils::statusFromErrno(EAFNOSUPPORT, "Invalid address family");
Nathan Harold1a371532017-01-30 12:30:48 -0800286 }
287}
288
289void fillXfrmNlaHdr(nlattr* hdr, uint16_t type, uint16_t len) {
290 hdr->nla_type = type;
291 hdr->nla_len = len;
292}
293
294void fillXfrmCurLifetimeDefaults(xfrm_lifetime_cur* cur) {
295 memset(reinterpret_cast<char*>(cur), 0, sizeof(*cur));
296}
297void fillXfrmLifetimeDefaults(xfrm_lifetime_cfg* cfg) {
298 cfg->soft_byte_limit = XFRM_INF;
299 cfg->hard_byte_limit = XFRM_INF;
300 cfg->soft_packet_limit = XFRM_INF;
301 cfg->hard_packet_limit = XFRM_INF;
302}
303
304/*
305 * Allocate SPIs within an (inclusive) range of min-max.
306 * returns 0 (INVALID_SPI) once the entire range has been parsed.
307 */
308class RandomSpi {
309public:
310 RandomSpi(int min, int max) : mMin(min) {
Nathan Harold1e284452017-10-10 13:31:19 -0700311 // Re-seeding should be safe because the seed itself is
312 // sufficiently random and we don't need secure random
313 std::mt19937 rnd = std::mt19937(std::random_device()());
314 mNext = std::uniform_int_distribution<>(1, INT_MAX)(rnd);
Nathan Harold1a371532017-01-30 12:30:48 -0800315 mSize = max - min + 1;
316 mCount = mSize;
317 }
318
319 uint32_t next() {
320 if (!mCount)
321 return 0;
322 mCount--;
323 return (mNext++ % mSize) + mMin;
324 }
325
326private:
327 uint32_t mNext;
328 uint32_t mSize;
329 uint32_t mMin;
330 uint32_t mCount;
331};
332
333} // namespace
334
335//
336// Begin XfrmController Impl
337//
338//
339XfrmController::XfrmController(void) {}
340
ludi6e8eccd2017-08-14 14:40:37 -0700341netdutils::Status XfrmController::ipSecAllocateSpi(int32_t transformId, int32_t direction,
342 const std::string& localAddress,
343 const std::string& remoteAddress, int32_t inSpi,
344 int32_t* outSpi) {
Nathan Harold1a371532017-01-30 12:30:48 -0800345 ALOGD("XfrmController:%s, line=%d", __FUNCTION__, __LINE__);
346 ALOGD("transformId=%d", transformId);
347 ALOGD("direction=%d", direction);
348 ALOGD("localAddress=%s", localAddress.c_str());
349 ALOGD("remoteAddress=%s", remoteAddress.c_str());
350 ALOGD("inSpi=%0.8x", inSpi);
351
352 XfrmSaInfo saInfo{};
Nathan Harold1a371532017-01-30 12:30:48 -0800353
ludi6e8eccd2017-08-14 14:40:37 -0700354 netdutils::Status ret =
355 fillXfrmSaId(direction, localAddress, remoteAddress, INVALID_SPI, &saInfo);
356 if (!isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800357 return ret;
358 }
359
360 XfrmSocketImpl sock;
ludi6e8eccd2017-08-14 14:40:37 -0700361 netdutils::Status socketStatus = sock.open();
362 if (!isOk(socketStatus)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800363 ALOGD("Sock open failed for XFRM, line=%d", __LINE__);
ludi6e8eccd2017-08-14 14:40:37 -0700364 return socketStatus;
Nathan Harold1a371532017-01-30 12:30:48 -0800365 }
366
367 int minSpi = RAND_SPI_MIN, maxSpi = RAND_SPI_MAX;
368
369 if (inSpi)
370 minSpi = maxSpi = inSpi;
ludi6e8eccd2017-08-14 14:40:37 -0700371
Nathan Harold1a371532017-01-30 12:30:48 -0800372 ret = allocateSpi(saInfo, minSpi, maxSpi, reinterpret_cast<uint32_t*>(outSpi), sock);
ludi6e8eccd2017-08-14 14:40:37 -0700373 if (!isOk(ret)) {
374 // TODO: May want to return a new Status with a modified status string
Nathan Harold1a371532017-01-30 12:30:48 -0800375 ALOGD("Failed to Allocate an SPI, line=%d", __LINE__);
376 *outSpi = INVALID_SPI;
377 }
378
379 return ret;
380}
381
ludi6e8eccd2017-08-14 14:40:37 -0700382netdutils::Status XfrmController::ipSecAddSecurityAssociation(
Nathan Harold1a371532017-01-30 12:30:48 -0800383 int32_t transformId, int32_t mode, int32_t direction, const std::string& localAddress,
Nathan Harold420ceac2017-04-05 19:36:59 -0700384 const std::string& remoteAddress, int64_t underlyingNetworkHandle, int32_t spi,
Nathan Harold1a371532017-01-30 12:30:48 -0800385 const std::string& authAlgo, const std::vector<uint8_t>& authKey, int32_t authTruncBits,
386 const std::string& cryptAlgo, const std::vector<uint8_t>& cryptKey, int32_t cryptTruncBits,
Benedict Wongbe65b432017-08-22 21:43:14 -0700387 const std::string& aeadAlgo, const std::vector<uint8_t>& aeadKey, int32_t aeadIcvBits,
ludiec836052017-05-20 14:17:05 -0700388 int32_t encapType, int32_t encapLocalPort, int32_t encapRemotePort) {
Nathan Harold1a371532017-01-30 12:30:48 -0800389 ALOGD("XfrmController::%s, line=%d", __FUNCTION__, __LINE__);
390 ALOGD("transformId=%d", transformId);
391 ALOGD("mode=%d", mode);
392 ALOGD("direction=%d", direction);
393 ALOGD("localAddress=%s", localAddress.c_str());
394 ALOGD("remoteAddress=%s", remoteAddress.c_str());
Nathan Harold420ceac2017-04-05 19:36:59 -0700395 ALOGD("underlyingNetworkHandle=%" PRIx64, underlyingNetworkHandle);
Nathan Harold1a371532017-01-30 12:30:48 -0800396 ALOGD("spi=%0.8x", spi);
397 ALOGD("authAlgo=%s", authAlgo.c_str());
398 ALOGD("authTruncBits=%d", authTruncBits);
399 ALOGD("cryptAlgo=%s", cryptAlgo.c_str());
400 ALOGD("cryptTruncBits=%d,", cryptTruncBits);
Benedict Wongbe65b432017-08-22 21:43:14 -0700401 ALOGD("aeadAlgo=%s", aeadAlgo.c_str());
402 ALOGD("aeadIcvBits=%d,", aeadIcvBits);
Nathan Harold1a371532017-01-30 12:30:48 -0800403 ALOGD("encapType=%d", encapType);
404 ALOGD("encapLocalPort=%d", encapLocalPort);
405 ALOGD("encapRemotePort=%d", encapRemotePort);
406
407 XfrmSaInfo saInfo{};
ludi6e8eccd2017-08-14 14:40:37 -0700408 netdutils::Status ret = fillXfrmSaId(direction, localAddress, remoteAddress, spi, &saInfo);
409 if (!isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800410 return ret;
411 }
412
413 saInfo.transformId = transformId;
414
Nathan Harold1a371532017-01-30 12:30:48 -0800415 saInfo.auth = XfrmAlgo{
416 .name = authAlgo, .key = authKey, .truncLenBits = static_cast<uint16_t>(authTruncBits)};
417
418 saInfo.crypt = XfrmAlgo{
419 .name = cryptAlgo, .key = cryptKey, .truncLenBits = static_cast<uint16_t>(cryptTruncBits)};
420
Benedict Wongbe65b432017-08-22 21:43:14 -0700421 saInfo.aead = XfrmAlgo{
422 .name = aeadAlgo, .key = aeadKey, .truncLenBits = static_cast<uint16_t>(aeadIcvBits)};
423
Nathan Harold1a371532017-01-30 12:30:48 -0800424 saInfo.direction = static_cast<XfrmDirection>(direction);
425
426 switch (static_cast<XfrmMode>(mode)) {
427 case XfrmMode::TRANSPORT:
428 case XfrmMode::TUNNEL:
429 saInfo.mode = static_cast<XfrmMode>(mode);
430 break;
431 default:
ludi6e8eccd2017-08-14 14:40:37 -0700432 return netdutils::statusFromErrno(EINVAL, "Invalid xfrm mode");
Nathan Harold1a371532017-01-30 12:30:48 -0800433 }
434
435 XfrmSocketImpl sock;
ludi6e8eccd2017-08-14 14:40:37 -0700436 netdutils::Status socketStatus = sock.open();
437 if (!isOk(socketStatus)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800438 ALOGD("Sock open failed for XFRM, line=%d", __LINE__);
ludi6e8eccd2017-08-14 14:40:37 -0700439 return socketStatus;
Nathan Harold1a371532017-01-30 12:30:48 -0800440 }
441
Nathan Harold420ceac2017-04-05 19:36:59 -0700442 switch (static_cast<XfrmEncapType>(encapType)) {
443 case XfrmEncapType::ESPINUDP:
444 case XfrmEncapType::ESPINUDP_NON_IKE:
445 if (saInfo.addrFamily != AF_INET) {
ludi6e8eccd2017-08-14 14:40:37 -0700446 return netdutils::statusFromErrno(EAFNOSUPPORT, "IPv6 encap not supported");
Nathan Harold420ceac2017-04-05 19:36:59 -0700447 }
448 switch (saInfo.direction) {
449 case XfrmDirection::IN:
450 saInfo.encap.srcPort = encapRemotePort;
451 saInfo.encap.dstPort = encapLocalPort;
452 break;
453 case XfrmDirection::OUT:
454 saInfo.encap.srcPort = encapLocalPort;
455 saInfo.encap.dstPort = encapRemotePort;
456 break;
457 default:
ludi6e8eccd2017-08-14 14:40:37 -0700458 return netdutils::statusFromErrno(EINVAL, "Invalid direction");
Nathan Harold420ceac2017-04-05 19:36:59 -0700459 }
460 // fall through
461 case XfrmEncapType::NONE:
462 saInfo.encap.type = static_cast<XfrmEncapType>(encapType);
463 break;
464 default:
ludi6e8eccd2017-08-14 14:40:37 -0700465 return netdutils::statusFromErrno(EINVAL, "Invalid encap type");
Nathan Harold420ceac2017-04-05 19:36:59 -0700466 }
467
Nathan Harold1a371532017-01-30 12:30:48 -0800468 ret = createTransportModeSecurityAssociation(saInfo, sock);
ludi6e8eccd2017-08-14 14:40:37 -0700469 if (!isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800470 ALOGD("Failed creating a Security Association, line=%d", __LINE__);
Nathan Harold1a371532017-01-30 12:30:48 -0800471 }
472
ludi6e8eccd2017-08-14 14:40:37 -0700473 return ret;
Nathan Harold1a371532017-01-30 12:30:48 -0800474}
475
ludi6e8eccd2017-08-14 14:40:37 -0700476netdutils::Status XfrmController::ipSecDeleteSecurityAssociation(int32_t transformId,
477 int32_t direction,
478 const std::string& localAddress,
479 const std::string& remoteAddress,
480 int32_t spi) {
Nathan Harold1a371532017-01-30 12:30:48 -0800481 ALOGD("XfrmController:%s, line=%d", __FUNCTION__, __LINE__);
482 ALOGD("transformId=%d", transformId);
483 ALOGD("direction=%d", direction);
484 ALOGD("localAddress=%s", localAddress.c_str());
485 ALOGD("remoteAddress=%s", remoteAddress.c_str());
486 ALOGD("spi=%0.8x", spi);
487
Jonathan Basseriebdaa682017-09-14 16:33:08 -0700488 XfrmSaId saId{};
ludi6e8eccd2017-08-14 14:40:37 -0700489 netdutils::Status ret = fillXfrmSaId(direction, localAddress, remoteAddress, spi, &saId);
490 if (!isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800491 return ret;
492 }
493
494 XfrmSocketImpl sock;
ludi6e8eccd2017-08-14 14:40:37 -0700495 netdutils::Status socketStatus = sock.open();
496 if (!isOk(socketStatus)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800497 ALOGD("Sock open failed for XFRM, line=%d", __LINE__);
ludi6e8eccd2017-08-14 14:40:37 -0700498 return socketStatus;
Nathan Harold1a371532017-01-30 12:30:48 -0800499 }
500
501 ret = deleteSecurityAssociation(saId, sock);
ludi6e8eccd2017-08-14 14:40:37 -0700502 if (!isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800503 ALOGD("Failed to delete Security Association, line=%d", __LINE__);
Nathan Harold1a371532017-01-30 12:30:48 -0800504 }
505
506 return ret;
507}
508
ludi6e8eccd2017-08-14 14:40:37 -0700509netdutils::Status XfrmController::fillXfrmSaId(int32_t direction, const std::string& localAddress,
510 const std::string& remoteAddress, int32_t spi,
511 XfrmSaId* xfrmId) {
Nathan Harold1a371532017-01-30 12:30:48 -0800512 xfrm_address_t localXfrmAddr{}, remoteXfrmAddr{};
513
ludi6e8eccd2017-08-14 14:40:37 -0700514 StatusOr<int> addrFamilyLocal, addrFamilyRemote;
Nathan Harold1a371532017-01-30 12:30:48 -0800515 addrFamilyRemote = convertToXfrmAddr(remoteAddress, &remoteXfrmAddr);
516 addrFamilyLocal = convertToXfrmAddr(localAddress, &localXfrmAddr);
ludi6e8eccd2017-08-14 14:40:37 -0700517 if (!isOk(addrFamilyRemote) || !isOk(addrFamilyLocal)) {
518 return netdutils::statusFromErrno(EINVAL,
519 "Invalid address " + localAddress + "/" + remoteAddress);
Nathan Harold1a371532017-01-30 12:30:48 -0800520 }
521
ludi6e8eccd2017-08-14 14:40:37 -0700522 if (addrFamilyRemote.value() == AF_UNSPEC ||
523 (addrFamilyLocal.value() != AF_UNSPEC &&
524 addrFamilyLocal.value() != addrFamilyRemote.value())) {
525 ALOGD("Invalid or Mismatched Address Families, %d != %d, line=%d", addrFamilyLocal.value(),
526 addrFamilyRemote.value(), __LINE__);
527 return netdutils::statusFromErrno(EINVAL, "Invalid or mismatched address families");
Nathan Harold1a371532017-01-30 12:30:48 -0800528 }
529
ludi6e8eccd2017-08-14 14:40:37 -0700530 xfrmId->addrFamily = addrFamilyRemote.value();
Nathan Harold1a371532017-01-30 12:30:48 -0800531
532 xfrmId->spi = htonl(spi);
533
534 switch (static_cast<XfrmDirection>(direction)) {
535 case XfrmDirection::IN:
536 xfrmId->dstAddr = localXfrmAddr;
537 xfrmId->srcAddr = remoteXfrmAddr;
538 break;
539
540 case XfrmDirection::OUT:
541 xfrmId->dstAddr = remoteXfrmAddr;
542 xfrmId->srcAddr = localXfrmAddr;
543 break;
544
545 default:
546 ALOGD("Invalid XFRM direction, line=%d", __LINE__);
547 // Invalid direction for Transport mode transform: time to bail
ludi6e8eccd2017-08-14 14:40:37 -0700548 return netdutils::statusFromErrno(EINVAL, "Invalid direction");
Nathan Harold1a371532017-01-30 12:30:48 -0800549 }
ludi6e8eccd2017-08-14 14:40:37 -0700550 return netdutils::status::ok;
Nathan Harold1a371532017-01-30 12:30:48 -0800551}
552
ludi6e8eccd2017-08-14 14:40:37 -0700553netdutils::Status XfrmController::ipSecApplyTransportModeTransform(
554 const android::base::unique_fd& socket, int32_t transformId, int32_t direction,
555 const std::string& localAddress, const std::string& remoteAddress, int32_t spi) {
Nathan Harold1a371532017-01-30 12:30:48 -0800556 ALOGD("XfrmController::%s, line=%d", __FUNCTION__, __LINE__);
557 ALOGD("transformId=%d", transformId);
558 ALOGD("direction=%d", direction);
559 ALOGD("localAddress=%s", localAddress.c_str());
560 ALOGD("remoteAddress=%s", remoteAddress.c_str());
561 ALOGD("spi=%0.8x", spi);
562
563 struct sockaddr_storage saddr;
564
ludi4072ff22017-06-15 08:56:52 -0700565 StatusOr<sockaddr_storage> ret = getSyscallInstance().getsockname<sockaddr_storage>(Fd(socket));
566 if (!isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800567 ALOGE("Failed to get socket info in %s", __FUNCTION__);
ludi6e8eccd2017-08-14 14:40:37 -0700568 return ret;
Nathan Harold1a371532017-01-30 12:30:48 -0800569 }
570
ludi4072ff22017-06-15 08:56:52 -0700571 saddr = ret.value();
572
Nathan Harold1a371532017-01-30 12:30:48 -0800573 XfrmSaInfo saInfo{};
574 saInfo.transformId = transformId;
575 saInfo.direction = static_cast<XfrmDirection>(direction);
576 saInfo.spi = spi;
577
ludi6e8eccd2017-08-14 14:40:37 -0700578 netdutils::Status status = fillXfrmSaId(direction, localAddress, remoteAddress, spi, &saInfo);
579 if (!isOk(status)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800580 ALOGE("Couldn't build SA ID %s", __FUNCTION__);
ludi6e8eccd2017-08-14 14:40:37 -0700581 return status;
Nathan Harold1a371532017-01-30 12:30:48 -0800582 }
583
584 if (saInfo.addrFamily != saddr.ss_family) {
585 ALOGE("Transform address family(%d) differs from socket address "
Nathan Harold420ceac2017-04-05 19:36:59 -0700586 "family(%d)!",
587 saInfo.addrFamily, saddr.ss_family);
ludi6e8eccd2017-08-14 14:40:37 -0700588 return netdutils::statusFromErrno(EINVAL, "Mismatched address family");
Nathan Harold1a371532017-01-30 12:30:48 -0800589 }
590
591 struct {
592 xfrm_userpolicy_info info;
593 xfrm_user_tmpl tmpl;
594 } policy{};
595
596 fillTransportModeUserSpInfo(saInfo, &policy.info);
597 fillUserTemplate(saInfo, &policy.tmpl);
598
599 LOG_HEX("XfrmUserPolicy", reinterpret_cast<char*>(&policy), sizeof(policy));
600
601 int sockOpt, sockLayer;
602 switch (saInfo.addrFamily) {
603 case AF_INET:
604 sockOpt = IP_XFRM_POLICY;
605 sockLayer = SOL_IP;
606 break;
607 case AF_INET6:
608 sockOpt = IPV6_XFRM_POLICY;
609 sockLayer = SOL_IPV6;
610 break;
611 default:
ludi6e8eccd2017-08-14 14:40:37 -0700612 return netdutils::statusFromErrno(EAFNOSUPPORT, "Invalid address family");
Nathan Harold1a371532017-01-30 12:30:48 -0800613 }
614
ludi6e8eccd2017-08-14 14:40:37 -0700615 status = getSyscallInstance().setsockopt(Fd(socket), sockLayer, sockOpt, policy);
ludi4072ff22017-06-15 08:56:52 -0700616 if (!isOk(status)) {
617 ALOGE("Error setting socket option for XFRM! (%s)", toString(status).c_str());
Nathan Harold1a371532017-01-30 12:30:48 -0800618 }
ludi6e8eccd2017-08-14 14:40:37 -0700619
620 return status;
Nathan Harold1a371532017-01-30 12:30:48 -0800621}
622
ludi6e8eccd2017-08-14 14:40:37 -0700623netdutils::Status
624XfrmController::ipSecRemoveTransportModeTransform(const android::base::unique_fd& socket) {
Nathan Harold1a371532017-01-30 12:30:48 -0800625 (void)socket;
ludi6e8eccd2017-08-14 14:40:37 -0700626 return netdutils::status::ok;
Nathan Harold1a371532017-01-30 12:30:48 -0800627}
628
629void XfrmController::fillTransportModeSelector(const XfrmSaInfo& record, xfrm_selector* selector) {
630 selector->family = record.addrFamily;
631 selector->proto = AF_UNSPEC; // TODO: do we need to match the protocol? it's
632 // possible via the socket
633 selector->ifindex = record.netId; // TODO : still need to sort this out
634}
635
ludi6e8eccd2017-08-14 14:40:37 -0700636netdutils::Status XfrmController::createTransportModeSecurityAssociation(const XfrmSaInfo& record,
637 const XfrmSocket& sock) {
Nathan Harold1a371532017-01-30 12:30:48 -0800638 xfrm_usersa_info usersa{};
639 nlattr_algo_crypt crypt{};
640 nlattr_algo_auth auth{};
Benedict Wongbe65b432017-08-22 21:43:14 -0700641 nlattr_algo_aead aead{};
Nathan Harold420ceac2017-04-05 19:36:59 -0700642 nlattr_encap_tmpl encap{};
Nathan Harold1a371532017-01-30 12:30:48 -0800643
Benedict Wongbe65b432017-08-22 21:43:14 -0700644 enum {
645 NLMSG_HDR,
646 USERSA,
647 USERSA_PAD,
648 CRYPT,
649 CRYPT_PAD,
650 AUTH,
651 AUTH_PAD,
652 AEAD,
653 AEAD_PAD,
654 ENCAP,
655 ENCAP_PAD
656 };
Nathan Harold1a371532017-01-30 12:30:48 -0800657
ludie51e3862017-08-15 19:28:12 -0700658 std::vector<iovec> iov = {
Nathan Harold1a371532017-01-30 12:30:48 -0800659 {NULL, 0}, // reserved for the eventual addition of a NLMSG_HDR
660 {&usersa, 0}, // main usersa_info struct
661 {kPadBytes, 0}, // up to NLMSG_ALIGNTO pad bytes of padding
662 {&crypt, 0}, // adjust size if crypt algo is present
663 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
664 {&auth, 0}, // adjust size if auth algo is present
665 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
Benedict Wongbe65b432017-08-22 21:43:14 -0700666 {&aead, 0}, // adjust size if aead algo is present
667 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
668 {&encap, 0}, // adjust size if encapsulating
Nathan Harold420ceac2017-04-05 19:36:59 -0700669 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
Nathan Harold1a371532017-01-30 12:30:48 -0800670 };
671
Benedict Wongbe65b432017-08-22 21:43:14 -0700672 if (!record.aead.name.empty() && (!record.auth.name.empty() || !record.crypt.name.empty())) {
673 return netdutils::statusFromErrno(EINVAL, "Invalid xfrm algo selection; AEAD is mutually "
674 "exclusive with both Authentication and "
675 "Encryption");
676 }
677
Benedict Wong4f60ee12017-10-10 12:27:25 -0700678 if (record.aead.key.size() > MAX_KEY_LENGTH || record.auth.key.size() > MAX_KEY_LENGTH ||
679 record.crypt.key.size() > MAX_KEY_LENGTH) {
680 return netdutils::statusFromErrno(EINVAL, "Key length invalid; exceeds MAX_KEY_LENGTH");
Benedict Wongbe65b432017-08-22 21:43:14 -0700681 }
682
Nathan Harold1a371532017-01-30 12:30:48 -0800683 int len;
684 len = iov[USERSA].iov_len = fillUserSaInfo(record, &usersa);
685 iov[USERSA_PAD].iov_len = NLMSG_ALIGN(len) - len;
686
687 len = iov[CRYPT].iov_len = fillNlAttrXfrmAlgoEnc(record.crypt, &crypt);
688 iov[CRYPT_PAD].iov_len = NLA_ALIGN(len) - len;
689
690 len = iov[AUTH].iov_len = fillNlAttrXfrmAlgoAuth(record.auth, &auth);
691 iov[AUTH_PAD].iov_len = NLA_ALIGN(len) - len;
692
Benedict Wongbe65b432017-08-22 21:43:14 -0700693 len = iov[AEAD].iov_len = fillNlAttrXfrmAlgoAead(record.aead, &aead);
694 iov[AEAD_PAD].iov_len = NLA_ALIGN(len) - len;
695
Nathan Harold420ceac2017-04-05 19:36:59 -0700696 len = iov[ENCAP].iov_len = fillNlAttrXfrmEncapTmpl(record, &encap);
697 iov[ENCAP_PAD].iov_len = NLA_ALIGN(len) - len;
ludie51e3862017-08-15 19:28:12 -0700698 return sock.sendMessage(XFRM_MSG_UPDSA, NETLINK_REQUEST_FLAGS, 0, &iov);
Nathan Harold1a371532017-01-30 12:30:48 -0800699}
700
701int XfrmController::fillNlAttrXfrmAlgoEnc(const XfrmAlgo& inAlgo, nlattr_algo_crypt* algo) {
Benedict Wongbe65b432017-08-22 21:43:14 -0700702 if (inAlgo.name.empty()) { // Do not fill anything if algorithm not provided
703 return 0;
704 }
705
Nathan Harold1a371532017-01-30 12:30:48 -0800706 int len = NLA_HDRLEN + sizeof(xfrm_algo);
Benedict Wongbe65b432017-08-22 21:43:14 -0700707 // Kernel always changes last char to null terminator; no safety checks needed.
Nathan Harold1a371532017-01-30 12:30:48 -0800708 strncpy(algo->crypt.alg_name, inAlgo.name.c_str(), sizeof(algo->crypt.alg_name));
709 algo->crypt.alg_key_len = inAlgo.key.size() * 8; // bits
Benedict Wongbe65b432017-08-22 21:43:14 -0700710 memcpy(algo->key, &inAlgo.key[0], inAlgo.key.size());
Nathan Harold1a371532017-01-30 12:30:48 -0800711 len += inAlgo.key.size();
712 fillXfrmNlaHdr(&algo->hdr, XFRMA_ALG_CRYPT, len);
713 return len;
714}
715
716int XfrmController::fillNlAttrXfrmAlgoAuth(const XfrmAlgo& inAlgo, nlattr_algo_auth* algo) {
Benedict Wongbe65b432017-08-22 21:43:14 -0700717 if (inAlgo.name.empty()) { // Do not fill anything if algorithm not provided
718 return 0;
719 }
720
Nathan Harold1a371532017-01-30 12:30:48 -0800721 int len = NLA_HDRLEN + sizeof(xfrm_algo_auth);
Benedict Wongbe65b432017-08-22 21:43:14 -0700722 // Kernel always changes last char to null terminator; no safety checks needed.
Nathan Harold1a371532017-01-30 12:30:48 -0800723 strncpy(algo->auth.alg_name, inAlgo.name.c_str(), sizeof(algo->auth.alg_name));
724 algo->auth.alg_key_len = inAlgo.key.size() * 8; // bits
725
726 // This is the extra field for ALG_AUTH_TRUNC
727 algo->auth.alg_trunc_len = inAlgo.truncLenBits;
728
Benedict Wongbe65b432017-08-22 21:43:14 -0700729 memcpy(algo->key, &inAlgo.key[0], inAlgo.key.size());
Nathan Harold1a371532017-01-30 12:30:48 -0800730 len += inAlgo.key.size();
731
732 fillXfrmNlaHdr(&algo->hdr, XFRMA_ALG_AUTH_TRUNC, len);
733 return len;
734}
735
Benedict Wongbe65b432017-08-22 21:43:14 -0700736int XfrmController::fillNlAttrXfrmAlgoAead(const XfrmAlgo& inAlgo, nlattr_algo_aead* algo) {
737 if (inAlgo.name.empty()) { // Do not fill anything if algorithm not provided
738 return 0;
739 }
740
741 int len = NLA_HDRLEN + sizeof(xfrm_algo_aead);
742 // Kernel always changes last char to null terminator; no safety checks needed.
743 strncpy(algo->aead.alg_name, inAlgo.name.c_str(), sizeof(algo->aead.alg_name));
744 algo->aead.alg_key_len = inAlgo.key.size() * 8; // bits
745
746 // This is the extra field for ALG_AEAD. ICV length is the same as truncation length
747 // for any AEAD algorithm.
748 algo->aead.alg_icv_len = inAlgo.truncLenBits;
749
750 memcpy(algo->key, &inAlgo.key[0], inAlgo.key.size());
751 len += inAlgo.key.size();
752
753 fillXfrmNlaHdr(&algo->hdr, XFRMA_ALG_AEAD, len);
754 return len;
755}
756
Nathan Harold420ceac2017-04-05 19:36:59 -0700757int XfrmController::fillNlAttrXfrmEncapTmpl(const XfrmSaInfo& record, nlattr_encap_tmpl* tmpl) {
758 if (record.encap.type == XfrmEncapType::NONE) {
759 return 0;
760 }
761
762 int len = NLA_HDRLEN + sizeof(xfrm_encap_tmpl);
763 tmpl->tmpl.encap_type = static_cast<uint16_t>(record.encap.type);
764 tmpl->tmpl.encap_sport = htons(record.encap.srcPort);
765 tmpl->tmpl.encap_dport = htons(record.encap.dstPort);
766 fillXfrmNlaHdr(&tmpl->hdr, XFRMA_ENCAP, len);
767 return len;
768}
769
Nathan Harold1a371532017-01-30 12:30:48 -0800770int XfrmController::fillUserSaInfo(const XfrmSaInfo& record, xfrm_usersa_info* usersa) {
771 fillTransportModeSelector(record, &usersa->sel);
772
773 usersa->id.proto = IPPROTO_ESP;
774 usersa->id.spi = record.spi;
775 usersa->id.daddr = record.dstAddr;
776
777 usersa->saddr = record.srcAddr;
778
779 fillXfrmLifetimeDefaults(&usersa->lft);
780 fillXfrmCurLifetimeDefaults(&usersa->curlft);
781 memset(&usersa->stats, 0, sizeof(usersa->stats)); // leave stats zeroed out
782 usersa->reqid = record.transformId;
783 usersa->family = record.addrFamily;
784 usersa->mode = static_cast<uint8_t>(record.mode);
785 usersa->replay_window = REPLAY_WINDOW_SIZE;
786 usersa->flags = 0; // TODO: should we actually set flags, XFRM_SA_XFLAG_DONT_ENCAP_DSCP?
787 return sizeof(*usersa);
788}
789
790int XfrmController::fillUserSaId(const XfrmSaId& record, xfrm_usersa_id* said) {
791 said->daddr = record.dstAddr;
792 said->spi = record.spi;
793 said->family = record.addrFamily;
794 said->proto = IPPROTO_ESP;
795
796 return sizeof(*said);
797}
798
ludi6e8eccd2017-08-14 14:40:37 -0700799netdutils::Status XfrmController::deleteSecurityAssociation(const XfrmSaId& record,
800 const XfrmSocket& sock) {
Nathan Harold1a371532017-01-30 12:30:48 -0800801 xfrm_usersa_id said{};
802
ludie51e3862017-08-15 19:28:12 -0700803 enum { NLMSG_HDR, USERSAID, USERSAID_PAD };
Nathan Harold1a371532017-01-30 12:30:48 -0800804
ludie51e3862017-08-15 19:28:12 -0700805 std::vector<iovec> iov = {
Nathan Harold1a371532017-01-30 12:30:48 -0800806 {NULL, 0}, // reserved for the eventual addition of a NLMSG_HDR
807 {&said, 0}, // main usersa_info struct
808 {kPadBytes, 0}, // up to NLMSG_ALIGNTO pad bytes of padding
809 };
810
811 int len;
812 len = iov[USERSAID].iov_len = fillUserSaId(record, &said);
813 iov[USERSAID_PAD].iov_len = NLMSG_ALIGN(len) - len;
814
ludie51e3862017-08-15 19:28:12 -0700815 return sock.sendMessage(XFRM_MSG_DELSA, NETLINK_REQUEST_FLAGS, 0, &iov);
Nathan Harold1a371532017-01-30 12:30:48 -0800816}
817
ludi6e8eccd2017-08-14 14:40:37 -0700818netdutils::Status XfrmController::allocateSpi(const XfrmSaInfo& record, uint32_t minSpi,
819 uint32_t maxSpi, uint32_t* outSpi,
820 const XfrmSocket& sock) {
Nathan Harold1a371532017-01-30 12:30:48 -0800821 xfrm_userspi_info spiInfo{};
822
ludie51e3862017-08-15 19:28:12 -0700823 enum { NLMSG_HDR, USERSAID, USERSAID_PAD };
Nathan Harold1a371532017-01-30 12:30:48 -0800824
ludie51e3862017-08-15 19:28:12 -0700825 std::vector<iovec> iov = {
Nathan Harold1a371532017-01-30 12:30:48 -0800826 {NULL, 0}, // reserved for the eventual addition of a NLMSG_HDR
827 {&spiInfo, 0}, // main userspi_info struct
828 {kPadBytes, 0}, // up to NLMSG_ALIGNTO pad bytes of padding
829 };
830
831 int len;
832 if (fillUserSaInfo(record, &spiInfo.info) == 0) {
833 ALOGE("Failed to fill transport SA Info");
834 }
835
836 len = iov[USERSAID].iov_len = sizeof(spiInfo);
837 iov[USERSAID_PAD].iov_len = NLMSG_ALIGN(len) - len;
838
839 RandomSpi spiGen = RandomSpi(minSpi, maxSpi);
ludi6e8eccd2017-08-14 14:40:37 -0700840 int spi;
841 netdutils::Status ret;
Nathan Harold1a371532017-01-30 12:30:48 -0800842 while ((spi = spiGen.next()) != INVALID_SPI) {
843 spiInfo.min = spi;
844 spiInfo.max = spi;
ludie51e3862017-08-15 19:28:12 -0700845 ret = sock.sendMessage(XFRM_MSG_ALLOCSPI, NETLINK_REQUEST_FLAGS, 0, &iov);
Nathan Harold1a371532017-01-30 12:30:48 -0800846
847 /* If the SPI is in use, we'll get ENOENT */
ludi6e8eccd2017-08-14 14:40:37 -0700848 if (netdutils::equalToErrno(ret, ENOENT))
Nathan Harold1a371532017-01-30 12:30:48 -0800849 continue;
850
ludi6e8eccd2017-08-14 14:40:37 -0700851 if (isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800852 *outSpi = spi;
Nathan Harold420ceac2017-04-05 19:36:59 -0700853 ALOGD("Allocated an SPI: %x", *outSpi);
Nathan Harold1a371532017-01-30 12:30:48 -0800854 } else {
855 *outSpi = INVALID_SPI;
ludi6e8eccd2017-08-14 14:40:37 -0700856 ALOGE("SPI Allocation Failed with error %d", ret.code());
Nathan Harold1a371532017-01-30 12:30:48 -0800857 }
858
859 return ret;
860 }
861
862 // Should always be -ENOENT if we get here
863 return ret;
864}
865
866int XfrmController::fillTransportModeUserSpInfo(const XfrmSaInfo& record,
867 xfrm_userpolicy_info* usersp) {
868 fillTransportModeSelector(record, &usersp->sel);
869 fillXfrmLifetimeDefaults(&usersp->lft);
870 fillXfrmCurLifetimeDefaults(&usersp->curlft);
Nathan Harold420ceac2017-04-05 19:36:59 -0700871 /* if (index) index & 0x3 == dir -- must be true
872 * xfrm_user.c:verify_newpolicy_info() */
Nathan Harold1a371532017-01-30 12:30:48 -0800873 usersp->index = 0;
874 usersp->dir = static_cast<uint8_t>(record.direction);
875 usersp->action = XFRM_POLICY_ALLOW;
876 usersp->flags = XFRM_POLICY_LOCALOK;
877 usersp->share = XFRM_SHARE_UNIQUE;
878 return sizeof(*usersp);
879}
880
881int XfrmController::fillUserTemplate(const XfrmSaInfo& record, xfrm_user_tmpl* tmpl) {
882 tmpl->id.daddr = record.dstAddr;
883 tmpl->id.spi = record.spi;
884 tmpl->id.proto = IPPROTO_ESP;
885
886 tmpl->family = record.addrFamily;
887 tmpl->saddr = record.srcAddr;
888 tmpl->reqid = record.transformId;
889 tmpl->mode = static_cast<uint8_t>(record.mode);
890 tmpl->share = XFRM_SHARE_UNIQUE;
891 tmpl->optional = 0; // if this is true, then a failed state lookup will be considered OK:
892 // http://lxr.free-electrons.com/source/net/xfrm/xfrm_policy.c#L1492
893 tmpl->aalgos = ALGO_MASK_AUTH_ALL; // TODO: if there's a bitmask somewhere of
894 // algos, we should find it and apply it.
895 // I can't find one.
896 tmpl->ealgos = ALGO_MASK_CRYPT_ALL; // TODO: if there's a bitmask somewhere...
897 return 0;
898}
899
900} // namespace net
901} // namespace android