blob: ddfda5a3acc6b72b32c6372356333a99218ebff0 [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>
19#include <vector>
20
21#include <ctype.h>
22#include <errno.h>
23#include <fcntl.h>
24#include <getopt.h>
25#include <stdio.h>
26#include <stdlib.h>
27#include <string.h>
Nathan Harold420ceac2017-04-05 19:36:59 -070028
29#define __STDC_FORMAT_MACROS
Nathan Harold1a371532017-01-30 12:30:48 -080030#include <inttypes.h>
31
32#include <arpa/inet.h>
33#include <netinet/in.h>
34
35#include <sys/socket.h>
36#include <sys/stat.h>
37#include <sys/types.h>
38#include <sys/wait.h>
39
40#include <linux/in.h>
41#include <linux/netlink.h>
42#include <linux/xfrm.h>
43
44#include "android-base/stringprintf.h"
45#include "android-base/strings.h"
46#include "android-base/unique_fd.h"
47#define LOG_TAG "XfrmController"
48#include "NetdConstants.h"
49#include "NetlinkCommands.h"
50#include "ResponseCode.h"
51#include "XfrmController.h"
ludi4072ff22017-06-15 08:56:52 -070052#include "netdutils/Fd.h"
53#include "netdutils/Slice.h"
54#include "netdutils/Syscalls.h"
Nathan Harold1a371532017-01-30 12:30:48 -080055#include <cutils/log.h>
56#include <cutils/properties.h>
57#include <logwrap/logwrap.h>
58
59#define VDBG 1 // STOPSHIP if true
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
122#if VDBG
Nathan Harold420ceac2017-04-05 19:36:59 -0700123#define LOG_HEX(__desc16__, __buf__, __len__) \
124 do { \
125 logHex(__desc16__, __buf__, __len__); \
126 } while (0)
ludie51e3862017-08-15 19:28:12 -0700127#define LOG_IOV(__iov__) \
Nathan Harold420ceac2017-04-05 19:36:59 -0700128 do { \
ludie51e3862017-08-15 19:28:12 -0700129 logIov(__iov__); \
Nathan Harold420ceac2017-04-05 19:36:59 -0700130 } while (0)
Nathan Harold1a371532017-01-30 12:30:48 -0800131
132void logHex(const char* desc16, const char* buf, size_t len) {
133 char* printBuf = new char[len * 2 + 1 + 26]; // len->ascii, +newline, +prefix strlen
134 int offset = 0;
135 if (desc16) {
136 sprintf(printBuf, "{%-16s}", desc16);
137 offset += 18; // prefix string length
138 }
139 sprintf(printBuf + offset, "[%4.4u]: ", (len > 9999) ? 9999 : (unsigned)len);
140 offset += 8;
141
142 for (uint32_t j = 0; j < (uint32_t)len; j++) {
143 sprintf(&printBuf[j * 2 + offset], "%0.2x", buf[j]);
144 }
145 ALOGD("%s", printBuf);
146 delete[] printBuf;
147}
148
ludie51e3862017-08-15 19:28:12 -0700149void logIov(const std::vector<iovec>& iov) {
150 for (const iovec& row : iov) {
151 logHex(0, reinterpret_cast<char*>(row.iov_base), row.iov_len);
Nathan Harold1a371532017-01-30 12:30:48 -0800152 }
153}
154
ludi6e8eccd2017-08-14 14:40:37 -0700155// TODO: Need to consider a way to refer to the sSycalls instance
ludi4072ff22017-06-15 08:56:52 -0700156inline Syscalls& getSyscallInstance() { return netdutils::sSyscalls.get(); }
157
Nathan Harold1a371532017-01-30 12:30:48 -0800158#else
159#define LOG_HEX(__desc16__, __buf__, __len__)
160#define LOG_IOV(__iov__, __iov_len__)
161#endif
162
163class XfrmSocketImpl : public XfrmSocket {
164private:
165 static constexpr int NLMSG_DEFAULTSIZE = 8192;
166
167 union NetlinkResponse {
168 nlmsghdr hdr;
169 struct _err_ {
170 nlmsghdr hdr;
171 nlmsgerr err;
172 } err;
173
174 struct _buf_ {
175 nlmsghdr hdr;
176 char buf[NLMSG_DEFAULTSIZE];
177 } buf;
178 };
179
180public:
ludi6e8eccd2017-08-14 14:40:37 -0700181 netdutils::Status open() override {
Nathan Harold1a371532017-01-30 12:30:48 -0800182 mSock = openNetlinkSocket(NETLINK_XFRM);
ludi6e8eccd2017-08-14 14:40:37 -0700183 if (mSock < 0) {
Nathan Harold1a371532017-01-30 12:30:48 -0800184 ALOGW("Could not get a new socket, line=%d", __LINE__);
ludi6e8eccd2017-08-14 14:40:37 -0700185 return netdutils::statusFromErrno(-mSock, "Could not open netlink socket");
Nathan Harold1a371532017-01-30 12:30:48 -0800186 }
187
ludi6e8eccd2017-08-14 14:40:37 -0700188 return netdutils::status::ok;
Nathan Harold1a371532017-01-30 12:30:48 -0800189 }
190
ludi6e8eccd2017-08-14 14:40:37 -0700191 static netdutils::Status validateResponse(NetlinkResponse response, size_t len) {
Nathan Harold1a371532017-01-30 12:30:48 -0800192 if (len < sizeof(nlmsghdr)) {
193 ALOGW("Invalid response message received over netlink");
ludi6e8eccd2017-08-14 14:40:37 -0700194 return netdutils::statusFromErrno(EBADMSG, "Invalid message");
Nathan Harold1a371532017-01-30 12:30:48 -0800195 }
196
197 switch (response.hdr.nlmsg_type) {
198 case NLMSG_NOOP:
199 case NLMSG_DONE:
ludi6e8eccd2017-08-14 14:40:37 -0700200 return netdutils::status::ok;
Nathan Harold1a371532017-01-30 12:30:48 -0800201 case NLMSG_OVERRUN:
202 ALOGD("Netlink request overran kernel buffer");
ludi6e8eccd2017-08-14 14:40:37 -0700203 return netdutils::statusFromErrno(EBADMSG, "Kernel buffer overrun");
Nathan Harold1a371532017-01-30 12:30:48 -0800204 case NLMSG_ERROR:
205 if (len < sizeof(NetlinkResponse::_err_)) {
206 ALOGD("Netlink message received malformed error response");
ludi6e8eccd2017-08-14 14:40:37 -0700207 return netdutils::statusFromErrno(EBADMSG, "Malformed error response");
Nathan Harold1a371532017-01-30 12:30:48 -0800208 }
ludi6e8eccd2017-08-14 14:40:37 -0700209 return netdutils::statusFromErrno(
210 -response.err.err.error,
211 "Error netlink message"); // Netlink errors are negative errno.
Nathan Harold1a371532017-01-30 12:30:48 -0800212 case XFRM_MSG_NEWSA:
213 break;
214 }
215
216 if (response.hdr.nlmsg_type < XFRM_MSG_BASE /*== NLMSG_MIN_TYPE*/ ||
217 response.hdr.nlmsg_type > XFRM_MSG_MAX) {
218 ALOGD("Netlink message responded with an out-of-range message ID");
ludi6e8eccd2017-08-14 14:40:37 -0700219 return netdutils::statusFromErrno(EBADMSG, "Invalid message ID");
Nathan Harold1a371532017-01-30 12:30:48 -0800220 }
221
222 // TODO Add more message validation here
ludi6e8eccd2017-08-14 14:40:37 -0700223 return netdutils::status::ok;
Nathan Harold1a371532017-01-30 12:30:48 -0800224 }
225
ludi6e8eccd2017-08-14 14:40:37 -0700226 netdutils::Status sendMessage(uint16_t nlMsgType, uint16_t nlMsgFlags, uint16_t nlMsgSeqNum,
227 std::vector<iovec>* iovecs) const override {
Nathan Harold1a371532017-01-30 12:30:48 -0800228 nlmsghdr nlMsg = {
229 .nlmsg_type = nlMsgType, .nlmsg_flags = nlMsgFlags, .nlmsg_seq = nlMsgSeqNum,
230 };
231
ludie51e3862017-08-15 19:28:12 -0700232 (*iovecs)[0].iov_base = &nlMsg;
233 (*iovecs)[0].iov_len = NLMSG_HDRLEN;
234 for (const iovec& iov : *iovecs) {
235 nlMsg.nlmsg_len += iov.iov_len;
Nathan Harold1a371532017-01-30 12:30:48 -0800236 }
237
238 ALOGD("Sending Netlink XFRM Message: %s", xfrmMsgTypeToString(nlMsgType));
239 if (VDBG)
ludie51e3862017-08-15 19:28:12 -0700240 LOG_IOV(*iovecs);
Nathan Harold1a371532017-01-30 12:30:48 -0800241
ludie51e3862017-08-15 19:28:12 -0700242 StatusOr<size_t> writeResult = getSyscallInstance().writev(mSock, *iovecs);
ludi4072ff22017-06-15 08:56:52 -0700243 if (!isOk(writeResult)) {
244 ALOGE("netlink socket writev failed (%s)", toString(writeResult).c_str());
ludi6e8eccd2017-08-14 14:40:37 -0700245 return writeResult;
Nathan Harold1a371532017-01-30 12:30:48 -0800246 }
247
ludi4072ff22017-06-15 08:56:52 -0700248 if (nlMsg.nlmsg_len != writeResult.value()) {
249 ALOGE("Invalid netlink message length sent %d", static_cast<int>(writeResult.value()));
ludi6e8eccd2017-08-14 14:40:37 -0700250 return netdutils::statusFromErrno(EBADMSG, "Invalid message length");
Nathan Harold1a371532017-01-30 12:30:48 -0800251 }
252
ludi4072ff22017-06-15 08:56:52 -0700253 NetlinkResponse response = {};
Nathan Harold1a371532017-01-30 12:30:48 -0800254
ludi4072ff22017-06-15 08:56:52 -0700255 StatusOr<Slice> readResult =
256 getSyscallInstance().read(Fd(mSock), netdutils::makeSlice(response));
257 if (!isOk(readResult)) {
258 ALOGE("netlink response error (%s)", toString(readResult).c_str());
ludi6e8eccd2017-08-14 14:40:37 -0700259 return readResult;
ludi4072ff22017-06-15 08:56:52 -0700260 }
261
262 LOG_HEX("netlink msg resp", reinterpret_cast<char*>(readResult.value().base()),
263 readResult.value().size());
264
ludi6e8eccd2017-08-14 14:40:37 -0700265 Status validateStatus = validateResponse(response, readResult.value().size());
266 if (!isOk(validateStatus)) {
267 ALOGE("netlink response contains error (%s)", toString(validateStatus).c_str());
268 }
269
270 return validateStatus;
Nathan Harold1a371532017-01-30 12:30:48 -0800271 }
272};
273
ludi6e8eccd2017-08-14 14:40:37 -0700274StatusOr<int> convertToXfrmAddr(const std::string& strAddr, xfrm_address_t* xfrmAddr) {
Nathan Harold1a371532017-01-30 12:30:48 -0800275 if (strAddr.length() == 0) {
276 memset(xfrmAddr, 0, sizeof(*xfrmAddr));
277 return AF_UNSPEC;
278 }
279
280 if (inet_pton(AF_INET6, strAddr.c_str(), reinterpret_cast<void*>(xfrmAddr))) {
281 return AF_INET6;
282 } else if (inet_pton(AF_INET, strAddr.c_str(), reinterpret_cast<void*>(xfrmAddr))) {
283 return AF_INET;
284 } else {
ludi6e8eccd2017-08-14 14:40:37 -0700285 return netdutils::statusFromErrno(EAFNOSUPPORT, "Invalid address family");
Nathan Harold1a371532017-01-30 12:30:48 -0800286 }
287}
288
289void fillXfrmNlaHdr(nlattr* hdr, uint16_t type, uint16_t len) {
290 hdr->nla_type = type;
291 hdr->nla_len = len;
292}
293
294void fillXfrmCurLifetimeDefaults(xfrm_lifetime_cur* cur) {
295 memset(reinterpret_cast<char*>(cur), 0, sizeof(*cur));
296}
297void fillXfrmLifetimeDefaults(xfrm_lifetime_cfg* cfg) {
298 cfg->soft_byte_limit = XFRM_INF;
299 cfg->hard_byte_limit = XFRM_INF;
300 cfg->soft_packet_limit = XFRM_INF;
301 cfg->hard_packet_limit = XFRM_INF;
302}
303
304/*
305 * Allocate SPIs within an (inclusive) range of min-max.
306 * returns 0 (INVALID_SPI) once the entire range has been parsed.
307 */
308class RandomSpi {
309public:
310 RandomSpi(int min, int max) : mMin(min) {
311 time_t t;
312 srand((unsigned int)time(&t));
313 // TODO: more random random
314 mNext = rand();
315 mSize = max - min + 1;
316 mCount = mSize;
317 }
318
319 uint32_t next() {
320 if (!mCount)
321 return 0;
322 mCount--;
323 return (mNext++ % mSize) + mMin;
324 }
325
326private:
327 uint32_t mNext;
328 uint32_t mSize;
329 uint32_t mMin;
330 uint32_t mCount;
331};
332
333} // namespace
334
335//
336// Begin XfrmController Impl
337//
338//
339XfrmController::XfrmController(void) {}
340
ludi6e8eccd2017-08-14 14:40:37 -0700341netdutils::Status XfrmController::ipSecAllocateSpi(int32_t transformId, int32_t direction,
342 const std::string& localAddress,
343 const std::string& remoteAddress, int32_t inSpi,
344 int32_t* outSpi) {
Nathan Harold1a371532017-01-30 12:30:48 -0800345 ALOGD("XfrmController:%s, line=%d", __FUNCTION__, __LINE__);
346 ALOGD("transformId=%d", transformId);
347 ALOGD("direction=%d", direction);
348 ALOGD("localAddress=%s", localAddress.c_str());
349 ALOGD("remoteAddress=%s", remoteAddress.c_str());
350 ALOGD("inSpi=%0.8x", inSpi);
351
352 XfrmSaInfo saInfo{};
Nathan Harold1a371532017-01-30 12:30:48 -0800353
ludi6e8eccd2017-08-14 14:40:37 -0700354 netdutils::Status ret =
355 fillXfrmSaId(direction, localAddress, remoteAddress, INVALID_SPI, &saInfo);
356 if (!isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800357 return ret;
358 }
359
360 XfrmSocketImpl sock;
ludi6e8eccd2017-08-14 14:40:37 -0700361 netdutils::Status socketStatus = sock.open();
362 if (!isOk(socketStatus)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800363 ALOGD("Sock open failed for XFRM, line=%d", __LINE__);
ludi6e8eccd2017-08-14 14:40:37 -0700364 return socketStatus;
Nathan Harold1a371532017-01-30 12:30:48 -0800365 }
366
367 int minSpi = RAND_SPI_MIN, maxSpi = RAND_SPI_MAX;
368
369 if (inSpi)
370 minSpi = maxSpi = inSpi;
ludi6e8eccd2017-08-14 14:40:37 -0700371
Nathan Harold1a371532017-01-30 12:30:48 -0800372 ret = allocateSpi(saInfo, minSpi, maxSpi, reinterpret_cast<uint32_t*>(outSpi), sock);
ludi6e8eccd2017-08-14 14:40:37 -0700373 if (!isOk(ret)) {
374 // TODO: May want to return a new Status with a modified status string
Nathan Harold1a371532017-01-30 12:30:48 -0800375 ALOGD("Failed to Allocate an SPI, line=%d", __LINE__);
376 *outSpi = INVALID_SPI;
377 }
378
379 return ret;
380}
381
ludi6e8eccd2017-08-14 14:40:37 -0700382netdutils::Status XfrmController::ipSecAddSecurityAssociation(
Nathan Harold1a371532017-01-30 12:30:48 -0800383 int32_t transformId, int32_t mode, int32_t direction, const std::string& localAddress,
Nathan Harold420ceac2017-04-05 19:36:59 -0700384 const std::string& remoteAddress, int64_t underlyingNetworkHandle, int32_t spi,
Nathan Harold1a371532017-01-30 12:30:48 -0800385 const std::string& authAlgo, const std::vector<uint8_t>& authKey, int32_t authTruncBits,
386 const std::string& cryptAlgo, const std::vector<uint8_t>& cryptKey, int32_t cryptTruncBits,
ludiec836052017-05-20 14:17:05 -0700387 int32_t encapType, int32_t encapLocalPort, int32_t encapRemotePort) {
Nathan Harold1a371532017-01-30 12:30:48 -0800388 android::RWLock::AutoWLock lock(mLock);
389
390 ALOGD("XfrmController::%s, line=%d", __FUNCTION__, __LINE__);
391 ALOGD("transformId=%d", transformId);
392 ALOGD("mode=%d", mode);
393 ALOGD("direction=%d", direction);
394 ALOGD("localAddress=%s", localAddress.c_str());
395 ALOGD("remoteAddress=%s", remoteAddress.c_str());
Nathan Harold420ceac2017-04-05 19:36:59 -0700396 ALOGD("underlyingNetworkHandle=%" PRIx64, underlyingNetworkHandle);
Nathan Harold1a371532017-01-30 12:30:48 -0800397 ALOGD("spi=%0.8x", spi);
398 ALOGD("authAlgo=%s", authAlgo.c_str());
399 ALOGD("authTruncBits=%d", authTruncBits);
400 ALOGD("cryptAlgo=%s", cryptAlgo.c_str());
401 ALOGD("cryptTruncBits=%d,", cryptTruncBits);
402 ALOGD("encapType=%d", encapType);
403 ALOGD("encapLocalPort=%d", encapLocalPort);
404 ALOGD("encapRemotePort=%d", encapRemotePort);
405
406 XfrmSaInfo saInfo{};
ludi6e8eccd2017-08-14 14:40:37 -0700407 netdutils::Status ret = fillXfrmSaId(direction, localAddress, remoteAddress, spi, &saInfo);
408 if (!isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800409 return ret;
410 }
411
412 saInfo.transformId = transformId;
413
414 // STOPSHIP : range check the key lengths to prevent puncturing and overflow
415 saInfo.auth = XfrmAlgo{
416 .name = authAlgo, .key = authKey, .truncLenBits = static_cast<uint16_t>(authTruncBits)};
417
418 saInfo.crypt = XfrmAlgo{
419 .name = cryptAlgo, .key = cryptKey, .truncLenBits = static_cast<uint16_t>(cryptTruncBits)};
420
421 saInfo.direction = static_cast<XfrmDirection>(direction);
422
423 switch (static_cast<XfrmMode>(mode)) {
424 case XfrmMode::TRANSPORT:
425 case XfrmMode::TUNNEL:
426 saInfo.mode = static_cast<XfrmMode>(mode);
427 break;
428 default:
ludi6e8eccd2017-08-14 14:40:37 -0700429 return netdutils::statusFromErrno(EINVAL, "Invalid xfrm mode");
Nathan Harold1a371532017-01-30 12:30:48 -0800430 }
431
432 XfrmSocketImpl sock;
ludi6e8eccd2017-08-14 14:40:37 -0700433 netdutils::Status socketStatus = sock.open();
434 if (!isOk(socketStatus)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800435 ALOGD("Sock open failed for XFRM, line=%d", __LINE__);
ludi6e8eccd2017-08-14 14:40:37 -0700436 return socketStatus;
Nathan Harold1a371532017-01-30 12:30:48 -0800437 }
438
Nathan Harold420ceac2017-04-05 19:36:59 -0700439 switch (static_cast<XfrmEncapType>(encapType)) {
440 case XfrmEncapType::ESPINUDP:
441 case XfrmEncapType::ESPINUDP_NON_IKE:
442 if (saInfo.addrFamily != AF_INET) {
ludi6e8eccd2017-08-14 14:40:37 -0700443 return netdutils::statusFromErrno(EAFNOSUPPORT, "IPv6 encap not supported");
Nathan Harold420ceac2017-04-05 19:36:59 -0700444 }
445 switch (saInfo.direction) {
446 case XfrmDirection::IN:
447 saInfo.encap.srcPort = encapRemotePort;
448 saInfo.encap.dstPort = encapLocalPort;
449 break;
450 case XfrmDirection::OUT:
451 saInfo.encap.srcPort = encapLocalPort;
452 saInfo.encap.dstPort = encapRemotePort;
453 break;
454 default:
ludi6e8eccd2017-08-14 14:40:37 -0700455 return netdutils::statusFromErrno(EINVAL, "Invalid direction");
Nathan Harold420ceac2017-04-05 19:36:59 -0700456 }
457 // fall through
458 case XfrmEncapType::NONE:
459 saInfo.encap.type = static_cast<XfrmEncapType>(encapType);
460 break;
461 default:
ludi6e8eccd2017-08-14 14:40:37 -0700462 return netdutils::statusFromErrno(EINVAL, "Invalid encap type");
Nathan Harold420ceac2017-04-05 19:36:59 -0700463 }
464
Nathan Harold1a371532017-01-30 12:30:48 -0800465 ret = createTransportModeSecurityAssociation(saInfo, sock);
ludi6e8eccd2017-08-14 14:40:37 -0700466 if (!isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800467 ALOGD("Failed creating a Security Association, line=%d", __LINE__);
Nathan Harold1a371532017-01-30 12:30:48 -0800468 }
469
ludi6e8eccd2017-08-14 14:40:37 -0700470 return ret;
Nathan Harold1a371532017-01-30 12:30:48 -0800471}
472
ludi6e8eccd2017-08-14 14:40:37 -0700473netdutils::Status XfrmController::ipSecDeleteSecurityAssociation(int32_t transformId,
474 int32_t direction,
475 const std::string& localAddress,
476 const std::string& remoteAddress,
477 int32_t spi) {
Nathan Harold1a371532017-01-30 12:30:48 -0800478 ALOGD("XfrmController:%s, line=%d", __FUNCTION__, __LINE__);
479 ALOGD("transformId=%d", transformId);
480 ALOGD("direction=%d", direction);
481 ALOGD("localAddress=%s", localAddress.c_str());
482 ALOGD("remoteAddress=%s", remoteAddress.c_str());
483 ALOGD("spi=%0.8x", spi);
484
Jonathan Basseriebdaa682017-09-14 16:33:08 -0700485 XfrmSaId saId{};
ludi6e8eccd2017-08-14 14:40:37 -0700486 netdutils::Status ret = fillXfrmSaId(direction, localAddress, remoteAddress, spi, &saId);
487 if (!isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800488 return ret;
489 }
490
491 XfrmSocketImpl sock;
ludi6e8eccd2017-08-14 14:40:37 -0700492 netdutils::Status socketStatus = sock.open();
493 if (!isOk(socketStatus)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800494 ALOGD("Sock open failed for XFRM, line=%d", __LINE__);
ludi6e8eccd2017-08-14 14:40:37 -0700495 return socketStatus;
Nathan Harold1a371532017-01-30 12:30:48 -0800496 }
497
498 ret = deleteSecurityAssociation(saId, sock);
ludi6e8eccd2017-08-14 14:40:37 -0700499 if (!isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800500 ALOGD("Failed to delete Security Association, line=%d", __LINE__);
Nathan Harold1a371532017-01-30 12:30:48 -0800501 }
502
503 return ret;
504}
505
ludi6e8eccd2017-08-14 14:40:37 -0700506netdutils::Status XfrmController::fillXfrmSaId(int32_t direction, const std::string& localAddress,
507 const std::string& remoteAddress, int32_t spi,
508 XfrmSaId* xfrmId) {
Nathan Harold1a371532017-01-30 12:30:48 -0800509 xfrm_address_t localXfrmAddr{}, remoteXfrmAddr{};
510
ludi6e8eccd2017-08-14 14:40:37 -0700511 StatusOr<int> addrFamilyLocal, addrFamilyRemote;
Nathan Harold1a371532017-01-30 12:30:48 -0800512 addrFamilyRemote = convertToXfrmAddr(remoteAddress, &remoteXfrmAddr);
513 addrFamilyLocal = convertToXfrmAddr(localAddress, &localXfrmAddr);
ludi6e8eccd2017-08-14 14:40:37 -0700514 if (!isOk(addrFamilyRemote) || !isOk(addrFamilyLocal)) {
515 return netdutils::statusFromErrno(EINVAL,
516 "Invalid address " + localAddress + "/" + remoteAddress);
Nathan Harold1a371532017-01-30 12:30:48 -0800517 }
518
ludi6e8eccd2017-08-14 14:40:37 -0700519 if (addrFamilyRemote.value() == AF_UNSPEC ||
520 (addrFamilyLocal.value() != AF_UNSPEC &&
521 addrFamilyLocal.value() != addrFamilyRemote.value())) {
522 ALOGD("Invalid or Mismatched Address Families, %d != %d, line=%d", addrFamilyLocal.value(),
523 addrFamilyRemote.value(), __LINE__);
524 return netdutils::statusFromErrno(EINVAL, "Invalid or mismatched address families");
Nathan Harold1a371532017-01-30 12:30:48 -0800525 }
526
ludi6e8eccd2017-08-14 14:40:37 -0700527 xfrmId->addrFamily = addrFamilyRemote.value();
Nathan Harold1a371532017-01-30 12:30:48 -0800528
529 xfrmId->spi = htonl(spi);
530
531 switch (static_cast<XfrmDirection>(direction)) {
532 case XfrmDirection::IN:
533 xfrmId->dstAddr = localXfrmAddr;
534 xfrmId->srcAddr = remoteXfrmAddr;
535 break;
536
537 case XfrmDirection::OUT:
538 xfrmId->dstAddr = remoteXfrmAddr;
539 xfrmId->srcAddr = localXfrmAddr;
540 break;
541
542 default:
543 ALOGD("Invalid XFRM direction, line=%d", __LINE__);
544 // Invalid direction for Transport mode transform: time to bail
ludi6e8eccd2017-08-14 14:40:37 -0700545 return netdutils::statusFromErrno(EINVAL, "Invalid direction");
Nathan Harold1a371532017-01-30 12:30:48 -0800546 }
ludi6e8eccd2017-08-14 14:40:37 -0700547 return netdutils::status::ok;
Nathan Harold1a371532017-01-30 12:30:48 -0800548}
549
ludi6e8eccd2017-08-14 14:40:37 -0700550netdutils::Status XfrmController::ipSecApplyTransportModeTransform(
551 const android::base::unique_fd& socket, int32_t transformId, int32_t direction,
552 const std::string& localAddress, const std::string& remoteAddress, int32_t spi) {
Nathan Harold1a371532017-01-30 12:30:48 -0800553 ALOGD("XfrmController::%s, line=%d", __FUNCTION__, __LINE__);
554 ALOGD("transformId=%d", transformId);
555 ALOGD("direction=%d", direction);
556 ALOGD("localAddress=%s", localAddress.c_str());
557 ALOGD("remoteAddress=%s", remoteAddress.c_str());
558 ALOGD("spi=%0.8x", spi);
559
560 struct sockaddr_storage saddr;
561
ludi4072ff22017-06-15 08:56:52 -0700562 StatusOr<sockaddr_storage> ret = getSyscallInstance().getsockname<sockaddr_storage>(Fd(socket));
563 if (!isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800564 ALOGE("Failed to get socket info in %s", __FUNCTION__);
ludi6e8eccd2017-08-14 14:40:37 -0700565 return ret;
Nathan Harold1a371532017-01-30 12:30:48 -0800566 }
567
ludi4072ff22017-06-15 08:56:52 -0700568 saddr = ret.value();
569
Nathan Harold1a371532017-01-30 12:30:48 -0800570 XfrmSaInfo saInfo{};
571 saInfo.transformId = transformId;
572 saInfo.direction = static_cast<XfrmDirection>(direction);
573 saInfo.spi = spi;
574
ludi6e8eccd2017-08-14 14:40:37 -0700575 netdutils::Status status = fillXfrmSaId(direction, localAddress, remoteAddress, spi, &saInfo);
576 if (!isOk(status)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800577 ALOGE("Couldn't build SA ID %s", __FUNCTION__);
ludi6e8eccd2017-08-14 14:40:37 -0700578 return status;
Nathan Harold1a371532017-01-30 12:30:48 -0800579 }
580
581 if (saInfo.addrFamily != saddr.ss_family) {
582 ALOGE("Transform address family(%d) differs from socket address "
Nathan Harold420ceac2017-04-05 19:36:59 -0700583 "family(%d)!",
584 saInfo.addrFamily, saddr.ss_family);
ludi6e8eccd2017-08-14 14:40:37 -0700585 return netdutils::statusFromErrno(EINVAL, "Mismatched address family");
Nathan Harold1a371532017-01-30 12:30:48 -0800586 }
587
588 struct {
589 xfrm_userpolicy_info info;
590 xfrm_user_tmpl tmpl;
591 } policy{};
592
593 fillTransportModeUserSpInfo(saInfo, &policy.info);
594 fillUserTemplate(saInfo, &policy.tmpl);
595
596 LOG_HEX("XfrmUserPolicy", reinterpret_cast<char*>(&policy), sizeof(policy));
597
598 int sockOpt, sockLayer;
599 switch (saInfo.addrFamily) {
600 case AF_INET:
601 sockOpt = IP_XFRM_POLICY;
602 sockLayer = SOL_IP;
603 break;
604 case AF_INET6:
605 sockOpt = IPV6_XFRM_POLICY;
606 sockLayer = SOL_IPV6;
607 break;
608 default:
ludi6e8eccd2017-08-14 14:40:37 -0700609 return netdutils::statusFromErrno(EAFNOSUPPORT, "Invalid address family");
Nathan Harold1a371532017-01-30 12:30:48 -0800610 }
611
ludi6e8eccd2017-08-14 14:40:37 -0700612 status = getSyscallInstance().setsockopt(Fd(socket), sockLayer, sockOpt, policy);
ludi4072ff22017-06-15 08:56:52 -0700613 if (!isOk(status)) {
614 ALOGE("Error setting socket option for XFRM! (%s)", toString(status).c_str());
Nathan Harold1a371532017-01-30 12:30:48 -0800615 }
ludi6e8eccd2017-08-14 14:40:37 -0700616
617 return status;
Nathan Harold1a371532017-01-30 12:30:48 -0800618}
619
ludi6e8eccd2017-08-14 14:40:37 -0700620netdutils::Status
621XfrmController::ipSecRemoveTransportModeTransform(const android::base::unique_fd& socket) {
Nathan Harold1a371532017-01-30 12:30:48 -0800622 (void)socket;
ludi6e8eccd2017-08-14 14:40:37 -0700623 return netdutils::status::ok;
Nathan Harold1a371532017-01-30 12:30:48 -0800624}
625
626void XfrmController::fillTransportModeSelector(const XfrmSaInfo& record, xfrm_selector* selector) {
627 selector->family = record.addrFamily;
628 selector->proto = AF_UNSPEC; // TODO: do we need to match the protocol? it's
629 // possible via the socket
630 selector->ifindex = record.netId; // TODO : still need to sort this out
631}
632
ludi6e8eccd2017-08-14 14:40:37 -0700633netdutils::Status XfrmController::createTransportModeSecurityAssociation(const XfrmSaInfo& record,
634 const XfrmSocket& sock) {
Nathan Harold1a371532017-01-30 12:30:48 -0800635 xfrm_usersa_info usersa{};
636 nlattr_algo_crypt crypt{};
637 nlattr_algo_auth auth{};
Nathan Harold420ceac2017-04-05 19:36:59 -0700638 nlattr_encap_tmpl encap{};
Nathan Harold1a371532017-01-30 12:30:48 -0800639
ludie51e3862017-08-15 19:28:12 -0700640 enum { NLMSG_HDR, USERSA, USERSA_PAD, CRYPT, CRYPT_PAD, AUTH, AUTH_PAD, ENCAP, ENCAP_PAD };
Nathan Harold1a371532017-01-30 12:30:48 -0800641
ludie51e3862017-08-15 19:28:12 -0700642 std::vector<iovec> iov = {
Nathan Harold1a371532017-01-30 12:30:48 -0800643 {NULL, 0}, // reserved for the eventual addition of a NLMSG_HDR
644 {&usersa, 0}, // main usersa_info struct
645 {kPadBytes, 0}, // up to NLMSG_ALIGNTO pad bytes of padding
646 {&crypt, 0}, // adjust size if crypt algo is present
647 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
648 {&auth, 0}, // adjust size if auth algo is present
649 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
Nathan Harold420ceac2017-04-05 19:36:59 -0700650 {&encap, 0}, // adjust size if auth algo is present
651 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
Nathan Harold1a371532017-01-30 12:30:48 -0800652 };
653
654 int len;
655 len = iov[USERSA].iov_len = fillUserSaInfo(record, &usersa);
656 iov[USERSA_PAD].iov_len = NLMSG_ALIGN(len) - len;
657
658 len = iov[CRYPT].iov_len = fillNlAttrXfrmAlgoEnc(record.crypt, &crypt);
659 iov[CRYPT_PAD].iov_len = NLA_ALIGN(len) - len;
660
661 len = iov[AUTH].iov_len = fillNlAttrXfrmAlgoAuth(record.auth, &auth);
662 iov[AUTH_PAD].iov_len = NLA_ALIGN(len) - len;
663
Nathan Harold420ceac2017-04-05 19:36:59 -0700664 len = iov[ENCAP].iov_len = fillNlAttrXfrmEncapTmpl(record, &encap);
665 iov[ENCAP_PAD].iov_len = NLA_ALIGN(len) - len;
ludie51e3862017-08-15 19:28:12 -0700666 return sock.sendMessage(XFRM_MSG_UPDSA, NETLINK_REQUEST_FLAGS, 0, &iov);
Nathan Harold1a371532017-01-30 12:30:48 -0800667}
668
669int XfrmController::fillNlAttrXfrmAlgoEnc(const XfrmAlgo& inAlgo, nlattr_algo_crypt* algo) {
670 int len = NLA_HDRLEN + sizeof(xfrm_algo);
671 strncpy(algo->crypt.alg_name, inAlgo.name.c_str(), sizeof(algo->crypt.alg_name));
672 algo->crypt.alg_key_len = inAlgo.key.size() * 8; // bits
673 memcpy(algo->key, &inAlgo.key[0], inAlgo.key.size()); // FIXME :safety checks
674 len += inAlgo.key.size();
675 fillXfrmNlaHdr(&algo->hdr, XFRMA_ALG_CRYPT, len);
676 return len;
677}
678
679int XfrmController::fillNlAttrXfrmAlgoAuth(const XfrmAlgo& inAlgo, nlattr_algo_auth* algo) {
680 int len = NLA_HDRLEN + sizeof(xfrm_algo_auth);
681 strncpy(algo->auth.alg_name, inAlgo.name.c_str(), sizeof(algo->auth.alg_name));
682 algo->auth.alg_key_len = inAlgo.key.size() * 8; // bits
683
684 // This is the extra field for ALG_AUTH_TRUNC
685 algo->auth.alg_trunc_len = inAlgo.truncLenBits;
686
687 memcpy(algo->key, &inAlgo.key[0], inAlgo.key.size()); // FIXME :safety checks
688 len += inAlgo.key.size();
689
690 fillXfrmNlaHdr(&algo->hdr, XFRMA_ALG_AUTH_TRUNC, len);
691 return len;
692}
693
Nathan Harold420ceac2017-04-05 19:36:59 -0700694int XfrmController::fillNlAttrXfrmEncapTmpl(const XfrmSaInfo& record, nlattr_encap_tmpl* tmpl) {
695 if (record.encap.type == XfrmEncapType::NONE) {
696 return 0;
697 }
698
699 int len = NLA_HDRLEN + sizeof(xfrm_encap_tmpl);
700 tmpl->tmpl.encap_type = static_cast<uint16_t>(record.encap.type);
701 tmpl->tmpl.encap_sport = htons(record.encap.srcPort);
702 tmpl->tmpl.encap_dport = htons(record.encap.dstPort);
703 fillXfrmNlaHdr(&tmpl->hdr, XFRMA_ENCAP, len);
704 return len;
705}
706
Nathan Harold1a371532017-01-30 12:30:48 -0800707int XfrmController::fillUserSaInfo(const XfrmSaInfo& record, xfrm_usersa_info* usersa) {
708 fillTransportModeSelector(record, &usersa->sel);
709
710 usersa->id.proto = IPPROTO_ESP;
711 usersa->id.spi = record.spi;
712 usersa->id.daddr = record.dstAddr;
713
714 usersa->saddr = record.srcAddr;
715
716 fillXfrmLifetimeDefaults(&usersa->lft);
717 fillXfrmCurLifetimeDefaults(&usersa->curlft);
718 memset(&usersa->stats, 0, sizeof(usersa->stats)); // leave stats zeroed out
719 usersa->reqid = record.transformId;
720 usersa->family = record.addrFamily;
721 usersa->mode = static_cast<uint8_t>(record.mode);
722 usersa->replay_window = REPLAY_WINDOW_SIZE;
723 usersa->flags = 0; // TODO: should we actually set flags, XFRM_SA_XFLAG_DONT_ENCAP_DSCP?
724 return sizeof(*usersa);
725}
726
727int XfrmController::fillUserSaId(const XfrmSaId& record, xfrm_usersa_id* said) {
728 said->daddr = record.dstAddr;
729 said->spi = record.spi;
730 said->family = record.addrFamily;
731 said->proto = IPPROTO_ESP;
732
733 return sizeof(*said);
734}
735
ludi6e8eccd2017-08-14 14:40:37 -0700736netdutils::Status XfrmController::deleteSecurityAssociation(const XfrmSaId& record,
737 const XfrmSocket& sock) {
Nathan Harold1a371532017-01-30 12:30:48 -0800738 xfrm_usersa_id said{};
739
ludie51e3862017-08-15 19:28:12 -0700740 enum { NLMSG_HDR, USERSAID, USERSAID_PAD };
Nathan Harold1a371532017-01-30 12:30:48 -0800741
ludie51e3862017-08-15 19:28:12 -0700742 std::vector<iovec> iov = {
Nathan Harold1a371532017-01-30 12:30:48 -0800743 {NULL, 0}, // reserved for the eventual addition of a NLMSG_HDR
744 {&said, 0}, // main usersa_info struct
745 {kPadBytes, 0}, // up to NLMSG_ALIGNTO pad bytes of padding
746 };
747
748 int len;
749 len = iov[USERSAID].iov_len = fillUserSaId(record, &said);
750 iov[USERSAID_PAD].iov_len = NLMSG_ALIGN(len) - len;
751
ludie51e3862017-08-15 19:28:12 -0700752 return sock.sendMessage(XFRM_MSG_DELSA, NETLINK_REQUEST_FLAGS, 0, &iov);
Nathan Harold1a371532017-01-30 12:30:48 -0800753}
754
ludi6e8eccd2017-08-14 14:40:37 -0700755netdutils::Status XfrmController::allocateSpi(const XfrmSaInfo& record, uint32_t minSpi,
756 uint32_t maxSpi, uint32_t* outSpi,
757 const XfrmSocket& sock) {
Nathan Harold1a371532017-01-30 12:30:48 -0800758 xfrm_userspi_info spiInfo{};
759
ludie51e3862017-08-15 19:28:12 -0700760 enum { NLMSG_HDR, USERSAID, USERSAID_PAD };
Nathan Harold1a371532017-01-30 12:30:48 -0800761
ludie51e3862017-08-15 19:28:12 -0700762 std::vector<iovec> iov = {
Nathan Harold1a371532017-01-30 12:30:48 -0800763 {NULL, 0}, // reserved for the eventual addition of a NLMSG_HDR
764 {&spiInfo, 0}, // main userspi_info struct
765 {kPadBytes, 0}, // up to NLMSG_ALIGNTO pad bytes of padding
766 };
767
768 int len;
769 if (fillUserSaInfo(record, &spiInfo.info) == 0) {
770 ALOGE("Failed to fill transport SA Info");
771 }
772
773 len = iov[USERSAID].iov_len = sizeof(spiInfo);
774 iov[USERSAID_PAD].iov_len = NLMSG_ALIGN(len) - len;
775
776 RandomSpi spiGen = RandomSpi(minSpi, maxSpi);
ludi6e8eccd2017-08-14 14:40:37 -0700777 int spi;
778 netdutils::Status ret;
Nathan Harold1a371532017-01-30 12:30:48 -0800779 while ((spi = spiGen.next()) != INVALID_SPI) {
780 spiInfo.min = spi;
781 spiInfo.max = spi;
ludie51e3862017-08-15 19:28:12 -0700782 ret = sock.sendMessage(XFRM_MSG_ALLOCSPI, NETLINK_REQUEST_FLAGS, 0, &iov);
Nathan Harold1a371532017-01-30 12:30:48 -0800783
784 /* If the SPI is in use, we'll get ENOENT */
ludi6e8eccd2017-08-14 14:40:37 -0700785 if (netdutils::equalToErrno(ret, ENOENT))
Nathan Harold1a371532017-01-30 12:30:48 -0800786 continue;
787
ludi6e8eccd2017-08-14 14:40:37 -0700788 if (isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800789 *outSpi = spi;
Nathan Harold420ceac2017-04-05 19:36:59 -0700790 ALOGD("Allocated an SPI: %x", *outSpi);
Nathan Harold1a371532017-01-30 12:30:48 -0800791 } else {
792 *outSpi = INVALID_SPI;
ludi6e8eccd2017-08-14 14:40:37 -0700793 ALOGE("SPI Allocation Failed with error %d", ret.code());
Nathan Harold1a371532017-01-30 12:30:48 -0800794 }
795
796 return ret;
797 }
798
799 // Should always be -ENOENT if we get here
800 return ret;
801}
802
803int XfrmController::fillTransportModeUserSpInfo(const XfrmSaInfo& record,
804 xfrm_userpolicy_info* usersp) {
805 fillTransportModeSelector(record, &usersp->sel);
806 fillXfrmLifetimeDefaults(&usersp->lft);
807 fillXfrmCurLifetimeDefaults(&usersp->curlft);
Nathan Harold420ceac2017-04-05 19:36:59 -0700808 /* if (index) index & 0x3 == dir -- must be true
809 * xfrm_user.c:verify_newpolicy_info() */
Nathan Harold1a371532017-01-30 12:30:48 -0800810 usersp->index = 0;
811 usersp->dir = static_cast<uint8_t>(record.direction);
812 usersp->action = XFRM_POLICY_ALLOW;
813 usersp->flags = XFRM_POLICY_LOCALOK;
814 usersp->share = XFRM_SHARE_UNIQUE;
815 return sizeof(*usersp);
816}
817
818int XfrmController::fillUserTemplate(const XfrmSaInfo& record, xfrm_user_tmpl* tmpl) {
819 tmpl->id.daddr = record.dstAddr;
820 tmpl->id.spi = record.spi;
821 tmpl->id.proto = IPPROTO_ESP;
822
823 tmpl->family = record.addrFamily;
824 tmpl->saddr = record.srcAddr;
825 tmpl->reqid = record.transformId;
826 tmpl->mode = static_cast<uint8_t>(record.mode);
827 tmpl->share = XFRM_SHARE_UNIQUE;
828 tmpl->optional = 0; // if this is true, then a failed state lookup will be considered OK:
829 // http://lxr.free-electrons.com/source/net/xfrm/xfrm_policy.c#L1492
830 tmpl->aalgos = ALGO_MASK_AUTH_ALL; // TODO: if there's a bitmask somewhere of
831 // algos, we should find it and apply it.
832 // I can't find one.
833 tmpl->ealgos = ALGO_MASK_CRYPT_ALL; // TODO: if there's a bitmask somewhere...
834 return 0;
835}
836
837} // namespace net
838} // namespace android