blob: 2721013956304a50716ce819cdfa370774ab1dfb [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"
48#define LOG_TAG "XfrmController"
49#include "NetdConstants.h"
50#include "NetlinkCommands.h"
51#include "ResponseCode.h"
52#include "XfrmController.h"
ludi4072ff22017-06-15 08:56:52 -070053#include "netdutils/Fd.h"
54#include "netdutils/Slice.h"
55#include "netdutils/Syscalls.h"
Nathan Harold1a371532017-01-30 12:30:48 -080056#include <cutils/log.h>
57#include <cutils/properties.h>
58#include <logwrap/logwrap.h>
59
60#define VDBG 1 // STOPSHIP if true
61
ludi4072ff22017-06-15 08:56:52 -070062using android::netdutils::Fd;
63using android::netdutils::Slice;
64using android::netdutils::Status;
65using android::netdutils::StatusOr;
66using android::netdutils::Syscalls;
67
Nathan Harold1a371532017-01-30 12:30:48 -080068namespace android {
69namespace net {
70
Nathan Harold39b5df42017-08-02 18:45:25 -070071// Exposed for testing
Nathan Harold1a371532017-01-30 12:30:48 -080072constexpr uint32_t ALGO_MASK_AUTH_ALL = ~0;
Nathan Harold39b5df42017-08-02 18:45:25 -070073// Exposed for testing
Nathan Harold1a371532017-01-30 12:30:48 -080074constexpr uint32_t ALGO_MASK_CRYPT_ALL = ~0;
Nathan Harold39b5df42017-08-02 18:45:25 -070075// Exposed for testing
Nathan Harold1a371532017-01-30 12:30:48 -080076constexpr uint8_t REPLAY_WINDOW_SIZE = 4;
77
Nathan Harold39b5df42017-08-02 18:45:25 -070078namespace {
79
Nathan Harold1a371532017-01-30 12:30:48 -080080constexpr uint32_t RAND_SPI_MIN = 1;
81constexpr uint32_t RAND_SPI_MAX = 0xFFFFFFFE;
82
83constexpr uint32_t INVALID_SPI = 0;
84
85#define XFRM_MSG_TRANS(x) \
86 case x: \
87 return #x;
88
89const char* xfrmMsgTypeToString(uint16_t msg) {
90 switch (msg) {
91 XFRM_MSG_TRANS(XFRM_MSG_NEWSA)
92 XFRM_MSG_TRANS(XFRM_MSG_DELSA)
93 XFRM_MSG_TRANS(XFRM_MSG_GETSA)
94 XFRM_MSG_TRANS(XFRM_MSG_NEWPOLICY)
95 XFRM_MSG_TRANS(XFRM_MSG_DELPOLICY)
96 XFRM_MSG_TRANS(XFRM_MSG_GETPOLICY)
97 XFRM_MSG_TRANS(XFRM_MSG_ALLOCSPI)
98 XFRM_MSG_TRANS(XFRM_MSG_ACQUIRE)
99 XFRM_MSG_TRANS(XFRM_MSG_EXPIRE)
100 XFRM_MSG_TRANS(XFRM_MSG_UPDPOLICY)
101 XFRM_MSG_TRANS(XFRM_MSG_UPDSA)
102 XFRM_MSG_TRANS(XFRM_MSG_POLEXPIRE)
103 XFRM_MSG_TRANS(XFRM_MSG_FLUSHSA)
104 XFRM_MSG_TRANS(XFRM_MSG_FLUSHPOLICY)
105 XFRM_MSG_TRANS(XFRM_MSG_NEWAE)
106 XFRM_MSG_TRANS(XFRM_MSG_GETAE)
107 XFRM_MSG_TRANS(XFRM_MSG_REPORT)
108 XFRM_MSG_TRANS(XFRM_MSG_MIGRATE)
109 XFRM_MSG_TRANS(XFRM_MSG_NEWSADINFO)
110 XFRM_MSG_TRANS(XFRM_MSG_GETSADINFO)
111 XFRM_MSG_TRANS(XFRM_MSG_GETSPDINFO)
112 XFRM_MSG_TRANS(XFRM_MSG_NEWSPDINFO)
113 XFRM_MSG_TRANS(XFRM_MSG_MAPPING)
114 default:
115 return "XFRM_MSG UNKNOWN";
116 }
117}
118
119// actually const but cannot be declared as such for reasons
120uint8_t kPadBytesArray[] = {0, 0, 0};
121void* kPadBytes = static_cast<void*>(kPadBytesArray);
122
123#if VDBG
Nathan Harold420ceac2017-04-05 19:36:59 -0700124#define LOG_HEX(__desc16__, __buf__, __len__) \
125 do { \
126 logHex(__desc16__, __buf__, __len__); \
127 } while (0)
ludie51e3862017-08-15 19:28:12 -0700128#define LOG_IOV(__iov__) \
Nathan Harold420ceac2017-04-05 19:36:59 -0700129 do { \
ludie51e3862017-08-15 19:28:12 -0700130 logIov(__iov__); \
Nathan Harold420ceac2017-04-05 19:36:59 -0700131 } while (0)
Nathan Harold1a371532017-01-30 12:30:48 -0800132
133void logHex(const char* desc16, const char* buf, size_t len) {
134 char* printBuf = new char[len * 2 + 1 + 26]; // len->ascii, +newline, +prefix strlen
135 int offset = 0;
136 if (desc16) {
137 sprintf(printBuf, "{%-16s}", desc16);
138 offset += 18; // prefix string length
139 }
140 sprintf(printBuf + offset, "[%4.4u]: ", (len > 9999) ? 9999 : (unsigned)len);
141 offset += 8;
142
143 for (uint32_t j = 0; j < (uint32_t)len; j++) {
144 sprintf(&printBuf[j * 2 + offset], "%0.2x", buf[j]);
145 }
146 ALOGD("%s", printBuf);
147 delete[] printBuf;
148}
149
ludie51e3862017-08-15 19:28:12 -0700150void logIov(const std::vector<iovec>& iov) {
151 for (const iovec& row : iov) {
152 logHex(0, reinterpret_cast<char*>(row.iov_base), row.iov_len);
Nathan Harold1a371532017-01-30 12:30:48 -0800153 }
154}
155
ludi6e8eccd2017-08-14 14:40:37 -0700156// TODO: Need to consider a way to refer to the sSycalls instance
ludi4072ff22017-06-15 08:56:52 -0700157inline Syscalls& getSyscallInstance() { return netdutils::sSyscalls.get(); }
158
Nathan Harold1a371532017-01-30 12:30:48 -0800159#else
160#define LOG_HEX(__desc16__, __buf__, __len__)
161#define LOG_IOV(__iov__, __iov_len__)
162#endif
163
164class 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));
240 if (VDBG)
ludie51e3862017-08-15 19:28:12 -0700241 LOG_IOV(*iovecs);
Nathan Harold1a371532017-01-30 12:30:48 -0800242
ludie51e3862017-08-15 19:28:12 -0700243 StatusOr<size_t> writeResult = getSyscallInstance().writev(mSock, *iovecs);
ludi4072ff22017-06-15 08:56:52 -0700244 if (!isOk(writeResult)) {
245 ALOGE("netlink socket writev failed (%s)", toString(writeResult).c_str());
ludi6e8eccd2017-08-14 14:40:37 -0700246 return writeResult;
Nathan Harold1a371532017-01-30 12:30:48 -0800247 }
248
ludi4072ff22017-06-15 08:56:52 -0700249 if (nlMsg.nlmsg_len != writeResult.value()) {
250 ALOGE("Invalid netlink message length sent %d", static_cast<int>(writeResult.value()));
ludi6e8eccd2017-08-14 14:40:37 -0700251 return netdutils::statusFromErrno(EBADMSG, "Invalid message length");
Nathan Harold1a371532017-01-30 12:30:48 -0800252 }
253
ludi4072ff22017-06-15 08:56:52 -0700254 NetlinkResponse response = {};
Nathan Harold1a371532017-01-30 12:30:48 -0800255
ludi4072ff22017-06-15 08:56:52 -0700256 StatusOr<Slice> readResult =
257 getSyscallInstance().read(Fd(mSock), netdutils::makeSlice(response));
258 if (!isOk(readResult)) {
259 ALOGE("netlink response error (%s)", toString(readResult).c_str());
ludi6e8eccd2017-08-14 14:40:37 -0700260 return readResult;
ludi4072ff22017-06-15 08:56:52 -0700261 }
262
263 LOG_HEX("netlink msg resp", reinterpret_cast<char*>(readResult.value().base()),
264 readResult.value().size());
265
ludi6e8eccd2017-08-14 14:40:37 -0700266 Status validateStatus = validateResponse(response, readResult.value().size());
267 if (!isOk(validateStatus)) {
268 ALOGE("netlink response contains error (%s)", toString(validateStatus).c_str());
269 }
270
271 return validateStatus;
Nathan Harold1a371532017-01-30 12:30:48 -0800272 }
273};
274
ludi6e8eccd2017-08-14 14:40:37 -0700275StatusOr<int> convertToXfrmAddr(const std::string& strAddr, xfrm_address_t* xfrmAddr) {
Nathan Harold1a371532017-01-30 12:30:48 -0800276 if (strAddr.length() == 0) {
277 memset(xfrmAddr, 0, sizeof(*xfrmAddr));
278 return AF_UNSPEC;
279 }
280
281 if (inet_pton(AF_INET6, strAddr.c_str(), reinterpret_cast<void*>(xfrmAddr))) {
282 return AF_INET6;
283 } else if (inet_pton(AF_INET, strAddr.c_str(), reinterpret_cast<void*>(xfrmAddr))) {
284 return AF_INET;
285 } else {
ludi6e8eccd2017-08-14 14:40:37 -0700286 return netdutils::statusFromErrno(EAFNOSUPPORT, "Invalid address family");
Nathan Harold1a371532017-01-30 12:30:48 -0800287 }
288}
289
290void fillXfrmNlaHdr(nlattr* hdr, uint16_t type, uint16_t len) {
291 hdr->nla_type = type;
292 hdr->nla_len = len;
293}
294
295void fillXfrmCurLifetimeDefaults(xfrm_lifetime_cur* cur) {
296 memset(reinterpret_cast<char*>(cur), 0, sizeof(*cur));
297}
298void fillXfrmLifetimeDefaults(xfrm_lifetime_cfg* cfg) {
299 cfg->soft_byte_limit = XFRM_INF;
300 cfg->hard_byte_limit = XFRM_INF;
301 cfg->soft_packet_limit = XFRM_INF;
302 cfg->hard_packet_limit = XFRM_INF;
303}
304
305/*
306 * Allocate SPIs within an (inclusive) range of min-max.
307 * returns 0 (INVALID_SPI) once the entire range has been parsed.
308 */
309class RandomSpi {
310public:
311 RandomSpi(int min, int max) : mMin(min) {
Nathan Harold1e284452017-10-10 13:31:19 -0700312 // Re-seeding should be safe because the seed itself is
313 // sufficiently random and we don't need secure random
314 std::mt19937 rnd = std::mt19937(std::random_device()());
315 mNext = std::uniform_int_distribution<>(1, INT_MAX)(rnd);
Nathan Harold1a371532017-01-30 12:30:48 -0800316 mSize = max - min + 1;
317 mCount = mSize;
318 }
319
320 uint32_t next() {
321 if (!mCount)
322 return 0;
323 mCount--;
324 return (mNext++ % mSize) + mMin;
325 }
326
327private:
328 uint32_t mNext;
329 uint32_t mSize;
330 uint32_t mMin;
331 uint32_t mCount;
332};
333
334} // namespace
335
336//
337// Begin XfrmController Impl
338//
339//
340XfrmController::XfrmController(void) {}
341
ludi6e8eccd2017-08-14 14:40:37 -0700342netdutils::Status XfrmController::ipSecAllocateSpi(int32_t transformId, int32_t direction,
343 const std::string& localAddress,
344 const std::string& remoteAddress, int32_t inSpi,
345 int32_t* outSpi) {
Nathan Harold1a371532017-01-30 12:30:48 -0800346 ALOGD("XfrmController:%s, line=%d", __FUNCTION__, __LINE__);
347 ALOGD("transformId=%d", transformId);
348 ALOGD("direction=%d", direction);
349 ALOGD("localAddress=%s", localAddress.c_str());
350 ALOGD("remoteAddress=%s", remoteAddress.c_str());
351 ALOGD("inSpi=%0.8x", inSpi);
352
353 XfrmSaInfo saInfo{};
Nathan Harold1a371532017-01-30 12:30:48 -0800354
ludi6e8eccd2017-08-14 14:40:37 -0700355 netdutils::Status ret =
356 fillXfrmSaId(direction, localAddress, remoteAddress, INVALID_SPI, &saInfo);
357 if (!isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800358 return ret;
359 }
360
361 XfrmSocketImpl sock;
ludi6e8eccd2017-08-14 14:40:37 -0700362 netdutils::Status socketStatus = sock.open();
363 if (!isOk(socketStatus)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800364 ALOGD("Sock open failed for XFRM, line=%d", __LINE__);
ludi6e8eccd2017-08-14 14:40:37 -0700365 return socketStatus;
Nathan Harold1a371532017-01-30 12:30:48 -0800366 }
367
368 int minSpi = RAND_SPI_MIN, maxSpi = RAND_SPI_MAX;
369
370 if (inSpi)
371 minSpi = maxSpi = inSpi;
ludi6e8eccd2017-08-14 14:40:37 -0700372
Nathan Harold1a371532017-01-30 12:30:48 -0800373 ret = allocateSpi(saInfo, minSpi, maxSpi, reinterpret_cast<uint32_t*>(outSpi), sock);
ludi6e8eccd2017-08-14 14:40:37 -0700374 if (!isOk(ret)) {
375 // TODO: May want to return a new Status with a modified status string
Nathan Harold1a371532017-01-30 12:30:48 -0800376 ALOGD("Failed to Allocate an SPI, line=%d", __LINE__);
377 *outSpi = INVALID_SPI;
378 }
379
380 return ret;
381}
382
ludi6e8eccd2017-08-14 14:40:37 -0700383netdutils::Status XfrmController::ipSecAddSecurityAssociation(
Nathan Harold1a371532017-01-30 12:30:48 -0800384 int32_t transformId, int32_t mode, int32_t direction, const std::string& localAddress,
Nathan Harold420ceac2017-04-05 19:36:59 -0700385 const std::string& remoteAddress, int64_t underlyingNetworkHandle, int32_t spi,
Nathan Harold1a371532017-01-30 12:30:48 -0800386 const std::string& authAlgo, const std::vector<uint8_t>& authKey, int32_t authTruncBits,
387 const std::string& cryptAlgo, const std::vector<uint8_t>& cryptKey, int32_t cryptTruncBits,
ludiec836052017-05-20 14:17:05 -0700388 int32_t encapType, int32_t encapLocalPort, int32_t encapRemotePort) {
Nathan Harold1a371532017-01-30 12:30:48 -0800389 android::RWLock::AutoWLock lock(mLock);
390
391 ALOGD("XfrmController::%s, line=%d", __FUNCTION__, __LINE__);
392 ALOGD("transformId=%d", transformId);
393 ALOGD("mode=%d", mode);
394 ALOGD("direction=%d", direction);
395 ALOGD("localAddress=%s", localAddress.c_str());
396 ALOGD("remoteAddress=%s", remoteAddress.c_str());
Nathan Harold420ceac2017-04-05 19:36:59 -0700397 ALOGD("underlyingNetworkHandle=%" PRIx64, underlyingNetworkHandle);
Nathan Harold1a371532017-01-30 12:30:48 -0800398 ALOGD("spi=%0.8x", spi);
399 ALOGD("authAlgo=%s", authAlgo.c_str());
400 ALOGD("authTruncBits=%d", authTruncBits);
401 ALOGD("cryptAlgo=%s", cryptAlgo.c_str());
402 ALOGD("cryptTruncBits=%d,", cryptTruncBits);
403 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
415 // STOPSHIP : range check the key lengths to prevent puncturing and overflow
416 saInfo.auth = XfrmAlgo{
417 .name = authAlgo, .key = authKey, .truncLenBits = static_cast<uint16_t>(authTruncBits)};
418
419 saInfo.crypt = XfrmAlgo{
420 .name = cryptAlgo, .key = cryptKey, .truncLenBits = static_cast<uint16_t>(cryptTruncBits)};
421
422 saInfo.direction = static_cast<XfrmDirection>(direction);
423
424 switch (static_cast<XfrmMode>(mode)) {
425 case XfrmMode::TRANSPORT:
426 case XfrmMode::TUNNEL:
427 saInfo.mode = static_cast<XfrmMode>(mode);
428 break;
429 default:
ludi6e8eccd2017-08-14 14:40:37 -0700430 return netdutils::statusFromErrno(EINVAL, "Invalid xfrm mode");
Nathan Harold1a371532017-01-30 12:30:48 -0800431 }
432
433 XfrmSocketImpl sock;
ludi6e8eccd2017-08-14 14:40:37 -0700434 netdutils::Status socketStatus = sock.open();
435 if (!isOk(socketStatus)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800436 ALOGD("Sock open failed for XFRM, line=%d", __LINE__);
ludi6e8eccd2017-08-14 14:40:37 -0700437 return socketStatus;
Nathan Harold1a371532017-01-30 12:30:48 -0800438 }
439
Nathan Harold420ceac2017-04-05 19:36:59 -0700440 switch (static_cast<XfrmEncapType>(encapType)) {
441 case XfrmEncapType::ESPINUDP:
442 case XfrmEncapType::ESPINUDP_NON_IKE:
443 if (saInfo.addrFamily != AF_INET) {
ludi6e8eccd2017-08-14 14:40:37 -0700444 return netdutils::statusFromErrno(EAFNOSUPPORT, "IPv6 encap not supported");
Nathan Harold420ceac2017-04-05 19:36:59 -0700445 }
446 switch (saInfo.direction) {
447 case XfrmDirection::IN:
448 saInfo.encap.srcPort = encapRemotePort;
449 saInfo.encap.dstPort = encapLocalPort;
450 break;
451 case XfrmDirection::OUT:
452 saInfo.encap.srcPort = encapLocalPort;
453 saInfo.encap.dstPort = encapRemotePort;
454 break;
455 default:
ludi6e8eccd2017-08-14 14:40:37 -0700456 return netdutils::statusFromErrno(EINVAL, "Invalid direction");
Nathan Harold420ceac2017-04-05 19:36:59 -0700457 }
458 // fall through
459 case XfrmEncapType::NONE:
460 saInfo.encap.type = static_cast<XfrmEncapType>(encapType);
461 break;
462 default:
ludi6e8eccd2017-08-14 14:40:37 -0700463 return netdutils::statusFromErrno(EINVAL, "Invalid encap type");
Nathan Harold420ceac2017-04-05 19:36:59 -0700464 }
465
Nathan Harold1a371532017-01-30 12:30:48 -0800466 ret = createTransportModeSecurityAssociation(saInfo, sock);
ludi6e8eccd2017-08-14 14:40:37 -0700467 if (!isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800468 ALOGD("Failed creating a Security Association, line=%d", __LINE__);
Nathan Harold1a371532017-01-30 12:30:48 -0800469 }
470
ludi6e8eccd2017-08-14 14:40:37 -0700471 return ret;
Nathan Harold1a371532017-01-30 12:30:48 -0800472}
473
ludi6e8eccd2017-08-14 14:40:37 -0700474netdutils::Status XfrmController::ipSecDeleteSecurityAssociation(int32_t transformId,
475 int32_t direction,
476 const std::string& localAddress,
477 const std::string& remoteAddress,
478 int32_t spi) {
Nathan Harold1a371532017-01-30 12:30:48 -0800479 ALOGD("XfrmController:%s, line=%d", __FUNCTION__, __LINE__);
480 ALOGD("transformId=%d", transformId);
481 ALOGD("direction=%d", direction);
482 ALOGD("localAddress=%s", localAddress.c_str());
483 ALOGD("remoteAddress=%s", remoteAddress.c_str());
484 ALOGD("spi=%0.8x", spi);
485
Jonathan Basseriebdaa682017-09-14 16:33:08 -0700486 XfrmSaId saId{};
ludi6e8eccd2017-08-14 14:40:37 -0700487 netdutils::Status ret = fillXfrmSaId(direction, localAddress, remoteAddress, spi, &saId);
488 if (!isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800489 return ret;
490 }
491
492 XfrmSocketImpl sock;
ludi6e8eccd2017-08-14 14:40:37 -0700493 netdutils::Status socketStatus = sock.open();
494 if (!isOk(socketStatus)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800495 ALOGD("Sock open failed for XFRM, line=%d", __LINE__);
ludi6e8eccd2017-08-14 14:40:37 -0700496 return socketStatus;
Nathan Harold1a371532017-01-30 12:30:48 -0800497 }
498
499 ret = deleteSecurityAssociation(saId, sock);
ludi6e8eccd2017-08-14 14:40:37 -0700500 if (!isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800501 ALOGD("Failed to delete Security Association, line=%d", __LINE__);
Nathan Harold1a371532017-01-30 12:30:48 -0800502 }
503
504 return ret;
505}
506
ludi6e8eccd2017-08-14 14:40:37 -0700507netdutils::Status XfrmController::fillXfrmSaId(int32_t direction, const std::string& localAddress,
508 const std::string& remoteAddress, int32_t spi,
509 XfrmSaId* xfrmId) {
Nathan Harold1a371532017-01-30 12:30:48 -0800510 xfrm_address_t localXfrmAddr{}, remoteXfrmAddr{};
511
ludi6e8eccd2017-08-14 14:40:37 -0700512 StatusOr<int> addrFamilyLocal, addrFamilyRemote;
Nathan Harold1a371532017-01-30 12:30:48 -0800513 addrFamilyRemote = convertToXfrmAddr(remoteAddress, &remoteXfrmAddr);
514 addrFamilyLocal = convertToXfrmAddr(localAddress, &localXfrmAddr);
ludi6e8eccd2017-08-14 14:40:37 -0700515 if (!isOk(addrFamilyRemote) || !isOk(addrFamilyLocal)) {
516 return netdutils::statusFromErrno(EINVAL,
517 "Invalid address " + localAddress + "/" + remoteAddress);
Nathan Harold1a371532017-01-30 12:30:48 -0800518 }
519
ludi6e8eccd2017-08-14 14:40:37 -0700520 if (addrFamilyRemote.value() == AF_UNSPEC ||
521 (addrFamilyLocal.value() != AF_UNSPEC &&
522 addrFamilyLocal.value() != addrFamilyRemote.value())) {
523 ALOGD("Invalid or Mismatched Address Families, %d != %d, line=%d", addrFamilyLocal.value(),
524 addrFamilyRemote.value(), __LINE__);
525 return netdutils::statusFromErrno(EINVAL, "Invalid or mismatched address families");
Nathan Harold1a371532017-01-30 12:30:48 -0800526 }
527
ludi6e8eccd2017-08-14 14:40:37 -0700528 xfrmId->addrFamily = addrFamilyRemote.value();
Nathan Harold1a371532017-01-30 12:30:48 -0800529
530 xfrmId->spi = htonl(spi);
531
532 switch (static_cast<XfrmDirection>(direction)) {
533 case XfrmDirection::IN:
534 xfrmId->dstAddr = localXfrmAddr;
535 xfrmId->srcAddr = remoteXfrmAddr;
536 break;
537
538 case XfrmDirection::OUT:
539 xfrmId->dstAddr = remoteXfrmAddr;
540 xfrmId->srcAddr = localXfrmAddr;
541 break;
542
543 default:
544 ALOGD("Invalid XFRM direction, line=%d", __LINE__);
545 // Invalid direction for Transport mode transform: time to bail
ludi6e8eccd2017-08-14 14:40:37 -0700546 return netdutils::statusFromErrno(EINVAL, "Invalid direction");
Nathan Harold1a371532017-01-30 12:30:48 -0800547 }
ludi6e8eccd2017-08-14 14:40:37 -0700548 return netdutils::status::ok;
Nathan Harold1a371532017-01-30 12:30:48 -0800549}
550
ludi6e8eccd2017-08-14 14:40:37 -0700551netdutils::Status XfrmController::ipSecApplyTransportModeTransform(
552 const android::base::unique_fd& socket, int32_t transformId, int32_t direction,
553 const std::string& localAddress, const std::string& remoteAddress, int32_t spi) {
Nathan Harold1a371532017-01-30 12:30:48 -0800554 ALOGD("XfrmController::%s, line=%d", __FUNCTION__, __LINE__);
555 ALOGD("transformId=%d", transformId);
556 ALOGD("direction=%d", direction);
557 ALOGD("localAddress=%s", localAddress.c_str());
558 ALOGD("remoteAddress=%s", remoteAddress.c_str());
559 ALOGD("spi=%0.8x", spi);
560
561 struct sockaddr_storage saddr;
562
ludi4072ff22017-06-15 08:56:52 -0700563 StatusOr<sockaddr_storage> ret = getSyscallInstance().getsockname<sockaddr_storage>(Fd(socket));
564 if (!isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800565 ALOGE("Failed to get socket info in %s", __FUNCTION__);
ludi6e8eccd2017-08-14 14:40:37 -0700566 return ret;
Nathan Harold1a371532017-01-30 12:30:48 -0800567 }
568
ludi4072ff22017-06-15 08:56:52 -0700569 saddr = ret.value();
570
Nathan Harold1a371532017-01-30 12:30:48 -0800571 XfrmSaInfo saInfo{};
572 saInfo.transformId = transformId;
573 saInfo.direction = static_cast<XfrmDirection>(direction);
574 saInfo.spi = spi;
575
ludi6e8eccd2017-08-14 14:40:37 -0700576 netdutils::Status status = fillXfrmSaId(direction, localAddress, remoteAddress, spi, &saInfo);
577 if (!isOk(status)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800578 ALOGE("Couldn't build SA ID %s", __FUNCTION__);
ludi6e8eccd2017-08-14 14:40:37 -0700579 return status;
Nathan Harold1a371532017-01-30 12:30:48 -0800580 }
581
582 if (saInfo.addrFamily != saddr.ss_family) {
583 ALOGE("Transform address family(%d) differs from socket address "
Nathan Harold420ceac2017-04-05 19:36:59 -0700584 "family(%d)!",
585 saInfo.addrFamily, saddr.ss_family);
ludi6e8eccd2017-08-14 14:40:37 -0700586 return netdutils::statusFromErrno(EINVAL, "Mismatched address family");
Nathan Harold1a371532017-01-30 12:30:48 -0800587 }
588
589 struct {
590 xfrm_userpolicy_info info;
591 xfrm_user_tmpl tmpl;
592 } policy{};
593
594 fillTransportModeUserSpInfo(saInfo, &policy.info);
595 fillUserTemplate(saInfo, &policy.tmpl);
596
597 LOG_HEX("XfrmUserPolicy", reinterpret_cast<char*>(&policy), sizeof(policy));
598
599 int sockOpt, sockLayer;
600 switch (saInfo.addrFamily) {
601 case AF_INET:
602 sockOpt = IP_XFRM_POLICY;
603 sockLayer = SOL_IP;
604 break;
605 case AF_INET6:
606 sockOpt = IPV6_XFRM_POLICY;
607 sockLayer = SOL_IPV6;
608 break;
609 default:
ludi6e8eccd2017-08-14 14:40:37 -0700610 return netdutils::statusFromErrno(EAFNOSUPPORT, "Invalid address family");
Nathan Harold1a371532017-01-30 12:30:48 -0800611 }
612
ludi6e8eccd2017-08-14 14:40:37 -0700613 status = getSyscallInstance().setsockopt(Fd(socket), sockLayer, sockOpt, policy);
ludi4072ff22017-06-15 08:56:52 -0700614 if (!isOk(status)) {
615 ALOGE("Error setting socket option for XFRM! (%s)", toString(status).c_str());
Nathan Harold1a371532017-01-30 12:30:48 -0800616 }
ludi6e8eccd2017-08-14 14:40:37 -0700617
618 return status;
Nathan Harold1a371532017-01-30 12:30:48 -0800619}
620
ludi6e8eccd2017-08-14 14:40:37 -0700621netdutils::Status
622XfrmController::ipSecRemoveTransportModeTransform(const android::base::unique_fd& socket) {
Nathan Harold1a371532017-01-30 12:30:48 -0800623 (void)socket;
ludi6e8eccd2017-08-14 14:40:37 -0700624 return netdutils::status::ok;
Nathan Harold1a371532017-01-30 12:30:48 -0800625}
626
627void XfrmController::fillTransportModeSelector(const XfrmSaInfo& record, xfrm_selector* selector) {
628 selector->family = record.addrFamily;
629 selector->proto = AF_UNSPEC; // TODO: do we need to match the protocol? it's
630 // possible via the socket
631 selector->ifindex = record.netId; // TODO : still need to sort this out
632}
633
ludi6e8eccd2017-08-14 14:40:37 -0700634netdutils::Status XfrmController::createTransportModeSecurityAssociation(const XfrmSaInfo& record,
635 const XfrmSocket& sock) {
Nathan Harold1a371532017-01-30 12:30:48 -0800636 xfrm_usersa_info usersa{};
637 nlattr_algo_crypt crypt{};
638 nlattr_algo_auth auth{};
Nathan Harold420ceac2017-04-05 19:36:59 -0700639 nlattr_encap_tmpl encap{};
Nathan Harold1a371532017-01-30 12:30:48 -0800640
ludie51e3862017-08-15 19:28:12 -0700641 enum { NLMSG_HDR, USERSA, USERSA_PAD, CRYPT, CRYPT_PAD, AUTH, AUTH_PAD, ENCAP, ENCAP_PAD };
Nathan Harold1a371532017-01-30 12:30:48 -0800642
ludie51e3862017-08-15 19:28:12 -0700643 std::vector<iovec> iov = {
Nathan Harold1a371532017-01-30 12:30:48 -0800644 {NULL, 0}, // reserved for the eventual addition of a NLMSG_HDR
645 {&usersa, 0}, // main usersa_info struct
646 {kPadBytes, 0}, // up to NLMSG_ALIGNTO pad bytes of padding
647 {&crypt, 0}, // adjust size if crypt algo is present
648 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
649 {&auth, 0}, // adjust size if auth algo is present
650 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
Nathan Harold420ceac2017-04-05 19:36:59 -0700651 {&encap, 0}, // adjust size if auth algo is present
652 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
Nathan Harold1a371532017-01-30 12:30:48 -0800653 };
654
655 int len;
656 len = iov[USERSA].iov_len = fillUserSaInfo(record, &usersa);
657 iov[USERSA_PAD].iov_len = NLMSG_ALIGN(len) - len;
658
659 len = iov[CRYPT].iov_len = fillNlAttrXfrmAlgoEnc(record.crypt, &crypt);
660 iov[CRYPT_PAD].iov_len = NLA_ALIGN(len) - len;
661
662 len = iov[AUTH].iov_len = fillNlAttrXfrmAlgoAuth(record.auth, &auth);
663 iov[AUTH_PAD].iov_len = NLA_ALIGN(len) - len;
664
Nathan Harold420ceac2017-04-05 19:36:59 -0700665 len = iov[ENCAP].iov_len = fillNlAttrXfrmEncapTmpl(record, &encap);
666 iov[ENCAP_PAD].iov_len = NLA_ALIGN(len) - len;
ludie51e3862017-08-15 19:28:12 -0700667 return sock.sendMessage(XFRM_MSG_UPDSA, NETLINK_REQUEST_FLAGS, 0, &iov);
Nathan Harold1a371532017-01-30 12:30:48 -0800668}
669
670int XfrmController::fillNlAttrXfrmAlgoEnc(const XfrmAlgo& inAlgo, nlattr_algo_crypt* algo) {
671 int len = NLA_HDRLEN + sizeof(xfrm_algo);
672 strncpy(algo->crypt.alg_name, inAlgo.name.c_str(), sizeof(algo->crypt.alg_name));
673 algo->crypt.alg_key_len = inAlgo.key.size() * 8; // bits
674 memcpy(algo->key, &inAlgo.key[0], inAlgo.key.size()); // FIXME :safety checks
675 len += inAlgo.key.size();
676 fillXfrmNlaHdr(&algo->hdr, XFRMA_ALG_CRYPT, len);
677 return len;
678}
679
680int XfrmController::fillNlAttrXfrmAlgoAuth(const XfrmAlgo& inAlgo, nlattr_algo_auth* algo) {
681 int len = NLA_HDRLEN + sizeof(xfrm_algo_auth);
682 strncpy(algo->auth.alg_name, inAlgo.name.c_str(), sizeof(algo->auth.alg_name));
683 algo->auth.alg_key_len = inAlgo.key.size() * 8; // bits
684
685 // This is the extra field for ALG_AUTH_TRUNC
686 algo->auth.alg_trunc_len = inAlgo.truncLenBits;
687
688 memcpy(algo->key, &inAlgo.key[0], inAlgo.key.size()); // FIXME :safety checks
689 len += inAlgo.key.size();
690
691 fillXfrmNlaHdr(&algo->hdr, XFRMA_ALG_AUTH_TRUNC, len);
692 return len;
693}
694
Nathan Harold420ceac2017-04-05 19:36:59 -0700695int XfrmController::fillNlAttrXfrmEncapTmpl(const XfrmSaInfo& record, nlattr_encap_tmpl* tmpl) {
696 if (record.encap.type == XfrmEncapType::NONE) {
697 return 0;
698 }
699
700 int len = NLA_HDRLEN + sizeof(xfrm_encap_tmpl);
701 tmpl->tmpl.encap_type = static_cast<uint16_t>(record.encap.type);
702 tmpl->tmpl.encap_sport = htons(record.encap.srcPort);
703 tmpl->tmpl.encap_dport = htons(record.encap.dstPort);
704 fillXfrmNlaHdr(&tmpl->hdr, XFRMA_ENCAP, len);
705 return len;
706}
707
Nathan Harold1a371532017-01-30 12:30:48 -0800708int XfrmController::fillUserSaInfo(const XfrmSaInfo& record, xfrm_usersa_info* usersa) {
709 fillTransportModeSelector(record, &usersa->sel);
710
711 usersa->id.proto = IPPROTO_ESP;
712 usersa->id.spi = record.spi;
713 usersa->id.daddr = record.dstAddr;
714
715 usersa->saddr = record.srcAddr;
716
717 fillXfrmLifetimeDefaults(&usersa->lft);
718 fillXfrmCurLifetimeDefaults(&usersa->curlft);
719 memset(&usersa->stats, 0, sizeof(usersa->stats)); // leave stats zeroed out
720 usersa->reqid = record.transformId;
721 usersa->family = record.addrFamily;
722 usersa->mode = static_cast<uint8_t>(record.mode);
723 usersa->replay_window = REPLAY_WINDOW_SIZE;
724 usersa->flags = 0; // TODO: should we actually set flags, XFRM_SA_XFLAG_DONT_ENCAP_DSCP?
725 return sizeof(*usersa);
726}
727
728int XfrmController::fillUserSaId(const XfrmSaId& record, xfrm_usersa_id* said) {
729 said->daddr = record.dstAddr;
730 said->spi = record.spi;
731 said->family = record.addrFamily;
732 said->proto = IPPROTO_ESP;
733
734 return sizeof(*said);
735}
736
ludi6e8eccd2017-08-14 14:40:37 -0700737netdutils::Status XfrmController::deleteSecurityAssociation(const XfrmSaId& record,
738 const XfrmSocket& sock) {
Nathan Harold1a371532017-01-30 12:30:48 -0800739 xfrm_usersa_id said{};
740
ludie51e3862017-08-15 19:28:12 -0700741 enum { NLMSG_HDR, USERSAID, USERSAID_PAD };
Nathan Harold1a371532017-01-30 12:30:48 -0800742
ludie51e3862017-08-15 19:28:12 -0700743 std::vector<iovec> iov = {
Nathan Harold1a371532017-01-30 12:30:48 -0800744 {NULL, 0}, // reserved for the eventual addition of a NLMSG_HDR
745 {&said, 0}, // main usersa_info struct
746 {kPadBytes, 0}, // up to NLMSG_ALIGNTO pad bytes of padding
747 };
748
749 int len;
750 len = iov[USERSAID].iov_len = fillUserSaId(record, &said);
751 iov[USERSAID_PAD].iov_len = NLMSG_ALIGN(len) - len;
752
ludie51e3862017-08-15 19:28:12 -0700753 return sock.sendMessage(XFRM_MSG_DELSA, NETLINK_REQUEST_FLAGS, 0, &iov);
Nathan Harold1a371532017-01-30 12:30:48 -0800754}
755
ludi6e8eccd2017-08-14 14:40:37 -0700756netdutils::Status XfrmController::allocateSpi(const XfrmSaInfo& record, uint32_t minSpi,
757 uint32_t maxSpi, uint32_t* outSpi,
758 const XfrmSocket& sock) {
Nathan Harold1a371532017-01-30 12:30:48 -0800759 xfrm_userspi_info spiInfo{};
760
ludie51e3862017-08-15 19:28:12 -0700761 enum { NLMSG_HDR, USERSAID, USERSAID_PAD };
Nathan Harold1a371532017-01-30 12:30:48 -0800762
ludie51e3862017-08-15 19:28:12 -0700763 std::vector<iovec> iov = {
Nathan Harold1a371532017-01-30 12:30:48 -0800764 {NULL, 0}, // reserved for the eventual addition of a NLMSG_HDR
765 {&spiInfo, 0}, // main userspi_info struct
766 {kPadBytes, 0}, // up to NLMSG_ALIGNTO pad bytes of padding
767 };
768
769 int len;
770 if (fillUserSaInfo(record, &spiInfo.info) == 0) {
771 ALOGE("Failed to fill transport SA Info");
772 }
773
774 len = iov[USERSAID].iov_len = sizeof(spiInfo);
775 iov[USERSAID_PAD].iov_len = NLMSG_ALIGN(len) - len;
776
777 RandomSpi spiGen = RandomSpi(minSpi, maxSpi);
ludi6e8eccd2017-08-14 14:40:37 -0700778 int spi;
779 netdutils::Status ret;
Nathan Harold1a371532017-01-30 12:30:48 -0800780 while ((spi = spiGen.next()) != INVALID_SPI) {
781 spiInfo.min = spi;
782 spiInfo.max = spi;
ludie51e3862017-08-15 19:28:12 -0700783 ret = sock.sendMessage(XFRM_MSG_ALLOCSPI, NETLINK_REQUEST_FLAGS, 0, &iov);
Nathan Harold1a371532017-01-30 12:30:48 -0800784
785 /* If the SPI is in use, we'll get ENOENT */
ludi6e8eccd2017-08-14 14:40:37 -0700786 if (netdutils::equalToErrno(ret, ENOENT))
Nathan Harold1a371532017-01-30 12:30:48 -0800787 continue;
788
ludi6e8eccd2017-08-14 14:40:37 -0700789 if (isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800790 *outSpi = spi;
Nathan Harold420ceac2017-04-05 19:36:59 -0700791 ALOGD("Allocated an SPI: %x", *outSpi);
Nathan Harold1a371532017-01-30 12:30:48 -0800792 } else {
793 *outSpi = INVALID_SPI;
ludi6e8eccd2017-08-14 14:40:37 -0700794 ALOGE("SPI Allocation Failed with error %d", ret.code());
Nathan Harold1a371532017-01-30 12:30:48 -0800795 }
796
797 return ret;
798 }
799
800 // Should always be -ENOENT if we get here
801 return ret;
802}
803
804int XfrmController::fillTransportModeUserSpInfo(const XfrmSaInfo& record,
805 xfrm_userpolicy_info* usersp) {
806 fillTransportModeSelector(record, &usersp->sel);
807 fillXfrmLifetimeDefaults(&usersp->lft);
808 fillXfrmCurLifetimeDefaults(&usersp->curlft);
Nathan Harold420ceac2017-04-05 19:36:59 -0700809 /* if (index) index & 0x3 == dir -- must be true
810 * xfrm_user.c:verify_newpolicy_info() */
Nathan Harold1a371532017-01-30 12:30:48 -0800811 usersp->index = 0;
812 usersp->dir = static_cast<uint8_t>(record.direction);
813 usersp->action = XFRM_POLICY_ALLOW;
814 usersp->flags = XFRM_POLICY_LOCALOK;
815 usersp->share = XFRM_SHARE_UNIQUE;
816 return sizeof(*usersp);
817}
818
819int XfrmController::fillUserTemplate(const XfrmSaInfo& record, xfrm_user_tmpl* tmpl) {
820 tmpl->id.daddr = record.dstAddr;
821 tmpl->id.spi = record.spi;
822 tmpl->id.proto = IPPROTO_ESP;
823
824 tmpl->family = record.addrFamily;
825 tmpl->saddr = record.srcAddr;
826 tmpl->reqid = record.transformId;
827 tmpl->mode = static_cast<uint8_t>(record.mode);
828 tmpl->share = XFRM_SHARE_UNIQUE;
829 tmpl->optional = 0; // if this is true, then a failed state lookup will be considered OK:
830 // http://lxr.free-electrons.com/source/net/xfrm/xfrm_policy.c#L1492
831 tmpl->aalgos = ALGO_MASK_AUTH_ALL; // TODO: if there's a bitmask somewhere of
832 // algos, we should find it and apply it.
833 // I can't find one.
834 tmpl->ealgos = ALGO_MASK_CRYPT_ALL; // TODO: if there's a bitmask somewhere...
835 return 0;
836}
837
838} // namespace net
839} // namespace android