blob: de5eadb825cac7f87cb4909e2aa494aef5ffbc41 [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
Nathan Harold1e284452017-10-10 13:31:19 -070018#include <random>
Nathan Harold7441c692017-12-12 21:25:01 -080019#include <string>
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__); \
Nathan Harold7441c692017-12-12 21:25:01 -0800128 } while (0); \
Manojd9c93c22017-10-19 13:40:26 -0700129 }
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__); \
Nathan Harold7441c692017-12-12 21:25:01 -0800135 } 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 = {
Nathan Harold7441c692017-12-12 21:25:01 -0800230 .nlmsg_type = nlMsgType,
231 .nlmsg_flags = nlMsgFlags,
232 .nlmsg_seq = nlMsgSeqNum,
Nathan Harold1a371532017-01-30 12:30:48 -0800233 };
234
ludie51e3862017-08-15 19:28:12 -0700235 (*iovecs)[0].iov_base = &nlMsg;
236 (*iovecs)[0].iov_len = NLMSG_HDRLEN;
237 for (const iovec& iov : *iovecs) {
238 nlMsg.nlmsg_len += iov.iov_len;
Nathan Harold1a371532017-01-30 12:30:48 -0800239 }
240
241 ALOGD("Sending Netlink XFRM Message: %s", xfrmMsgTypeToString(nlMsgType));
Manojd9c93c22017-10-19 13:40:26 -0700242 LOG_IOV(*iovecs);
Nathan Harold1a371532017-01-30 12:30:48 -0800243
ludie51e3862017-08-15 19:28:12 -0700244 StatusOr<size_t> writeResult = getSyscallInstance().writev(mSock, *iovecs);
ludi4072ff22017-06-15 08:56:52 -0700245 if (!isOk(writeResult)) {
246 ALOGE("netlink socket writev failed (%s)", toString(writeResult).c_str());
ludi6e8eccd2017-08-14 14:40:37 -0700247 return writeResult;
Nathan Harold1a371532017-01-30 12:30:48 -0800248 }
249
ludi4072ff22017-06-15 08:56:52 -0700250 if (nlMsg.nlmsg_len != writeResult.value()) {
251 ALOGE("Invalid netlink message length sent %d", static_cast<int>(writeResult.value()));
ludi6e8eccd2017-08-14 14:40:37 -0700252 return netdutils::statusFromErrno(EBADMSG, "Invalid message length");
Nathan Harold1a371532017-01-30 12:30:48 -0800253 }
254
ludi4072ff22017-06-15 08:56:52 -0700255 NetlinkResponse response = {};
Nathan Harold1a371532017-01-30 12:30:48 -0800256
ludi4072ff22017-06-15 08:56:52 -0700257 StatusOr<Slice> readResult =
258 getSyscallInstance().read(Fd(mSock), netdutils::makeSlice(response));
259 if (!isOk(readResult)) {
260 ALOGE("netlink response error (%s)", toString(readResult).c_str());
ludi6e8eccd2017-08-14 14:40:37 -0700261 return readResult;
ludi4072ff22017-06-15 08:56:52 -0700262 }
263
264 LOG_HEX("netlink msg resp", reinterpret_cast<char*>(readResult.value().base()),
265 readResult.value().size());
266
ludi6e8eccd2017-08-14 14:40:37 -0700267 Status validateStatus = validateResponse(response, readResult.value().size());
268 if (!isOk(validateStatus)) {
269 ALOGE("netlink response contains error (%s)", toString(validateStatus).c_str());
270 }
271
272 return validateStatus;
Nathan Harold1a371532017-01-30 12:30:48 -0800273 }
274};
275
ludi6e8eccd2017-08-14 14:40:37 -0700276StatusOr<int> convertToXfrmAddr(const std::string& strAddr, xfrm_address_t* xfrmAddr) {
Nathan Harold1a371532017-01-30 12:30:48 -0800277 if (strAddr.length() == 0) {
278 memset(xfrmAddr, 0, sizeof(*xfrmAddr));
279 return AF_UNSPEC;
280 }
281
282 if (inet_pton(AF_INET6, strAddr.c_str(), reinterpret_cast<void*>(xfrmAddr))) {
283 return AF_INET6;
284 } else if (inet_pton(AF_INET, strAddr.c_str(), reinterpret_cast<void*>(xfrmAddr))) {
285 return AF_INET;
286 } else {
ludi6e8eccd2017-08-14 14:40:37 -0700287 return netdutils::statusFromErrno(EAFNOSUPPORT, "Invalid address family");
Nathan Harold1a371532017-01-30 12:30:48 -0800288 }
289}
290
291void fillXfrmNlaHdr(nlattr* hdr, uint16_t type, uint16_t len) {
292 hdr->nla_type = type;
293 hdr->nla_len = len;
294}
295
296void fillXfrmCurLifetimeDefaults(xfrm_lifetime_cur* cur) {
297 memset(reinterpret_cast<char*>(cur), 0, sizeof(*cur));
298}
299void fillXfrmLifetimeDefaults(xfrm_lifetime_cfg* cfg) {
300 cfg->soft_byte_limit = XFRM_INF;
301 cfg->hard_byte_limit = XFRM_INF;
302 cfg->soft_packet_limit = XFRM_INF;
303 cfg->hard_packet_limit = XFRM_INF;
304}
305
306/*
307 * Allocate SPIs within an (inclusive) range of min-max.
308 * returns 0 (INVALID_SPI) once the entire range has been parsed.
309 */
310class RandomSpi {
311public:
312 RandomSpi(int min, int max) : mMin(min) {
Nathan Harold1e284452017-10-10 13:31:19 -0700313 // Re-seeding should be safe because the seed itself is
314 // sufficiently random and we don't need secure random
315 std::mt19937 rnd = std::mt19937(std::random_device()());
316 mNext = std::uniform_int_distribution<>(1, INT_MAX)(rnd);
Nathan Harold1a371532017-01-30 12:30:48 -0800317 mSize = max - min + 1;
318 mCount = mSize;
319 }
320
321 uint32_t next() {
322 if (!mCount)
323 return 0;
324 mCount--;
325 return (mNext++ % mSize) + mMin;
326 }
327
328private:
329 uint32_t mNext;
330 uint32_t mSize;
331 uint32_t mMin;
332 uint32_t mCount;
333};
334
335} // namespace
336
337//
338// Begin XfrmController Impl
339//
340//
341XfrmController::XfrmController(void) {}
342
Benedict Wongb2daefb2017-12-06 22:05:46 -0800343netdutils::Status XfrmController::ipSecSetEncapSocketOwner(const android::base::unique_fd& socket,
344 int newUid, uid_t callerUid) {
345 ALOGD("XfrmController:%s, line=%d", __FUNCTION__, __LINE__);
346
347 const int fd = socket.get();
348 struct stat info;
349 if (fstat(fd, &info)) {
350 return netdutils::statusFromErrno(errno, "Failed to stat socket file descriptor");
351 }
352 if (info.st_uid != callerUid) {
353 return netdutils::statusFromErrno(EPERM, "fchown disabled for non-owner calls");
354 }
355 if (S_ISSOCK(info.st_mode) == 0){
356 return netdutils::statusFromErrno(EINVAL, "File descriptor was not a socket");
357 }
358
359 int optval;
360 socklen_t optlen;
361 netdutils::Status status = getSyscallInstance().getsockopt(Fd(socket), IPPROTO_UDP, UDP_ENCAP,
362 &optval, &optlen);
363 if (status != netdutils::status::ok) {
364 return status;
365 }
366 if (optval != UDP_ENCAP_ESPINUDP && optval != UDP_ENCAP_ESPINUDP_NON_IKE){
367 return netdutils::statusFromErrno(EINVAL, "Socket did not have UDP-encap sockopt set");
368 }
369 if (fchown(fd, newUid, -1)) {
370 return netdutils::statusFromErrno(errno, "Failed to fchown socket file descriptor");
371 }
372
373 return netdutils::status::ok;
374}
375
ludi6e8eccd2017-08-14 14:40:37 -0700376netdutils::Status XfrmController::ipSecAllocateSpi(int32_t transformId, int32_t direction,
377 const std::string& localAddress,
378 const std::string& remoteAddress, int32_t inSpi,
379 int32_t* outSpi) {
Nathan Harold1a371532017-01-30 12:30:48 -0800380 ALOGD("XfrmController:%s, line=%d", __FUNCTION__, __LINE__);
381 ALOGD("transformId=%d", transformId);
382 ALOGD("direction=%d", direction);
383 ALOGD("localAddress=%s", localAddress.c_str());
384 ALOGD("remoteAddress=%s", remoteAddress.c_str());
385 ALOGD("inSpi=%0.8x", inSpi);
386
387 XfrmSaInfo saInfo{};
ludi6e8eccd2017-08-14 14:40:37 -0700388 netdutils::Status ret =
Nathan Harold7441c692017-12-12 21:25:01 -0800389 fillXfrmId(direction, localAddress, remoteAddress, INVALID_SPI, transformId, &saInfo);
ludi6e8eccd2017-08-14 14:40:37 -0700390 if (!isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800391 return ret;
392 }
393
394 XfrmSocketImpl sock;
ludi6e8eccd2017-08-14 14:40:37 -0700395 netdutils::Status socketStatus = sock.open();
396 if (!isOk(socketStatus)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800397 ALOGD("Sock open failed for XFRM, line=%d", __LINE__);
ludi6e8eccd2017-08-14 14:40:37 -0700398 return socketStatus;
Nathan Harold1a371532017-01-30 12:30:48 -0800399 }
400
401 int minSpi = RAND_SPI_MIN, maxSpi = RAND_SPI_MAX;
402
403 if (inSpi)
404 minSpi = maxSpi = inSpi;
ludi6e8eccd2017-08-14 14:40:37 -0700405
Nathan Harold1a371532017-01-30 12:30:48 -0800406 ret = allocateSpi(saInfo, minSpi, maxSpi, reinterpret_cast<uint32_t*>(outSpi), sock);
ludi6e8eccd2017-08-14 14:40:37 -0700407 if (!isOk(ret)) {
408 // TODO: May want to return a new Status with a modified status string
Nathan Harold1a371532017-01-30 12:30:48 -0800409 ALOGD("Failed to Allocate an SPI, line=%d", __LINE__);
410 *outSpi = INVALID_SPI;
411 }
412
413 return ret;
414}
415
ludi6e8eccd2017-08-14 14:40:37 -0700416netdutils::Status XfrmController::ipSecAddSecurityAssociation(
Nathan Harold1a371532017-01-30 12:30:48 -0800417 int32_t transformId, int32_t mode, int32_t direction, const std::string& localAddress,
Nathan Harold420ceac2017-04-05 19:36:59 -0700418 const std::string& remoteAddress, int64_t underlyingNetworkHandle, int32_t spi,
Nathan Harold1a371532017-01-30 12:30:48 -0800419 const std::string& authAlgo, const std::vector<uint8_t>& authKey, int32_t authTruncBits,
420 const std::string& cryptAlgo, const std::vector<uint8_t>& cryptKey, int32_t cryptTruncBits,
Benedict Wongbe65b432017-08-22 21:43:14 -0700421 const std::string& aeadAlgo, const std::vector<uint8_t>& aeadKey, int32_t aeadIcvBits,
ludiec836052017-05-20 14:17:05 -0700422 int32_t encapType, int32_t encapLocalPort, int32_t encapRemotePort) {
Nathan Harold1a371532017-01-30 12:30:48 -0800423 ALOGD("XfrmController::%s, line=%d", __FUNCTION__, __LINE__);
424 ALOGD("transformId=%d", transformId);
425 ALOGD("mode=%d", mode);
426 ALOGD("direction=%d", direction);
427 ALOGD("localAddress=%s", localAddress.c_str());
428 ALOGD("remoteAddress=%s", remoteAddress.c_str());
Nathan Harold420ceac2017-04-05 19:36:59 -0700429 ALOGD("underlyingNetworkHandle=%" PRIx64, underlyingNetworkHandle);
Nathan Harold1a371532017-01-30 12:30:48 -0800430 ALOGD("spi=%0.8x", spi);
431 ALOGD("authAlgo=%s", authAlgo.c_str());
432 ALOGD("authTruncBits=%d", authTruncBits);
433 ALOGD("cryptAlgo=%s", cryptAlgo.c_str());
434 ALOGD("cryptTruncBits=%d,", cryptTruncBits);
Benedict Wongbe65b432017-08-22 21:43:14 -0700435 ALOGD("aeadAlgo=%s", aeadAlgo.c_str());
436 ALOGD("aeadIcvBits=%d,", aeadIcvBits);
Nathan Harold1a371532017-01-30 12:30:48 -0800437 ALOGD("encapType=%d", encapType);
438 ALOGD("encapLocalPort=%d", encapLocalPort);
439 ALOGD("encapRemotePort=%d", encapRemotePort);
440
441 XfrmSaInfo saInfo{};
Nathan Harold7441c692017-12-12 21:25:01 -0800442 netdutils::Status ret =
443 fillXfrmId(direction, localAddress, remoteAddress, spi, transformId, &saInfo);
ludi6e8eccd2017-08-14 14:40:37 -0700444 if (!isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800445 return ret;
446 }
447
Nathan Harold1a371532017-01-30 12:30:48 -0800448 saInfo.auth = XfrmAlgo{
449 .name = authAlgo, .key = authKey, .truncLenBits = static_cast<uint16_t>(authTruncBits)};
450
451 saInfo.crypt = XfrmAlgo{
452 .name = cryptAlgo, .key = cryptKey, .truncLenBits = static_cast<uint16_t>(cryptTruncBits)};
453
Benedict Wongbe65b432017-08-22 21:43:14 -0700454 saInfo.aead = XfrmAlgo{
455 .name = aeadAlgo, .key = aeadKey, .truncLenBits = static_cast<uint16_t>(aeadIcvBits)};
456
Nathan Harold1a371532017-01-30 12:30:48 -0800457 saInfo.direction = static_cast<XfrmDirection>(direction);
458
459 switch (static_cast<XfrmMode>(mode)) {
460 case XfrmMode::TRANSPORT:
461 case XfrmMode::TUNNEL:
462 saInfo.mode = static_cast<XfrmMode>(mode);
463 break;
464 default:
ludi6e8eccd2017-08-14 14:40:37 -0700465 return netdutils::statusFromErrno(EINVAL, "Invalid xfrm mode");
Nathan Harold1a371532017-01-30 12:30:48 -0800466 }
467
468 XfrmSocketImpl sock;
ludi6e8eccd2017-08-14 14:40:37 -0700469 netdutils::Status socketStatus = sock.open();
470 if (!isOk(socketStatus)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800471 ALOGD("Sock open failed for XFRM, line=%d", __LINE__);
ludi6e8eccd2017-08-14 14:40:37 -0700472 return socketStatus;
Nathan Harold1a371532017-01-30 12:30:48 -0800473 }
474
Nathan Harold420ceac2017-04-05 19:36:59 -0700475 switch (static_cast<XfrmEncapType>(encapType)) {
476 case XfrmEncapType::ESPINUDP:
477 case XfrmEncapType::ESPINUDP_NON_IKE:
478 if (saInfo.addrFamily != AF_INET) {
ludi6e8eccd2017-08-14 14:40:37 -0700479 return netdutils::statusFromErrno(EAFNOSUPPORT, "IPv6 encap not supported");
Nathan Harold420ceac2017-04-05 19:36:59 -0700480 }
481 switch (saInfo.direction) {
482 case XfrmDirection::IN:
483 saInfo.encap.srcPort = encapRemotePort;
484 saInfo.encap.dstPort = encapLocalPort;
485 break;
486 case XfrmDirection::OUT:
487 saInfo.encap.srcPort = encapLocalPort;
488 saInfo.encap.dstPort = encapRemotePort;
489 break;
490 default:
ludi6e8eccd2017-08-14 14:40:37 -0700491 return netdutils::statusFromErrno(EINVAL, "Invalid direction");
Nathan Harold420ceac2017-04-05 19:36:59 -0700492 }
493 // fall through
494 case XfrmEncapType::NONE:
495 saInfo.encap.type = static_cast<XfrmEncapType>(encapType);
496 break;
497 default:
ludi6e8eccd2017-08-14 14:40:37 -0700498 return netdutils::statusFromErrno(EINVAL, "Invalid encap type");
Nathan Harold420ceac2017-04-05 19:36:59 -0700499 }
500
Di Lu0e16b5e2018-01-12 10:37:53 -0800501 ret = updateSecurityAssociation(saInfo, sock);
ludi6e8eccd2017-08-14 14:40:37 -0700502 if (!isOk(ret)) {
Di Lu0e16b5e2018-01-12 10:37:53 -0800503 ALOGD("Failed updating a Security Association, line=%d", __LINE__);
Nathan Harold1a371532017-01-30 12:30:48 -0800504 }
505
ludi6e8eccd2017-08-14 14:40:37 -0700506 return ret;
Nathan Harold1a371532017-01-30 12:30:48 -0800507}
508
ludi6e8eccd2017-08-14 14:40:37 -0700509netdutils::Status XfrmController::ipSecDeleteSecurityAssociation(int32_t transformId,
510 int32_t direction,
511 const std::string& localAddress,
512 const std::string& remoteAddress,
513 int32_t spi) {
Nathan Harold1a371532017-01-30 12:30:48 -0800514 ALOGD("XfrmController:%s, line=%d", __FUNCTION__, __LINE__);
515 ALOGD("transformId=%d", transformId);
516 ALOGD("direction=%d", direction);
517 ALOGD("localAddress=%s", localAddress.c_str());
518 ALOGD("remoteAddress=%s", remoteAddress.c_str());
519 ALOGD("spi=%0.8x", spi);
520
Nathan Harold7441c692017-12-12 21:25:01 -0800521 XfrmId saId{};
522 netdutils::Status ret =
523 fillXfrmId(direction, localAddress, remoteAddress, spi, transformId, &saId);
ludi6e8eccd2017-08-14 14:40:37 -0700524 if (!isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800525 return ret;
526 }
527
528 XfrmSocketImpl sock;
ludi6e8eccd2017-08-14 14:40:37 -0700529 netdutils::Status socketStatus = sock.open();
530 if (!isOk(socketStatus)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800531 ALOGD("Sock open failed for XFRM, line=%d", __LINE__);
ludi6e8eccd2017-08-14 14:40:37 -0700532 return socketStatus;
Nathan Harold1a371532017-01-30 12:30:48 -0800533 }
534
535 ret = deleteSecurityAssociation(saId, sock);
ludi6e8eccd2017-08-14 14:40:37 -0700536 if (!isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800537 ALOGD("Failed to delete Security Association, line=%d", __LINE__);
Nathan Harold1a371532017-01-30 12:30:48 -0800538 }
539
540 return ret;
541}
542
Nathan Harold7441c692017-12-12 21:25:01 -0800543netdutils::Status XfrmController::fillXfrmId(int32_t direction, const std::string& localAddress,
544 const std::string& remoteAddress, int32_t spi,
545 int32_t transformId, XfrmId* xfrmId) {
546 // Fill the straightforward fields first
547 xfrmId->transformId = transformId;
548 xfrmId->direction = static_cast<XfrmDirection>(direction);
549 xfrmId->spi = htonl(spi);
Nathan Harold1a371532017-01-30 12:30:48 -0800550
Nathan Harold7441c692017-12-12 21:25:01 -0800551 // Use the addresses to determine the address family and do validation
552 xfrm_address_t localXfrmAddr{}, remoteXfrmAddr{};
ludi6e8eccd2017-08-14 14:40:37 -0700553 StatusOr<int> addrFamilyLocal, addrFamilyRemote;
Nathan Harold1a371532017-01-30 12:30:48 -0800554 addrFamilyRemote = convertToXfrmAddr(remoteAddress, &remoteXfrmAddr);
555 addrFamilyLocal = convertToXfrmAddr(localAddress, &localXfrmAddr);
ludi6e8eccd2017-08-14 14:40:37 -0700556 if (!isOk(addrFamilyRemote) || !isOk(addrFamilyLocal)) {
557 return netdutils::statusFromErrno(EINVAL,
558 "Invalid address " + localAddress + "/" + remoteAddress);
Nathan Harold1a371532017-01-30 12:30:48 -0800559 }
560
ludi6e8eccd2017-08-14 14:40:37 -0700561 if (addrFamilyRemote.value() == AF_UNSPEC ||
562 (addrFamilyLocal.value() != AF_UNSPEC &&
563 addrFamilyLocal.value() != addrFamilyRemote.value())) {
564 ALOGD("Invalid or Mismatched Address Families, %d != %d, line=%d", addrFamilyLocal.value(),
565 addrFamilyRemote.value(), __LINE__);
566 return netdutils::statusFromErrno(EINVAL, "Invalid or mismatched address families");
Nathan Harold1a371532017-01-30 12:30:48 -0800567 }
568
ludi6e8eccd2017-08-14 14:40:37 -0700569 xfrmId->addrFamily = addrFamilyRemote.value();
Nathan Harold1a371532017-01-30 12:30:48 -0800570
Nathan Harold1a371532017-01-30 12:30:48 -0800571 switch (static_cast<XfrmDirection>(direction)) {
572 case XfrmDirection::IN:
573 xfrmId->dstAddr = localXfrmAddr;
574 xfrmId->srcAddr = remoteXfrmAddr;
575 break;
576
577 case XfrmDirection::OUT:
578 xfrmId->dstAddr = remoteXfrmAddr;
579 xfrmId->srcAddr = localXfrmAddr;
580 break;
581
582 default:
583 ALOGD("Invalid XFRM direction, line=%d", __LINE__);
584 // Invalid direction for Transport mode transform: time to bail
ludi6e8eccd2017-08-14 14:40:37 -0700585 return netdutils::statusFromErrno(EINVAL, "Invalid direction");
Nathan Harold1a371532017-01-30 12:30:48 -0800586 }
ludi6e8eccd2017-08-14 14:40:37 -0700587 return netdutils::status::ok;
Nathan Harold1a371532017-01-30 12:30:48 -0800588}
589
ludi6e8eccd2017-08-14 14:40:37 -0700590netdutils::Status XfrmController::ipSecApplyTransportModeTransform(
591 const android::base::unique_fd& socket, int32_t transformId, int32_t direction,
592 const std::string& localAddress, const std::string& remoteAddress, int32_t spi) {
Nathan Harold1a371532017-01-30 12:30:48 -0800593 ALOGD("XfrmController::%s, line=%d", __FUNCTION__, __LINE__);
594 ALOGD("transformId=%d", transformId);
595 ALOGD("direction=%d", direction);
596 ALOGD("localAddress=%s", localAddress.c_str());
597 ALOGD("remoteAddress=%s", remoteAddress.c_str());
598 ALOGD("spi=%0.8x", spi);
599
ludi4072ff22017-06-15 08:56:52 -0700600 StatusOr<sockaddr_storage> ret = getSyscallInstance().getsockname<sockaddr_storage>(Fd(socket));
601 if (!isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800602 ALOGE("Failed to get socket info in %s", __FUNCTION__);
ludi6e8eccd2017-08-14 14:40:37 -0700603 return ret;
Nathan Harold1a371532017-01-30 12:30:48 -0800604 }
Nathan Harold7441c692017-12-12 21:25:01 -0800605 struct sockaddr_storage saddr = ret.value();
ludi4072ff22017-06-15 08:56:52 -0700606
Nathan Harold1a371532017-01-30 12:30:48 -0800607 XfrmSaInfo saInfo{};
Nathan Harold7441c692017-12-12 21:25:01 -0800608 netdutils::Status status =
609 fillXfrmId(direction, localAddress, remoteAddress, spi, transformId, &saInfo);
ludi6e8eccd2017-08-14 14:40:37 -0700610 if (!isOk(status)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800611 ALOGE("Couldn't build SA ID %s", __FUNCTION__);
ludi6e8eccd2017-08-14 14:40:37 -0700612 return status;
Nathan Harold1a371532017-01-30 12:30:48 -0800613 }
614
manojboopathi26f42922017-12-14 10:51:57 -0800615 if (saddr.ss_family == AF_INET && saInfo.addrFamily != AF_INET) {
616 ALOGE("IPV4 socket address family(%d) should match IPV4 Transform "
617 "address family(%d)!",
618 saddr.ss_family, saInfo.addrFamily);
ludi6e8eccd2017-08-14 14:40:37 -0700619 return netdutils::statusFromErrno(EINVAL, "Mismatched address family");
Nathan Harold1a371532017-01-30 12:30:48 -0800620 }
621
622 struct {
623 xfrm_userpolicy_info info;
624 xfrm_user_tmpl tmpl;
625 } policy{};
626
627 fillTransportModeUserSpInfo(saInfo, &policy.info);
628 fillUserTemplate(saInfo, &policy.tmpl);
629
630 LOG_HEX("XfrmUserPolicy", reinterpret_cast<char*>(&policy), sizeof(policy));
631
632 int sockOpt, sockLayer;
manojboopathi26f42922017-12-14 10:51:57 -0800633 switch (saddr.ss_family) {
Nathan Harold1a371532017-01-30 12:30:48 -0800634 case AF_INET:
635 sockOpt = IP_XFRM_POLICY;
636 sockLayer = SOL_IP;
637 break;
638 case AF_INET6:
639 sockOpt = IPV6_XFRM_POLICY;
640 sockLayer = SOL_IPV6;
641 break;
642 default:
ludi6e8eccd2017-08-14 14:40:37 -0700643 return netdutils::statusFromErrno(EAFNOSUPPORT, "Invalid address family");
Nathan Harold1a371532017-01-30 12:30:48 -0800644 }
645
ludi6e8eccd2017-08-14 14:40:37 -0700646 status = getSyscallInstance().setsockopt(Fd(socket), sockLayer, sockOpt, policy);
ludi4072ff22017-06-15 08:56:52 -0700647 if (!isOk(status)) {
648 ALOGE("Error setting socket option for XFRM! (%s)", toString(status).c_str());
Nathan Harold1a371532017-01-30 12:30:48 -0800649 }
ludi6e8eccd2017-08-14 14:40:37 -0700650
651 return status;
Nathan Harold1a371532017-01-30 12:30:48 -0800652}
653
ludi6e8eccd2017-08-14 14:40:37 -0700654netdutils::Status
655XfrmController::ipSecRemoveTransportModeTransform(const android::base::unique_fd& socket) {
Nathan Harold1a371532017-01-30 12:30:48 -0800656 (void)socket;
ludi6e8eccd2017-08-14 14:40:37 -0700657 return netdutils::status::ok;
Nathan Harold1a371532017-01-30 12:30:48 -0800658}
659
660void XfrmController::fillTransportModeSelector(const XfrmSaInfo& record, xfrm_selector* selector) {
661 selector->family = record.addrFamily;
662 selector->proto = AF_UNSPEC; // TODO: do we need to match the protocol? it's
663 // possible via the socket
664 selector->ifindex = record.netId; // TODO : still need to sort this out
665}
666
Di Lu0e16b5e2018-01-12 10:37:53 -0800667netdutils::Status XfrmController::updateSecurityAssociation(const XfrmSaInfo& record,
manojboopathi4d2d6f12017-12-06 11:11:31 -0800668 const XfrmSocket& sock) {
Nathan Harold1a371532017-01-30 12:30:48 -0800669 xfrm_usersa_info usersa{};
670 nlattr_algo_crypt crypt{};
671 nlattr_algo_auth auth{};
Benedict Wongbe65b432017-08-22 21:43:14 -0700672 nlattr_algo_aead aead{};
Nathan Harold420ceac2017-04-05 19:36:59 -0700673 nlattr_encap_tmpl encap{};
Nathan Harold1a371532017-01-30 12:30:48 -0800674
Benedict Wongbe65b432017-08-22 21:43:14 -0700675 enum {
676 NLMSG_HDR,
677 USERSA,
678 USERSA_PAD,
679 CRYPT,
680 CRYPT_PAD,
681 AUTH,
682 AUTH_PAD,
683 AEAD,
684 AEAD_PAD,
685 ENCAP,
686 ENCAP_PAD
687 };
Nathan Harold1a371532017-01-30 12:30:48 -0800688
ludie51e3862017-08-15 19:28:12 -0700689 std::vector<iovec> iov = {
Nathan Harold1a371532017-01-30 12:30:48 -0800690 {NULL, 0}, // reserved for the eventual addition of a NLMSG_HDR
691 {&usersa, 0}, // main usersa_info struct
692 {kPadBytes, 0}, // up to NLMSG_ALIGNTO pad bytes of padding
693 {&crypt, 0}, // adjust size if crypt algo is present
694 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
695 {&auth, 0}, // adjust size if auth algo is present
696 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
Benedict Wongbe65b432017-08-22 21:43:14 -0700697 {&aead, 0}, // adjust size if aead algo is present
698 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
699 {&encap, 0}, // adjust size if encapsulating
Nathan Harold420ceac2017-04-05 19:36:59 -0700700 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
Nathan Harold1a371532017-01-30 12:30:48 -0800701 };
702
Benedict Wongbe65b432017-08-22 21:43:14 -0700703 if (!record.aead.name.empty() && (!record.auth.name.empty() || !record.crypt.name.empty())) {
704 return netdutils::statusFromErrno(EINVAL, "Invalid xfrm algo selection; AEAD is mutually "
705 "exclusive with both Authentication and "
706 "Encryption");
707 }
708
Benedict Wong4f60ee12017-10-10 12:27:25 -0700709 if (record.aead.key.size() > MAX_KEY_LENGTH || record.auth.key.size() > MAX_KEY_LENGTH ||
710 record.crypt.key.size() > MAX_KEY_LENGTH) {
711 return netdutils::statusFromErrno(EINVAL, "Key length invalid; exceeds MAX_KEY_LENGTH");
Benedict Wongbe65b432017-08-22 21:43:14 -0700712 }
713
Nathan Harold1a371532017-01-30 12:30:48 -0800714 int len;
715 len = iov[USERSA].iov_len = fillUserSaInfo(record, &usersa);
716 iov[USERSA_PAD].iov_len = NLMSG_ALIGN(len) - len;
717
718 len = iov[CRYPT].iov_len = fillNlAttrXfrmAlgoEnc(record.crypt, &crypt);
719 iov[CRYPT_PAD].iov_len = NLA_ALIGN(len) - len;
720
721 len = iov[AUTH].iov_len = fillNlAttrXfrmAlgoAuth(record.auth, &auth);
722 iov[AUTH_PAD].iov_len = NLA_ALIGN(len) - len;
723
Benedict Wongbe65b432017-08-22 21:43:14 -0700724 len = iov[AEAD].iov_len = fillNlAttrXfrmAlgoAead(record.aead, &aead);
725 iov[AEAD_PAD].iov_len = NLA_ALIGN(len) - len;
726
Nathan Harold420ceac2017-04-05 19:36:59 -0700727 len = iov[ENCAP].iov_len = fillNlAttrXfrmEncapTmpl(record, &encap);
728 iov[ENCAP_PAD].iov_len = NLA_ALIGN(len) - len;
ludie51e3862017-08-15 19:28:12 -0700729 return sock.sendMessage(XFRM_MSG_UPDSA, NETLINK_REQUEST_FLAGS, 0, &iov);
Nathan Harold1a371532017-01-30 12:30:48 -0800730}
731
732int XfrmController::fillNlAttrXfrmAlgoEnc(const XfrmAlgo& inAlgo, nlattr_algo_crypt* algo) {
Benedict Wongbe65b432017-08-22 21:43:14 -0700733 if (inAlgo.name.empty()) { // Do not fill anything if algorithm not provided
734 return 0;
735 }
736
Nathan Harold1a371532017-01-30 12:30:48 -0800737 int len = NLA_HDRLEN + sizeof(xfrm_algo);
Benedict Wongbe65b432017-08-22 21:43:14 -0700738 // Kernel always changes last char to null terminator; no safety checks needed.
Nathan Harold1a371532017-01-30 12:30:48 -0800739 strncpy(algo->crypt.alg_name, inAlgo.name.c_str(), sizeof(algo->crypt.alg_name));
Nathan Harold7441c692017-12-12 21:25:01 -0800740 algo->crypt.alg_key_len = inAlgo.key.size() * 8; // bits
Benedict Wongbe65b432017-08-22 21:43:14 -0700741 memcpy(algo->key, &inAlgo.key[0], inAlgo.key.size());
Nathan Harold1a371532017-01-30 12:30:48 -0800742 len += inAlgo.key.size();
743 fillXfrmNlaHdr(&algo->hdr, XFRMA_ALG_CRYPT, len);
744 return len;
745}
746
747int XfrmController::fillNlAttrXfrmAlgoAuth(const XfrmAlgo& inAlgo, nlattr_algo_auth* algo) {
Benedict Wongbe65b432017-08-22 21:43:14 -0700748 if (inAlgo.name.empty()) { // Do not fill anything if algorithm not provided
749 return 0;
750 }
751
Nathan Harold1a371532017-01-30 12:30:48 -0800752 int len = NLA_HDRLEN + sizeof(xfrm_algo_auth);
Benedict Wongbe65b432017-08-22 21:43:14 -0700753 // Kernel always changes last char to null terminator; no safety checks needed.
Nathan Harold1a371532017-01-30 12:30:48 -0800754 strncpy(algo->auth.alg_name, inAlgo.name.c_str(), sizeof(algo->auth.alg_name));
755 algo->auth.alg_key_len = inAlgo.key.size() * 8; // bits
756
757 // This is the extra field for ALG_AUTH_TRUNC
758 algo->auth.alg_trunc_len = inAlgo.truncLenBits;
759
Benedict Wongbe65b432017-08-22 21:43:14 -0700760 memcpy(algo->key, &inAlgo.key[0], inAlgo.key.size());
Nathan Harold1a371532017-01-30 12:30:48 -0800761 len += inAlgo.key.size();
762
763 fillXfrmNlaHdr(&algo->hdr, XFRMA_ALG_AUTH_TRUNC, len);
764 return len;
765}
766
Benedict Wongbe65b432017-08-22 21:43:14 -0700767int XfrmController::fillNlAttrXfrmAlgoAead(const XfrmAlgo& inAlgo, nlattr_algo_aead* algo) {
768 if (inAlgo.name.empty()) { // Do not fill anything if algorithm not provided
769 return 0;
770 }
771
772 int len = NLA_HDRLEN + sizeof(xfrm_algo_aead);
773 // Kernel always changes last char to null terminator; no safety checks needed.
774 strncpy(algo->aead.alg_name, inAlgo.name.c_str(), sizeof(algo->aead.alg_name));
775 algo->aead.alg_key_len = inAlgo.key.size() * 8; // bits
776
777 // This is the extra field for ALG_AEAD. ICV length is the same as truncation length
778 // for any AEAD algorithm.
779 algo->aead.alg_icv_len = inAlgo.truncLenBits;
780
781 memcpy(algo->key, &inAlgo.key[0], inAlgo.key.size());
782 len += inAlgo.key.size();
783
784 fillXfrmNlaHdr(&algo->hdr, XFRMA_ALG_AEAD, len);
785 return len;
786}
787
Nathan Harold420ceac2017-04-05 19:36:59 -0700788int XfrmController::fillNlAttrXfrmEncapTmpl(const XfrmSaInfo& record, nlattr_encap_tmpl* tmpl) {
789 if (record.encap.type == XfrmEncapType::NONE) {
790 return 0;
791 }
792
793 int len = NLA_HDRLEN + sizeof(xfrm_encap_tmpl);
794 tmpl->tmpl.encap_type = static_cast<uint16_t>(record.encap.type);
795 tmpl->tmpl.encap_sport = htons(record.encap.srcPort);
796 tmpl->tmpl.encap_dport = htons(record.encap.dstPort);
797 fillXfrmNlaHdr(&tmpl->hdr, XFRMA_ENCAP, len);
798 return len;
799}
800
Nathan Harold1a371532017-01-30 12:30:48 -0800801int XfrmController::fillUserSaInfo(const XfrmSaInfo& record, xfrm_usersa_info* usersa) {
802 fillTransportModeSelector(record, &usersa->sel);
803
804 usersa->id.proto = IPPROTO_ESP;
805 usersa->id.spi = record.spi;
806 usersa->id.daddr = record.dstAddr;
807
808 usersa->saddr = record.srcAddr;
809
810 fillXfrmLifetimeDefaults(&usersa->lft);
811 fillXfrmCurLifetimeDefaults(&usersa->curlft);
812 memset(&usersa->stats, 0, sizeof(usersa->stats)); // leave stats zeroed out
813 usersa->reqid = record.transformId;
814 usersa->family = record.addrFamily;
815 usersa->mode = static_cast<uint8_t>(record.mode);
816 usersa->replay_window = REPLAY_WINDOW_SIZE;
manojboopathi4d2d6f12017-12-06 11:11:31 -0800817
818 if (record.mode == XfrmMode::TRANSPORT) {
819 usersa->flags = 0; // TODO: should we actually set flags, XFRM_SA_XFLAG_DONT_ENCAP_DSCP?
820 } else {
821 usersa->flags = XFRM_STATE_AF_UNSPEC;
822 }
823
Nathan Harold1a371532017-01-30 12:30:48 -0800824 return sizeof(*usersa);
825}
826
Nathan Harold7441c692017-12-12 21:25:01 -0800827int XfrmController::fillUserSaId(const XfrmId& record, xfrm_usersa_id* said) {
Nathan Harold1a371532017-01-30 12:30:48 -0800828 said->daddr = record.dstAddr;
829 said->spi = record.spi;
830 said->family = record.addrFamily;
831 said->proto = IPPROTO_ESP;
832
833 return sizeof(*said);
834}
835
Nathan Harold7441c692017-12-12 21:25:01 -0800836netdutils::Status XfrmController::deleteSecurityAssociation(const XfrmId& record,
ludi6e8eccd2017-08-14 14:40:37 -0700837 const XfrmSocket& sock) {
Nathan Harold1a371532017-01-30 12:30:48 -0800838 xfrm_usersa_id said{};
839
ludie51e3862017-08-15 19:28:12 -0700840 enum { NLMSG_HDR, USERSAID, USERSAID_PAD };
Nathan Harold1a371532017-01-30 12:30:48 -0800841
ludie51e3862017-08-15 19:28:12 -0700842 std::vector<iovec> iov = {
Nathan Harold1a371532017-01-30 12:30:48 -0800843 {NULL, 0}, // reserved for the eventual addition of a NLMSG_HDR
844 {&said, 0}, // main usersa_info struct
845 {kPadBytes, 0}, // up to NLMSG_ALIGNTO pad bytes of padding
846 };
847
848 int len;
849 len = iov[USERSAID].iov_len = fillUserSaId(record, &said);
850 iov[USERSAID_PAD].iov_len = NLMSG_ALIGN(len) - len;
851
ludie51e3862017-08-15 19:28:12 -0700852 return sock.sendMessage(XFRM_MSG_DELSA, NETLINK_REQUEST_FLAGS, 0, &iov);
Nathan Harold1a371532017-01-30 12:30:48 -0800853}
854
ludi6e8eccd2017-08-14 14:40:37 -0700855netdutils::Status XfrmController::allocateSpi(const XfrmSaInfo& record, uint32_t minSpi,
856 uint32_t maxSpi, uint32_t* outSpi,
857 const XfrmSocket& sock) {
Nathan Harold1a371532017-01-30 12:30:48 -0800858 xfrm_userspi_info spiInfo{};
859
ludie51e3862017-08-15 19:28:12 -0700860 enum { NLMSG_HDR, USERSAID, USERSAID_PAD };
Nathan Harold1a371532017-01-30 12:30:48 -0800861
ludie51e3862017-08-15 19:28:12 -0700862 std::vector<iovec> iov = {
Nathan Harold1a371532017-01-30 12:30:48 -0800863 {NULL, 0}, // reserved for the eventual addition of a NLMSG_HDR
864 {&spiInfo, 0}, // main userspi_info struct
865 {kPadBytes, 0}, // up to NLMSG_ALIGNTO pad bytes of padding
866 };
867
868 int len;
869 if (fillUserSaInfo(record, &spiInfo.info) == 0) {
870 ALOGE("Failed to fill transport SA Info");
871 }
872
873 len = iov[USERSAID].iov_len = sizeof(spiInfo);
874 iov[USERSAID_PAD].iov_len = NLMSG_ALIGN(len) - len;
875
876 RandomSpi spiGen = RandomSpi(minSpi, maxSpi);
ludi6e8eccd2017-08-14 14:40:37 -0700877 int spi;
878 netdutils::Status ret;
Nathan Harold1a371532017-01-30 12:30:48 -0800879 while ((spi = spiGen.next()) != INVALID_SPI) {
880 spiInfo.min = spi;
881 spiInfo.max = spi;
ludie51e3862017-08-15 19:28:12 -0700882 ret = sock.sendMessage(XFRM_MSG_ALLOCSPI, NETLINK_REQUEST_FLAGS, 0, &iov);
Nathan Harold1a371532017-01-30 12:30:48 -0800883
884 /* If the SPI is in use, we'll get ENOENT */
ludi6e8eccd2017-08-14 14:40:37 -0700885 if (netdutils::equalToErrno(ret, ENOENT))
Nathan Harold1a371532017-01-30 12:30:48 -0800886 continue;
887
ludi6e8eccd2017-08-14 14:40:37 -0700888 if (isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800889 *outSpi = spi;
Nathan Harold420ceac2017-04-05 19:36:59 -0700890 ALOGD("Allocated an SPI: %x", *outSpi);
Nathan Harold1a371532017-01-30 12:30:48 -0800891 } else {
892 *outSpi = INVALID_SPI;
ludi6e8eccd2017-08-14 14:40:37 -0700893 ALOGE("SPI Allocation Failed with error %d", ret.code());
Nathan Harold1a371532017-01-30 12:30:48 -0800894 }
895
896 return ret;
897 }
898
899 // Should always be -ENOENT if we get here
900 return ret;
901}
902
903int XfrmController::fillTransportModeUserSpInfo(const XfrmSaInfo& record,
904 xfrm_userpolicy_info* usersp) {
905 fillTransportModeSelector(record, &usersp->sel);
906 fillXfrmLifetimeDefaults(&usersp->lft);
907 fillXfrmCurLifetimeDefaults(&usersp->curlft);
Nathan Harold420ceac2017-04-05 19:36:59 -0700908 /* if (index) index & 0x3 == dir -- must be true
909 * xfrm_user.c:verify_newpolicy_info() */
Nathan Harold1a371532017-01-30 12:30:48 -0800910 usersp->index = 0;
911 usersp->dir = static_cast<uint8_t>(record.direction);
912 usersp->action = XFRM_POLICY_ALLOW;
913 usersp->flags = XFRM_POLICY_LOCALOK;
914 usersp->share = XFRM_SHARE_UNIQUE;
915 return sizeof(*usersp);
916}
917
918int XfrmController::fillUserTemplate(const XfrmSaInfo& record, xfrm_user_tmpl* tmpl) {
919 tmpl->id.daddr = record.dstAddr;
920 tmpl->id.spi = record.spi;
921 tmpl->id.proto = IPPROTO_ESP;
922
923 tmpl->family = record.addrFamily;
924 tmpl->saddr = record.srcAddr;
925 tmpl->reqid = record.transformId;
926 tmpl->mode = static_cast<uint8_t>(record.mode);
927 tmpl->share = XFRM_SHARE_UNIQUE;
928 tmpl->optional = 0; // if this is true, then a failed state lookup will be considered OK:
929 // http://lxr.free-electrons.com/source/net/xfrm/xfrm_policy.c#L1492
930 tmpl->aalgos = ALGO_MASK_AUTH_ALL; // TODO: if there's a bitmask somewhere of
931 // algos, we should find it and apply it.
932 // I can't find one.
933 tmpl->ealgos = ALGO_MASK_CRYPT_ALL; // TODO: if there's a bitmask somewhere...
934 return 0;
935}
936
937} // namespace net
938} // namespace android