blob: b31aafaa34cc14399002763b5f77e1fa3f3d4374 [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
Nathan Harold1a371532017-01-30 12:30:48 -080075constexpr uint8_t REPLAY_WINDOW_SIZE = 4;
76
Nathan Harold39b5df42017-08-02 18:45:25 -070077namespace {
78
Nathan Harold1a371532017-01-30 12:30:48 -080079constexpr uint32_t RAND_SPI_MIN = 1;
80constexpr uint32_t RAND_SPI_MAX = 0xFFFFFFFE;
81
82constexpr uint32_t INVALID_SPI = 0;
83
84#define XFRM_MSG_TRANS(x) \
85 case x: \
86 return #x;
87
88const char* xfrmMsgTypeToString(uint16_t msg) {
89 switch (msg) {
90 XFRM_MSG_TRANS(XFRM_MSG_NEWSA)
91 XFRM_MSG_TRANS(XFRM_MSG_DELSA)
92 XFRM_MSG_TRANS(XFRM_MSG_GETSA)
93 XFRM_MSG_TRANS(XFRM_MSG_NEWPOLICY)
94 XFRM_MSG_TRANS(XFRM_MSG_DELPOLICY)
95 XFRM_MSG_TRANS(XFRM_MSG_GETPOLICY)
96 XFRM_MSG_TRANS(XFRM_MSG_ALLOCSPI)
97 XFRM_MSG_TRANS(XFRM_MSG_ACQUIRE)
98 XFRM_MSG_TRANS(XFRM_MSG_EXPIRE)
99 XFRM_MSG_TRANS(XFRM_MSG_UPDPOLICY)
100 XFRM_MSG_TRANS(XFRM_MSG_UPDSA)
101 XFRM_MSG_TRANS(XFRM_MSG_POLEXPIRE)
102 XFRM_MSG_TRANS(XFRM_MSG_FLUSHSA)
103 XFRM_MSG_TRANS(XFRM_MSG_FLUSHPOLICY)
104 XFRM_MSG_TRANS(XFRM_MSG_NEWAE)
105 XFRM_MSG_TRANS(XFRM_MSG_GETAE)
106 XFRM_MSG_TRANS(XFRM_MSG_REPORT)
107 XFRM_MSG_TRANS(XFRM_MSG_MIGRATE)
108 XFRM_MSG_TRANS(XFRM_MSG_NEWSADINFO)
109 XFRM_MSG_TRANS(XFRM_MSG_GETSADINFO)
110 XFRM_MSG_TRANS(XFRM_MSG_GETSPDINFO)
111 XFRM_MSG_TRANS(XFRM_MSG_NEWSPDINFO)
112 XFRM_MSG_TRANS(XFRM_MSG_MAPPING)
113 default:
114 return "XFRM_MSG UNKNOWN";
115 }
116}
117
118// actually const but cannot be declared as such for reasons
119uint8_t kPadBytesArray[] = {0, 0, 0};
120void* kPadBytes = static_cast<void*>(kPadBytesArray);
121
Nathan Harold420ceac2017-04-05 19:36:59 -0700122#define LOG_HEX(__desc16__, __buf__, __len__) \
Manojd9c93c22017-10-19 13:40:26 -0700123 if (__android_log_is_debuggable()) { \
124 do { \
125 logHex(__desc16__, __buf__, __len__); \
126 } while (0); \
127 }
128
ludie51e3862017-08-15 19:28:12 -0700129#define LOG_IOV(__iov__) \
Manojd9c93c22017-10-19 13:40:26 -0700130 if (__android_log_is_debuggable()) { \
131 do { \
132 logIov(__iov__); \
133 } while (0); \
134 }
Nathan Harold1a371532017-01-30 12:30:48 -0800135
136void logHex(const char* desc16, const char* buf, size_t len) {
137 char* printBuf = new char[len * 2 + 1 + 26]; // len->ascii, +newline, +prefix strlen
138 int offset = 0;
139 if (desc16) {
140 sprintf(printBuf, "{%-16s}", desc16);
141 offset += 18; // prefix string length
142 }
143 sprintf(printBuf + offset, "[%4.4u]: ", (len > 9999) ? 9999 : (unsigned)len);
144 offset += 8;
145
146 for (uint32_t j = 0; j < (uint32_t)len; j++) {
147 sprintf(&printBuf[j * 2 + offset], "%0.2x", buf[j]);
148 }
149 ALOGD("%s", printBuf);
150 delete[] printBuf;
151}
152
ludie51e3862017-08-15 19:28:12 -0700153void logIov(const std::vector<iovec>& iov) {
154 for (const iovec& row : iov) {
155 logHex(0, reinterpret_cast<char*>(row.iov_base), row.iov_len);
Nathan Harold1a371532017-01-30 12:30:48 -0800156 }
157}
158
ludi6e8eccd2017-08-14 14:40:37 -0700159// TODO: Need to consider a way to refer to the sSycalls instance
ludi4072ff22017-06-15 08:56:52 -0700160inline Syscalls& getSyscallInstance() { return netdutils::sSyscalls.get(); }
161
Nathan Harold1a371532017-01-30 12:30:48 -0800162class XfrmSocketImpl : public XfrmSocket {
163private:
164 static constexpr int NLMSG_DEFAULTSIZE = 8192;
165
166 union NetlinkResponse {
167 nlmsghdr hdr;
168 struct _err_ {
169 nlmsghdr hdr;
170 nlmsgerr err;
171 } err;
172
173 struct _buf_ {
174 nlmsghdr hdr;
175 char buf[NLMSG_DEFAULTSIZE];
176 } buf;
177 };
178
179public:
ludi6e8eccd2017-08-14 14:40:37 -0700180 netdutils::Status open() override {
Nathan Harold1a371532017-01-30 12:30:48 -0800181 mSock = openNetlinkSocket(NETLINK_XFRM);
ludi6e8eccd2017-08-14 14:40:37 -0700182 if (mSock < 0) {
Nathan Harold1a371532017-01-30 12:30:48 -0800183 ALOGW("Could not get a new socket, line=%d", __LINE__);
ludi6e8eccd2017-08-14 14:40:37 -0700184 return netdutils::statusFromErrno(-mSock, "Could not open netlink socket");
Nathan Harold1a371532017-01-30 12:30:48 -0800185 }
186
ludi6e8eccd2017-08-14 14:40:37 -0700187 return netdutils::status::ok;
Nathan Harold1a371532017-01-30 12:30:48 -0800188 }
189
ludi6e8eccd2017-08-14 14:40:37 -0700190 static netdutils::Status validateResponse(NetlinkResponse response, size_t len) {
Nathan Harold1a371532017-01-30 12:30:48 -0800191 if (len < sizeof(nlmsghdr)) {
192 ALOGW("Invalid response message received over netlink");
ludi6e8eccd2017-08-14 14:40:37 -0700193 return netdutils::statusFromErrno(EBADMSG, "Invalid message");
Nathan Harold1a371532017-01-30 12:30:48 -0800194 }
195
196 switch (response.hdr.nlmsg_type) {
197 case NLMSG_NOOP:
198 case NLMSG_DONE:
ludi6e8eccd2017-08-14 14:40:37 -0700199 return netdutils::status::ok;
Nathan Harold1a371532017-01-30 12:30:48 -0800200 case NLMSG_OVERRUN:
201 ALOGD("Netlink request overran kernel buffer");
ludi6e8eccd2017-08-14 14:40:37 -0700202 return netdutils::statusFromErrno(EBADMSG, "Kernel buffer overrun");
Nathan Harold1a371532017-01-30 12:30:48 -0800203 case NLMSG_ERROR:
204 if (len < sizeof(NetlinkResponse::_err_)) {
205 ALOGD("Netlink message received malformed error response");
ludi6e8eccd2017-08-14 14:40:37 -0700206 return netdutils::statusFromErrno(EBADMSG, "Malformed error response");
Nathan Harold1a371532017-01-30 12:30:48 -0800207 }
ludi6e8eccd2017-08-14 14:40:37 -0700208 return netdutils::statusFromErrno(
209 -response.err.err.error,
210 "Error netlink message"); // Netlink errors are negative errno.
Nathan Harold1a371532017-01-30 12:30:48 -0800211 case XFRM_MSG_NEWSA:
212 break;
213 }
214
215 if (response.hdr.nlmsg_type < XFRM_MSG_BASE /*== NLMSG_MIN_TYPE*/ ||
216 response.hdr.nlmsg_type > XFRM_MSG_MAX) {
217 ALOGD("Netlink message responded with an out-of-range message ID");
ludi6e8eccd2017-08-14 14:40:37 -0700218 return netdutils::statusFromErrno(EBADMSG, "Invalid message ID");
Nathan Harold1a371532017-01-30 12:30:48 -0800219 }
220
221 // TODO Add more message validation here
ludi6e8eccd2017-08-14 14:40:37 -0700222 return netdutils::status::ok;
Nathan Harold1a371532017-01-30 12:30:48 -0800223 }
224
ludi6e8eccd2017-08-14 14:40:37 -0700225 netdutils::Status sendMessage(uint16_t nlMsgType, uint16_t nlMsgFlags, uint16_t nlMsgSeqNum,
226 std::vector<iovec>* iovecs) const override {
Nathan Harold1a371532017-01-30 12:30:48 -0800227 nlmsghdr nlMsg = {
228 .nlmsg_type = nlMsgType, .nlmsg_flags = nlMsgFlags, .nlmsg_seq = nlMsgSeqNum,
229 };
230
ludie51e3862017-08-15 19:28:12 -0700231 (*iovecs)[0].iov_base = &nlMsg;
232 (*iovecs)[0].iov_len = NLMSG_HDRLEN;
233 for (const iovec& iov : *iovecs) {
234 nlMsg.nlmsg_len += iov.iov_len;
Nathan Harold1a371532017-01-30 12:30:48 -0800235 }
236
237 ALOGD("Sending Netlink XFRM Message: %s", xfrmMsgTypeToString(nlMsgType));
Manojd9c93c22017-10-19 13:40:26 -0700238 LOG_IOV(*iovecs);
Nathan Harold1a371532017-01-30 12:30:48 -0800239
ludie51e3862017-08-15 19:28:12 -0700240 StatusOr<size_t> writeResult = getSyscallInstance().writev(mSock, *iovecs);
ludi4072ff22017-06-15 08:56:52 -0700241 if (!isOk(writeResult)) {
242 ALOGE("netlink socket writev failed (%s)", toString(writeResult).c_str());
ludi6e8eccd2017-08-14 14:40:37 -0700243 return writeResult;
Nathan Harold1a371532017-01-30 12:30:48 -0800244 }
245
ludi4072ff22017-06-15 08:56:52 -0700246 if (nlMsg.nlmsg_len != writeResult.value()) {
247 ALOGE("Invalid netlink message length sent %d", static_cast<int>(writeResult.value()));
ludi6e8eccd2017-08-14 14:40:37 -0700248 return netdutils::statusFromErrno(EBADMSG, "Invalid message length");
Nathan Harold1a371532017-01-30 12:30:48 -0800249 }
250
ludi4072ff22017-06-15 08:56:52 -0700251 NetlinkResponse response = {};
Nathan Harold1a371532017-01-30 12:30:48 -0800252
ludi4072ff22017-06-15 08:56:52 -0700253 StatusOr<Slice> readResult =
254 getSyscallInstance().read(Fd(mSock), netdutils::makeSlice(response));
255 if (!isOk(readResult)) {
256 ALOGE("netlink response error (%s)", toString(readResult).c_str());
ludi6e8eccd2017-08-14 14:40:37 -0700257 return readResult;
ludi4072ff22017-06-15 08:56:52 -0700258 }
259
260 LOG_HEX("netlink msg resp", reinterpret_cast<char*>(readResult.value().base()),
261 readResult.value().size());
262
ludi6e8eccd2017-08-14 14:40:37 -0700263 Status validateStatus = validateResponse(response, readResult.value().size());
264 if (!isOk(validateStatus)) {
265 ALOGE("netlink response contains error (%s)", toString(validateStatus).c_str());
266 }
267
268 return validateStatus;
Nathan Harold1a371532017-01-30 12:30:48 -0800269 }
270};
271
ludi6e8eccd2017-08-14 14:40:37 -0700272StatusOr<int> convertToXfrmAddr(const std::string& strAddr, xfrm_address_t* xfrmAddr) {
Nathan Harold1a371532017-01-30 12:30:48 -0800273 if (strAddr.length() == 0) {
274 memset(xfrmAddr, 0, sizeof(*xfrmAddr));
275 return AF_UNSPEC;
276 }
277
278 if (inet_pton(AF_INET6, strAddr.c_str(), reinterpret_cast<void*>(xfrmAddr))) {
279 return AF_INET6;
280 } else if (inet_pton(AF_INET, strAddr.c_str(), reinterpret_cast<void*>(xfrmAddr))) {
281 return AF_INET;
282 } else {
ludi6e8eccd2017-08-14 14:40:37 -0700283 return netdutils::statusFromErrno(EAFNOSUPPORT, "Invalid address family");
Nathan Harold1a371532017-01-30 12:30:48 -0800284 }
285}
286
287void fillXfrmNlaHdr(nlattr* hdr, uint16_t type, uint16_t len) {
288 hdr->nla_type = type;
289 hdr->nla_len = len;
290}
291
292void fillXfrmCurLifetimeDefaults(xfrm_lifetime_cur* cur) {
293 memset(reinterpret_cast<char*>(cur), 0, sizeof(*cur));
294}
295void fillXfrmLifetimeDefaults(xfrm_lifetime_cfg* cfg) {
296 cfg->soft_byte_limit = XFRM_INF;
297 cfg->hard_byte_limit = XFRM_INF;
298 cfg->soft_packet_limit = XFRM_INF;
299 cfg->hard_packet_limit = XFRM_INF;
300}
301
302/*
303 * Allocate SPIs within an (inclusive) range of min-max.
304 * returns 0 (INVALID_SPI) once the entire range has been parsed.
305 */
306class RandomSpi {
307public:
308 RandomSpi(int min, int max) : mMin(min) {
Nathan Harold1e284452017-10-10 13:31:19 -0700309 // Re-seeding should be safe because the seed itself is
310 // sufficiently random and we don't need secure random
311 std::mt19937 rnd = std::mt19937(std::random_device()());
312 mNext = std::uniform_int_distribution<>(1, INT_MAX)(rnd);
Nathan Harold1a371532017-01-30 12:30:48 -0800313 mSize = max - min + 1;
314 mCount = mSize;
315 }
316
317 uint32_t next() {
318 if (!mCount)
319 return 0;
320 mCount--;
321 return (mNext++ % mSize) + mMin;
322 }
323
324private:
325 uint32_t mNext;
326 uint32_t mSize;
327 uint32_t mMin;
328 uint32_t mCount;
329};
330
331} // namespace
332
333//
334// Begin XfrmController Impl
335//
336//
337XfrmController::XfrmController(void) {}
338
ludi6e8eccd2017-08-14 14:40:37 -0700339netdutils::Status XfrmController::ipSecAllocateSpi(int32_t transformId, int32_t direction,
340 const std::string& localAddress,
341 const std::string& remoteAddress, int32_t inSpi,
342 int32_t* outSpi) {
Nathan Harold1a371532017-01-30 12:30:48 -0800343 ALOGD("XfrmController:%s, line=%d", __FUNCTION__, __LINE__);
344 ALOGD("transformId=%d", transformId);
345 ALOGD("direction=%d", direction);
346 ALOGD("localAddress=%s", localAddress.c_str());
347 ALOGD("remoteAddress=%s", remoteAddress.c_str());
348 ALOGD("inSpi=%0.8x", inSpi);
349
350 XfrmSaInfo saInfo{};
Nathan Harold1a371532017-01-30 12:30:48 -0800351
ludi6e8eccd2017-08-14 14:40:37 -0700352 netdutils::Status ret =
353 fillXfrmSaId(direction, localAddress, remoteAddress, INVALID_SPI, &saInfo);
354 if (!isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800355 return ret;
356 }
357
358 XfrmSocketImpl sock;
ludi6e8eccd2017-08-14 14:40:37 -0700359 netdutils::Status socketStatus = sock.open();
360 if (!isOk(socketStatus)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800361 ALOGD("Sock open failed for XFRM, line=%d", __LINE__);
ludi6e8eccd2017-08-14 14:40:37 -0700362 return socketStatus;
Nathan Harold1a371532017-01-30 12:30:48 -0800363 }
364
365 int minSpi = RAND_SPI_MIN, maxSpi = RAND_SPI_MAX;
366
367 if (inSpi)
368 minSpi = maxSpi = inSpi;
ludi6e8eccd2017-08-14 14:40:37 -0700369
Nathan Harold1a371532017-01-30 12:30:48 -0800370 ret = allocateSpi(saInfo, minSpi, maxSpi, reinterpret_cast<uint32_t*>(outSpi), sock);
ludi6e8eccd2017-08-14 14:40:37 -0700371 if (!isOk(ret)) {
372 // TODO: May want to return a new Status with a modified status string
Nathan Harold1a371532017-01-30 12:30:48 -0800373 ALOGD("Failed to Allocate an SPI, line=%d", __LINE__);
374 *outSpi = INVALID_SPI;
375 }
376
377 return ret;
378}
379
ludi6e8eccd2017-08-14 14:40:37 -0700380netdutils::Status XfrmController::ipSecAddSecurityAssociation(
Nathan Harold1a371532017-01-30 12:30:48 -0800381 int32_t transformId, int32_t mode, int32_t direction, const std::string& localAddress,
Nathan Harold420ceac2017-04-05 19:36:59 -0700382 const std::string& remoteAddress, int64_t underlyingNetworkHandle, int32_t spi,
Nathan Harold1a371532017-01-30 12:30:48 -0800383 const std::string& authAlgo, const std::vector<uint8_t>& authKey, int32_t authTruncBits,
384 const std::string& cryptAlgo, const std::vector<uint8_t>& cryptKey, int32_t cryptTruncBits,
ludiec836052017-05-20 14:17:05 -0700385 int32_t encapType, int32_t encapLocalPort, int32_t encapRemotePort) {
Nathan Harold1a371532017-01-30 12:30:48 -0800386 android::RWLock::AutoWLock lock(mLock);
387
388 ALOGD("XfrmController::%s, line=%d", __FUNCTION__, __LINE__);
389 ALOGD("transformId=%d", transformId);
390 ALOGD("mode=%d", mode);
391 ALOGD("direction=%d", direction);
392 ALOGD("localAddress=%s", localAddress.c_str());
393 ALOGD("remoteAddress=%s", remoteAddress.c_str());
Nathan Harold420ceac2017-04-05 19:36:59 -0700394 ALOGD("underlyingNetworkHandle=%" PRIx64, underlyingNetworkHandle);
Nathan Harold1a371532017-01-30 12:30:48 -0800395 ALOGD("spi=%0.8x", spi);
396 ALOGD("authAlgo=%s", authAlgo.c_str());
397 ALOGD("authTruncBits=%d", authTruncBits);
398 ALOGD("cryptAlgo=%s", cryptAlgo.c_str());
399 ALOGD("cryptTruncBits=%d,", cryptTruncBits);
400 ALOGD("encapType=%d", encapType);
401 ALOGD("encapLocalPort=%d", encapLocalPort);
402 ALOGD("encapRemotePort=%d", encapRemotePort);
403
404 XfrmSaInfo saInfo{};
ludi6e8eccd2017-08-14 14:40:37 -0700405 netdutils::Status ret = fillXfrmSaId(direction, localAddress, remoteAddress, spi, &saInfo);
406 if (!isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800407 return ret;
408 }
409
410 saInfo.transformId = transformId;
411
412 // STOPSHIP : range check the key lengths to prevent puncturing and overflow
413 saInfo.auth = XfrmAlgo{
414 .name = authAlgo, .key = authKey, .truncLenBits = static_cast<uint16_t>(authTruncBits)};
415
416 saInfo.crypt = XfrmAlgo{
417 .name = cryptAlgo, .key = cryptKey, .truncLenBits = static_cast<uint16_t>(cryptTruncBits)};
418
419 saInfo.direction = static_cast<XfrmDirection>(direction);
420
421 switch (static_cast<XfrmMode>(mode)) {
422 case XfrmMode::TRANSPORT:
423 case XfrmMode::TUNNEL:
424 saInfo.mode = static_cast<XfrmMode>(mode);
425 break;
426 default:
ludi6e8eccd2017-08-14 14:40:37 -0700427 return netdutils::statusFromErrno(EINVAL, "Invalid xfrm mode");
Nathan Harold1a371532017-01-30 12:30:48 -0800428 }
429
430 XfrmSocketImpl sock;
ludi6e8eccd2017-08-14 14:40:37 -0700431 netdutils::Status socketStatus = sock.open();
432 if (!isOk(socketStatus)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800433 ALOGD("Sock open failed for XFRM, line=%d", __LINE__);
ludi6e8eccd2017-08-14 14:40:37 -0700434 return socketStatus;
Nathan Harold1a371532017-01-30 12:30:48 -0800435 }
436
Nathan Harold420ceac2017-04-05 19:36:59 -0700437 switch (static_cast<XfrmEncapType>(encapType)) {
438 case XfrmEncapType::ESPINUDP:
439 case XfrmEncapType::ESPINUDP_NON_IKE:
440 if (saInfo.addrFamily != AF_INET) {
ludi6e8eccd2017-08-14 14:40:37 -0700441 return netdutils::statusFromErrno(EAFNOSUPPORT, "IPv6 encap not supported");
Nathan Harold420ceac2017-04-05 19:36:59 -0700442 }
443 switch (saInfo.direction) {
444 case XfrmDirection::IN:
445 saInfo.encap.srcPort = encapRemotePort;
446 saInfo.encap.dstPort = encapLocalPort;
447 break;
448 case XfrmDirection::OUT:
449 saInfo.encap.srcPort = encapLocalPort;
450 saInfo.encap.dstPort = encapRemotePort;
451 break;
452 default:
ludi6e8eccd2017-08-14 14:40:37 -0700453 return netdutils::statusFromErrno(EINVAL, "Invalid direction");
Nathan Harold420ceac2017-04-05 19:36:59 -0700454 }
455 // fall through
456 case XfrmEncapType::NONE:
457 saInfo.encap.type = static_cast<XfrmEncapType>(encapType);
458 break;
459 default:
ludi6e8eccd2017-08-14 14:40:37 -0700460 return netdutils::statusFromErrno(EINVAL, "Invalid encap type");
Nathan Harold420ceac2017-04-05 19:36:59 -0700461 }
462
Nathan Harold1a371532017-01-30 12:30:48 -0800463 ret = createTransportModeSecurityAssociation(saInfo, sock);
ludi6e8eccd2017-08-14 14:40:37 -0700464 if (!isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800465 ALOGD("Failed creating a Security Association, line=%d", __LINE__);
Nathan Harold1a371532017-01-30 12:30:48 -0800466 }
467
ludi6e8eccd2017-08-14 14:40:37 -0700468 return ret;
Nathan Harold1a371532017-01-30 12:30:48 -0800469}
470
ludi6e8eccd2017-08-14 14:40:37 -0700471netdutils::Status XfrmController::ipSecDeleteSecurityAssociation(int32_t transformId,
472 int32_t direction,
473 const std::string& localAddress,
474 const std::string& remoteAddress,
475 int32_t spi) {
Nathan Harold1a371532017-01-30 12:30:48 -0800476 ALOGD("XfrmController:%s, line=%d", __FUNCTION__, __LINE__);
477 ALOGD("transformId=%d", transformId);
478 ALOGD("direction=%d", direction);
479 ALOGD("localAddress=%s", localAddress.c_str());
480 ALOGD("remoteAddress=%s", remoteAddress.c_str());
481 ALOGD("spi=%0.8x", spi);
482
Jonathan Basseriebdaa682017-09-14 16:33:08 -0700483 XfrmSaId saId{};
ludi6e8eccd2017-08-14 14:40:37 -0700484 netdutils::Status ret = fillXfrmSaId(direction, localAddress, remoteAddress, spi, &saId);
485 if (!isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800486 return ret;
487 }
488
489 XfrmSocketImpl sock;
ludi6e8eccd2017-08-14 14:40:37 -0700490 netdutils::Status socketStatus = sock.open();
491 if (!isOk(socketStatus)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800492 ALOGD("Sock open failed for XFRM, line=%d", __LINE__);
ludi6e8eccd2017-08-14 14:40:37 -0700493 return socketStatus;
Nathan Harold1a371532017-01-30 12:30:48 -0800494 }
495
496 ret = deleteSecurityAssociation(saId, sock);
ludi6e8eccd2017-08-14 14:40:37 -0700497 if (!isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800498 ALOGD("Failed to delete Security Association, line=%d", __LINE__);
Nathan Harold1a371532017-01-30 12:30:48 -0800499 }
500
501 return ret;
502}
503
ludi6e8eccd2017-08-14 14:40:37 -0700504netdutils::Status XfrmController::fillXfrmSaId(int32_t direction, const std::string& localAddress,
505 const std::string& remoteAddress, int32_t spi,
506 XfrmSaId* xfrmId) {
Nathan Harold1a371532017-01-30 12:30:48 -0800507 xfrm_address_t localXfrmAddr{}, remoteXfrmAddr{};
508
ludi6e8eccd2017-08-14 14:40:37 -0700509 StatusOr<int> addrFamilyLocal, addrFamilyRemote;
Nathan Harold1a371532017-01-30 12:30:48 -0800510 addrFamilyRemote = convertToXfrmAddr(remoteAddress, &remoteXfrmAddr);
511 addrFamilyLocal = convertToXfrmAddr(localAddress, &localXfrmAddr);
ludi6e8eccd2017-08-14 14:40:37 -0700512 if (!isOk(addrFamilyRemote) || !isOk(addrFamilyLocal)) {
513 return netdutils::statusFromErrno(EINVAL,
514 "Invalid address " + localAddress + "/" + remoteAddress);
Nathan Harold1a371532017-01-30 12:30:48 -0800515 }
516
ludi6e8eccd2017-08-14 14:40:37 -0700517 if (addrFamilyRemote.value() == AF_UNSPEC ||
518 (addrFamilyLocal.value() != AF_UNSPEC &&
519 addrFamilyLocal.value() != addrFamilyRemote.value())) {
520 ALOGD("Invalid or Mismatched Address Families, %d != %d, line=%d", addrFamilyLocal.value(),
521 addrFamilyRemote.value(), __LINE__);
522 return netdutils::statusFromErrno(EINVAL, "Invalid or mismatched address families");
Nathan Harold1a371532017-01-30 12:30:48 -0800523 }
524
ludi6e8eccd2017-08-14 14:40:37 -0700525 xfrmId->addrFamily = addrFamilyRemote.value();
Nathan Harold1a371532017-01-30 12:30:48 -0800526
527 xfrmId->spi = htonl(spi);
528
529 switch (static_cast<XfrmDirection>(direction)) {
530 case XfrmDirection::IN:
531 xfrmId->dstAddr = localXfrmAddr;
532 xfrmId->srcAddr = remoteXfrmAddr;
533 break;
534
535 case XfrmDirection::OUT:
536 xfrmId->dstAddr = remoteXfrmAddr;
537 xfrmId->srcAddr = localXfrmAddr;
538 break;
539
540 default:
541 ALOGD("Invalid XFRM direction, line=%d", __LINE__);
542 // Invalid direction for Transport mode transform: time to bail
ludi6e8eccd2017-08-14 14:40:37 -0700543 return netdutils::statusFromErrno(EINVAL, "Invalid direction");
Nathan Harold1a371532017-01-30 12:30:48 -0800544 }
ludi6e8eccd2017-08-14 14:40:37 -0700545 return netdutils::status::ok;
Nathan Harold1a371532017-01-30 12:30:48 -0800546}
547
ludi6e8eccd2017-08-14 14:40:37 -0700548netdutils::Status XfrmController::ipSecApplyTransportModeTransform(
549 const android::base::unique_fd& socket, int32_t transformId, int32_t direction,
550 const std::string& localAddress, const std::string& remoteAddress, int32_t spi) {
Nathan Harold1a371532017-01-30 12:30:48 -0800551 ALOGD("XfrmController::%s, line=%d", __FUNCTION__, __LINE__);
552 ALOGD("transformId=%d", transformId);
553 ALOGD("direction=%d", direction);
554 ALOGD("localAddress=%s", localAddress.c_str());
555 ALOGD("remoteAddress=%s", remoteAddress.c_str());
556 ALOGD("spi=%0.8x", spi);
557
558 struct sockaddr_storage saddr;
559
ludi4072ff22017-06-15 08:56:52 -0700560 StatusOr<sockaddr_storage> ret = getSyscallInstance().getsockname<sockaddr_storage>(Fd(socket));
561 if (!isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800562 ALOGE("Failed to get socket info in %s", __FUNCTION__);
ludi6e8eccd2017-08-14 14:40:37 -0700563 return ret;
Nathan Harold1a371532017-01-30 12:30:48 -0800564 }
565
ludi4072ff22017-06-15 08:56:52 -0700566 saddr = ret.value();
567
Nathan Harold1a371532017-01-30 12:30:48 -0800568 XfrmSaInfo saInfo{};
569 saInfo.transformId = transformId;
570 saInfo.direction = static_cast<XfrmDirection>(direction);
571 saInfo.spi = spi;
572
ludi6e8eccd2017-08-14 14:40:37 -0700573 netdutils::Status status = fillXfrmSaId(direction, localAddress, remoteAddress, spi, &saInfo);
574 if (!isOk(status)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800575 ALOGE("Couldn't build SA ID %s", __FUNCTION__);
ludi6e8eccd2017-08-14 14:40:37 -0700576 return status;
Nathan Harold1a371532017-01-30 12:30:48 -0800577 }
578
579 if (saInfo.addrFamily != saddr.ss_family) {
580 ALOGE("Transform address family(%d) differs from socket address "
Nathan Harold420ceac2017-04-05 19:36:59 -0700581 "family(%d)!",
582 saInfo.addrFamily, saddr.ss_family);
ludi6e8eccd2017-08-14 14:40:37 -0700583 return netdutils::statusFromErrno(EINVAL, "Mismatched address family");
Nathan Harold1a371532017-01-30 12:30:48 -0800584 }
585
586 struct {
587 xfrm_userpolicy_info info;
588 xfrm_user_tmpl tmpl;
589 } policy{};
590
591 fillTransportModeUserSpInfo(saInfo, &policy.info);
592 fillUserTemplate(saInfo, &policy.tmpl);
593
594 LOG_HEX("XfrmUserPolicy", reinterpret_cast<char*>(&policy), sizeof(policy));
595
596 int sockOpt, sockLayer;
597 switch (saInfo.addrFamily) {
598 case AF_INET:
599 sockOpt = IP_XFRM_POLICY;
600 sockLayer = SOL_IP;
601 break;
602 case AF_INET6:
603 sockOpt = IPV6_XFRM_POLICY;
604 sockLayer = SOL_IPV6;
605 break;
606 default:
ludi6e8eccd2017-08-14 14:40:37 -0700607 return netdutils::statusFromErrno(EAFNOSUPPORT, "Invalid address family");
Nathan Harold1a371532017-01-30 12:30:48 -0800608 }
609
ludi6e8eccd2017-08-14 14:40:37 -0700610 status = getSyscallInstance().setsockopt(Fd(socket), sockLayer, sockOpt, policy);
ludi4072ff22017-06-15 08:56:52 -0700611 if (!isOk(status)) {
612 ALOGE("Error setting socket option for XFRM! (%s)", toString(status).c_str());
Nathan Harold1a371532017-01-30 12:30:48 -0800613 }
ludi6e8eccd2017-08-14 14:40:37 -0700614
615 return status;
Nathan Harold1a371532017-01-30 12:30:48 -0800616}
617
ludi6e8eccd2017-08-14 14:40:37 -0700618netdutils::Status
619XfrmController::ipSecRemoveTransportModeTransform(const android::base::unique_fd& socket) {
Nathan Harold1a371532017-01-30 12:30:48 -0800620 (void)socket;
ludi6e8eccd2017-08-14 14:40:37 -0700621 return netdutils::status::ok;
Nathan Harold1a371532017-01-30 12:30:48 -0800622}
623
624void XfrmController::fillTransportModeSelector(const XfrmSaInfo& record, xfrm_selector* selector) {
625 selector->family = record.addrFamily;
626 selector->proto = AF_UNSPEC; // TODO: do we need to match the protocol? it's
627 // possible via the socket
628 selector->ifindex = record.netId; // TODO : still need to sort this out
629}
630
ludi6e8eccd2017-08-14 14:40:37 -0700631netdutils::Status XfrmController::createTransportModeSecurityAssociation(const XfrmSaInfo& record,
632 const XfrmSocket& sock) {
Nathan Harold1a371532017-01-30 12:30:48 -0800633 xfrm_usersa_info usersa{};
634 nlattr_algo_crypt crypt{};
635 nlattr_algo_auth auth{};
Nathan Harold420ceac2017-04-05 19:36:59 -0700636 nlattr_encap_tmpl encap{};
Nathan Harold1a371532017-01-30 12:30:48 -0800637
ludie51e3862017-08-15 19:28:12 -0700638 enum { NLMSG_HDR, USERSA, USERSA_PAD, CRYPT, CRYPT_PAD, AUTH, AUTH_PAD, ENCAP, ENCAP_PAD };
Nathan Harold1a371532017-01-30 12:30:48 -0800639
ludie51e3862017-08-15 19:28:12 -0700640 std::vector<iovec> iov = {
Nathan Harold1a371532017-01-30 12:30:48 -0800641 {NULL, 0}, // reserved for the eventual addition of a NLMSG_HDR
642 {&usersa, 0}, // main usersa_info struct
643 {kPadBytes, 0}, // up to NLMSG_ALIGNTO pad bytes of padding
644 {&crypt, 0}, // adjust size if crypt algo is present
645 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
646 {&auth, 0}, // adjust size if auth algo is present
647 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
Nathan Harold420ceac2017-04-05 19:36:59 -0700648 {&encap, 0}, // adjust size if auth algo is present
649 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
Nathan Harold1a371532017-01-30 12:30:48 -0800650 };
651
652 int len;
653 len = iov[USERSA].iov_len = fillUserSaInfo(record, &usersa);
654 iov[USERSA_PAD].iov_len = NLMSG_ALIGN(len) - len;
655
656 len = iov[CRYPT].iov_len = fillNlAttrXfrmAlgoEnc(record.crypt, &crypt);
657 iov[CRYPT_PAD].iov_len = NLA_ALIGN(len) - len;
658
659 len = iov[AUTH].iov_len = fillNlAttrXfrmAlgoAuth(record.auth, &auth);
660 iov[AUTH_PAD].iov_len = NLA_ALIGN(len) - len;
661
Nathan Harold420ceac2017-04-05 19:36:59 -0700662 len = iov[ENCAP].iov_len = fillNlAttrXfrmEncapTmpl(record, &encap);
663 iov[ENCAP_PAD].iov_len = NLA_ALIGN(len) - len;
ludie51e3862017-08-15 19:28:12 -0700664 return sock.sendMessage(XFRM_MSG_UPDSA, NETLINK_REQUEST_FLAGS, 0, &iov);
Nathan Harold1a371532017-01-30 12:30:48 -0800665}
666
667int XfrmController::fillNlAttrXfrmAlgoEnc(const XfrmAlgo& inAlgo, nlattr_algo_crypt* algo) {
668 int len = NLA_HDRLEN + sizeof(xfrm_algo);
669 strncpy(algo->crypt.alg_name, inAlgo.name.c_str(), sizeof(algo->crypt.alg_name));
670 algo->crypt.alg_key_len = inAlgo.key.size() * 8; // bits
671 memcpy(algo->key, &inAlgo.key[0], inAlgo.key.size()); // FIXME :safety checks
672 len += inAlgo.key.size();
673 fillXfrmNlaHdr(&algo->hdr, XFRMA_ALG_CRYPT, len);
674 return len;
675}
676
677int XfrmController::fillNlAttrXfrmAlgoAuth(const XfrmAlgo& inAlgo, nlattr_algo_auth* algo) {
678 int len = NLA_HDRLEN + sizeof(xfrm_algo_auth);
679 strncpy(algo->auth.alg_name, inAlgo.name.c_str(), sizeof(algo->auth.alg_name));
680 algo->auth.alg_key_len = inAlgo.key.size() * 8; // bits
681
682 // This is the extra field for ALG_AUTH_TRUNC
683 algo->auth.alg_trunc_len = inAlgo.truncLenBits;
684
685 memcpy(algo->key, &inAlgo.key[0], inAlgo.key.size()); // FIXME :safety checks
686 len += inAlgo.key.size();
687
688 fillXfrmNlaHdr(&algo->hdr, XFRMA_ALG_AUTH_TRUNC, len);
689 return len;
690}
691
Nathan Harold420ceac2017-04-05 19:36:59 -0700692int XfrmController::fillNlAttrXfrmEncapTmpl(const XfrmSaInfo& record, nlattr_encap_tmpl* tmpl) {
693 if (record.encap.type == XfrmEncapType::NONE) {
694 return 0;
695 }
696
697 int len = NLA_HDRLEN + sizeof(xfrm_encap_tmpl);
698 tmpl->tmpl.encap_type = static_cast<uint16_t>(record.encap.type);
699 tmpl->tmpl.encap_sport = htons(record.encap.srcPort);
700 tmpl->tmpl.encap_dport = htons(record.encap.dstPort);
701 fillXfrmNlaHdr(&tmpl->hdr, XFRMA_ENCAP, len);
702 return len;
703}
704
Nathan Harold1a371532017-01-30 12:30:48 -0800705int XfrmController::fillUserSaInfo(const XfrmSaInfo& record, xfrm_usersa_info* usersa) {
706 fillTransportModeSelector(record, &usersa->sel);
707
708 usersa->id.proto = IPPROTO_ESP;
709 usersa->id.spi = record.spi;
710 usersa->id.daddr = record.dstAddr;
711
712 usersa->saddr = record.srcAddr;
713
714 fillXfrmLifetimeDefaults(&usersa->lft);
715 fillXfrmCurLifetimeDefaults(&usersa->curlft);
716 memset(&usersa->stats, 0, sizeof(usersa->stats)); // leave stats zeroed out
717 usersa->reqid = record.transformId;
718 usersa->family = record.addrFamily;
719 usersa->mode = static_cast<uint8_t>(record.mode);
720 usersa->replay_window = REPLAY_WINDOW_SIZE;
721 usersa->flags = 0; // TODO: should we actually set flags, XFRM_SA_XFLAG_DONT_ENCAP_DSCP?
722 return sizeof(*usersa);
723}
724
725int XfrmController::fillUserSaId(const XfrmSaId& record, xfrm_usersa_id* said) {
726 said->daddr = record.dstAddr;
727 said->spi = record.spi;
728 said->family = record.addrFamily;
729 said->proto = IPPROTO_ESP;
730
731 return sizeof(*said);
732}
733
ludi6e8eccd2017-08-14 14:40:37 -0700734netdutils::Status XfrmController::deleteSecurityAssociation(const XfrmSaId& record,
735 const XfrmSocket& sock) {
Nathan Harold1a371532017-01-30 12:30:48 -0800736 xfrm_usersa_id said{};
737
ludie51e3862017-08-15 19:28:12 -0700738 enum { NLMSG_HDR, USERSAID, USERSAID_PAD };
Nathan Harold1a371532017-01-30 12:30:48 -0800739
ludie51e3862017-08-15 19:28:12 -0700740 std::vector<iovec> iov = {
Nathan Harold1a371532017-01-30 12:30:48 -0800741 {NULL, 0}, // reserved for the eventual addition of a NLMSG_HDR
742 {&said, 0}, // main usersa_info struct
743 {kPadBytes, 0}, // up to NLMSG_ALIGNTO pad bytes of padding
744 };
745
746 int len;
747 len = iov[USERSAID].iov_len = fillUserSaId(record, &said);
748 iov[USERSAID_PAD].iov_len = NLMSG_ALIGN(len) - len;
749
ludie51e3862017-08-15 19:28:12 -0700750 return sock.sendMessage(XFRM_MSG_DELSA, NETLINK_REQUEST_FLAGS, 0, &iov);
Nathan Harold1a371532017-01-30 12:30:48 -0800751}
752
ludi6e8eccd2017-08-14 14:40:37 -0700753netdutils::Status XfrmController::allocateSpi(const XfrmSaInfo& record, uint32_t minSpi,
754 uint32_t maxSpi, uint32_t* outSpi,
755 const XfrmSocket& sock) {
Nathan Harold1a371532017-01-30 12:30:48 -0800756 xfrm_userspi_info spiInfo{};
757
ludie51e3862017-08-15 19:28:12 -0700758 enum { NLMSG_HDR, USERSAID, USERSAID_PAD };
Nathan Harold1a371532017-01-30 12:30:48 -0800759
ludie51e3862017-08-15 19:28:12 -0700760 std::vector<iovec> iov = {
Nathan Harold1a371532017-01-30 12:30:48 -0800761 {NULL, 0}, // reserved for the eventual addition of a NLMSG_HDR
762 {&spiInfo, 0}, // main userspi_info struct
763 {kPadBytes, 0}, // up to NLMSG_ALIGNTO pad bytes of padding
764 };
765
766 int len;
767 if (fillUserSaInfo(record, &spiInfo.info) == 0) {
768 ALOGE("Failed to fill transport SA Info");
769 }
770
771 len = iov[USERSAID].iov_len = sizeof(spiInfo);
772 iov[USERSAID_PAD].iov_len = NLMSG_ALIGN(len) - len;
773
774 RandomSpi spiGen = RandomSpi(minSpi, maxSpi);
ludi6e8eccd2017-08-14 14:40:37 -0700775 int spi;
776 netdutils::Status ret;
Nathan Harold1a371532017-01-30 12:30:48 -0800777 while ((spi = spiGen.next()) != INVALID_SPI) {
778 spiInfo.min = spi;
779 spiInfo.max = spi;
ludie51e3862017-08-15 19:28:12 -0700780 ret = sock.sendMessage(XFRM_MSG_ALLOCSPI, NETLINK_REQUEST_FLAGS, 0, &iov);
Nathan Harold1a371532017-01-30 12:30:48 -0800781
782 /* If the SPI is in use, we'll get ENOENT */
ludi6e8eccd2017-08-14 14:40:37 -0700783 if (netdutils::equalToErrno(ret, ENOENT))
Nathan Harold1a371532017-01-30 12:30:48 -0800784 continue;
785
ludi6e8eccd2017-08-14 14:40:37 -0700786 if (isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800787 *outSpi = spi;
Nathan Harold420ceac2017-04-05 19:36:59 -0700788 ALOGD("Allocated an SPI: %x", *outSpi);
Nathan Harold1a371532017-01-30 12:30:48 -0800789 } else {
790 *outSpi = INVALID_SPI;
ludi6e8eccd2017-08-14 14:40:37 -0700791 ALOGE("SPI Allocation Failed with error %d", ret.code());
Nathan Harold1a371532017-01-30 12:30:48 -0800792 }
793
794 return ret;
795 }
796
797 // Should always be -ENOENT if we get here
798 return ret;
799}
800
801int XfrmController::fillTransportModeUserSpInfo(const XfrmSaInfo& record,
802 xfrm_userpolicy_info* usersp) {
803 fillTransportModeSelector(record, &usersp->sel);
804 fillXfrmLifetimeDefaults(&usersp->lft);
805 fillXfrmCurLifetimeDefaults(&usersp->curlft);
Nathan Harold420ceac2017-04-05 19:36:59 -0700806 /* if (index) index & 0x3 == dir -- must be true
807 * xfrm_user.c:verify_newpolicy_info() */
Nathan Harold1a371532017-01-30 12:30:48 -0800808 usersp->index = 0;
809 usersp->dir = static_cast<uint8_t>(record.direction);
810 usersp->action = XFRM_POLICY_ALLOW;
811 usersp->flags = XFRM_POLICY_LOCALOK;
812 usersp->share = XFRM_SHARE_UNIQUE;
813 return sizeof(*usersp);
814}
815
816int XfrmController::fillUserTemplate(const XfrmSaInfo& record, xfrm_user_tmpl* tmpl) {
817 tmpl->id.daddr = record.dstAddr;
818 tmpl->id.spi = record.spi;
819 tmpl->id.proto = IPPROTO_ESP;
820
821 tmpl->family = record.addrFamily;
822 tmpl->saddr = record.srcAddr;
823 tmpl->reqid = record.transformId;
824 tmpl->mode = static_cast<uint8_t>(record.mode);
825 tmpl->share = XFRM_SHARE_UNIQUE;
826 tmpl->optional = 0; // if this is true, then a failed state lookup will be considered OK:
827 // http://lxr.free-electrons.com/source/net/xfrm/xfrm_policy.c#L1492
828 tmpl->aalgos = ALGO_MASK_AUTH_ALL; // TODO: if there's a bitmask somewhere of
829 // algos, we should find it and apply it.
830 // I can't find one.
831 tmpl->ealgos = ALGO_MASK_CRYPT_ALL; // TODO: if there's a bitmask somewhere...
832 return 0;
833}
834
835} // namespace net
836} // namespace android