blob: ceaa2a3a52618e8c1d1446c370c0bf98d75d2e8a [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
ludi4072ff22017-06-15 08:56:52 -0700155inline Syscalls& getSyscallInstance() { return netdutils::sSyscalls.get(); }
156
Nathan Harold1a371532017-01-30 12:30:48 -0800157#else
158#define LOG_HEX(__desc16__, __buf__, __len__)
159#define LOG_IOV(__iov__, __iov_len__)
160#endif
161
162class 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:
180 virtual bool open() {
181 mSock = openNetlinkSocket(NETLINK_XFRM);
182 if (mSock <= 0) {
183 ALOGW("Could not get a new socket, line=%d", __LINE__);
184 return false;
185 }
186
187 return true;
188 }
189
190 static int validateResponse(NetlinkResponse response, size_t len) {
191 if (len < sizeof(nlmsghdr)) {
192 ALOGW("Invalid response message received over netlink");
193 return -EBADMSG;
194 }
195
196 switch (response.hdr.nlmsg_type) {
197 case NLMSG_NOOP:
198 case NLMSG_DONE:
199 return 0;
200 case NLMSG_OVERRUN:
201 ALOGD("Netlink request overran kernel buffer");
202 return -EBADMSG;
203 case NLMSG_ERROR:
204 if (len < sizeof(NetlinkResponse::_err_)) {
205 ALOGD("Netlink message received malformed error response");
206 return -EBADMSG;
207 }
208 return response.err.err.error; // Netlink errors are negative errno.
209 case XFRM_MSG_NEWSA:
210 break;
211 }
212
213 if (response.hdr.nlmsg_type < XFRM_MSG_BASE /*== NLMSG_MIN_TYPE*/ ||
214 response.hdr.nlmsg_type > XFRM_MSG_MAX) {
215 ALOGD("Netlink message responded with an out-of-range message ID");
216 return -EBADMSG;
217 }
218
219 // TODO Add more message validation here
220 return 0;
221 }
222
223 virtual int sendMessage(uint16_t nlMsgType, uint16_t nlMsgFlags, uint16_t nlMsgSeqNum,
ludie51e3862017-08-15 19:28:12 -0700224 std::vector<iovec>* iovecs) const {
Nathan Harold1a371532017-01-30 12:30:48 -0800225 nlmsghdr nlMsg = {
226 .nlmsg_type = nlMsgType, .nlmsg_flags = nlMsgFlags, .nlmsg_seq = nlMsgSeqNum,
227 };
228
ludie51e3862017-08-15 19:28:12 -0700229 (*iovecs)[0].iov_base = &nlMsg;
230 (*iovecs)[0].iov_len = NLMSG_HDRLEN;
231 for (const iovec& iov : *iovecs) {
232 nlMsg.nlmsg_len += iov.iov_len;
Nathan Harold1a371532017-01-30 12:30:48 -0800233 }
234
235 ALOGD("Sending Netlink XFRM Message: %s", xfrmMsgTypeToString(nlMsgType));
236 if (VDBG)
ludie51e3862017-08-15 19:28:12 -0700237 LOG_IOV(*iovecs);
Nathan Harold1a371532017-01-30 12:30:48 -0800238
ludie51e3862017-08-15 19:28:12 -0700239 StatusOr<size_t> writeResult = getSyscallInstance().writev(mSock, *iovecs);
ludi4072ff22017-06-15 08:56:52 -0700240 if (!isOk(writeResult)) {
241 ALOGE("netlink socket writev failed (%s)", toString(writeResult).c_str());
242 return -writeResult.status().code();
Nathan Harold1a371532017-01-30 12:30:48 -0800243 }
244
ludi4072ff22017-06-15 08:56:52 -0700245 if (nlMsg.nlmsg_len != writeResult.value()) {
246 ALOGE("Invalid netlink message length sent %d", static_cast<int>(writeResult.value()));
247 return -EBADMSG;
Nathan Harold1a371532017-01-30 12:30:48 -0800248 }
249
ludi4072ff22017-06-15 08:56:52 -0700250 NetlinkResponse response = {};
Nathan Harold1a371532017-01-30 12:30:48 -0800251
ludi4072ff22017-06-15 08:56:52 -0700252 StatusOr<Slice> readResult =
253 getSyscallInstance().read(Fd(mSock), netdutils::makeSlice(response));
254 if (!isOk(readResult)) {
255 ALOGE("netlink response error (%s)", toString(readResult).c_str());
256 return -readResult.status().code();
257 }
258
259 LOG_HEX("netlink msg resp", reinterpret_cast<char*>(readResult.value().base()),
260 readResult.value().size());
261
262 int retNum = validateResponse(response, readResult.value().size());
263 if (retNum < 0)
264 ALOGE("netlink response contains error (%s)", strerror(-retNum));
265 return retNum;
Nathan Harold1a371532017-01-30 12:30:48 -0800266 }
267};
268
269int convertToXfrmAddr(const std::string& strAddr, xfrm_address_t* xfrmAddr) {
270 if (strAddr.length() == 0) {
271 memset(xfrmAddr, 0, sizeof(*xfrmAddr));
272 return AF_UNSPEC;
273 }
274
275 if (inet_pton(AF_INET6, strAddr.c_str(), reinterpret_cast<void*>(xfrmAddr))) {
276 return AF_INET6;
277 } else if (inet_pton(AF_INET, strAddr.c_str(), reinterpret_cast<void*>(xfrmAddr))) {
278 return AF_INET;
279 } else {
280 return -EAFNOSUPPORT;
281 }
282}
283
284void fillXfrmNlaHdr(nlattr* hdr, uint16_t type, uint16_t len) {
285 hdr->nla_type = type;
286 hdr->nla_len = len;
287}
288
289void fillXfrmCurLifetimeDefaults(xfrm_lifetime_cur* cur) {
290 memset(reinterpret_cast<char*>(cur), 0, sizeof(*cur));
291}
292void fillXfrmLifetimeDefaults(xfrm_lifetime_cfg* cfg) {
293 cfg->soft_byte_limit = XFRM_INF;
294 cfg->hard_byte_limit = XFRM_INF;
295 cfg->soft_packet_limit = XFRM_INF;
296 cfg->hard_packet_limit = XFRM_INF;
297}
298
299/*
300 * Allocate SPIs within an (inclusive) range of min-max.
301 * returns 0 (INVALID_SPI) once the entire range has been parsed.
302 */
303class RandomSpi {
304public:
305 RandomSpi(int min, int max) : mMin(min) {
306 time_t t;
307 srand((unsigned int)time(&t));
308 // TODO: more random random
309 mNext = rand();
310 mSize = max - min + 1;
311 mCount = mSize;
312 }
313
314 uint32_t next() {
315 if (!mCount)
316 return 0;
317 mCount--;
318 return (mNext++ % mSize) + mMin;
319 }
320
321private:
322 uint32_t mNext;
323 uint32_t mSize;
324 uint32_t mMin;
325 uint32_t mCount;
326};
327
328} // namespace
329
330//
331// Begin XfrmController Impl
332//
333//
334XfrmController::XfrmController(void) {}
335
336int XfrmController::ipSecAllocateSpi(int32_t transformId, int32_t direction,
337 const std::string& localAddress,
338 const std::string& remoteAddress, int32_t inSpi,
339 int32_t* outSpi) {
Nathan Harold1a371532017-01-30 12:30:48 -0800340 ALOGD("XfrmController:%s, line=%d", __FUNCTION__, __LINE__);
341 ALOGD("transformId=%d", transformId);
342 ALOGD("direction=%d", direction);
343 ALOGD("localAddress=%s", localAddress.c_str());
344 ALOGD("remoteAddress=%s", remoteAddress.c_str());
345 ALOGD("inSpi=%0.8x", inSpi);
346
347 XfrmSaInfo saInfo{};
348 int ret;
349
350 if ((ret = fillXfrmSaId(direction, localAddress, remoteAddress, INVALID_SPI, &saInfo)) < 0) {
351 return ret;
352 }
353
354 XfrmSocketImpl sock;
355 if (!sock.open()) {
356 ALOGD("Sock open failed for XFRM, line=%d", __LINE__);
357 return -1; // TODO: return right error; for whatever reason the sock
358 // failed to open
359 }
360
361 int minSpi = RAND_SPI_MIN, maxSpi = RAND_SPI_MAX;
362
363 if (inSpi)
364 minSpi = maxSpi = inSpi;
365 ret = allocateSpi(saInfo, minSpi, maxSpi, reinterpret_cast<uint32_t*>(outSpi), sock);
366 if (ret < 0) {
367 ALOGD("Failed to Allocate an SPI, line=%d", __LINE__);
368 *outSpi = INVALID_SPI;
369 }
370
371 return ret;
372}
373
374int XfrmController::ipSecAddSecurityAssociation(
375 int32_t transformId, int32_t mode, int32_t direction, const std::string& localAddress,
Nathan Harold420ceac2017-04-05 19:36:59 -0700376 const std::string& remoteAddress, int64_t underlyingNetworkHandle, int32_t spi,
Nathan Harold1a371532017-01-30 12:30:48 -0800377 const std::string& authAlgo, const std::vector<uint8_t>& authKey, int32_t authTruncBits,
378 const std::string& cryptAlgo, const std::vector<uint8_t>& cryptKey, int32_t cryptTruncBits,
ludiec836052017-05-20 14:17:05 -0700379 int32_t encapType, int32_t encapLocalPort, int32_t encapRemotePort) {
Nathan Harold1a371532017-01-30 12:30:48 -0800380 android::RWLock::AutoWLock lock(mLock);
381
382 ALOGD("XfrmController::%s, line=%d", __FUNCTION__, __LINE__);
383 ALOGD("transformId=%d", transformId);
384 ALOGD("mode=%d", mode);
385 ALOGD("direction=%d", direction);
386 ALOGD("localAddress=%s", localAddress.c_str());
387 ALOGD("remoteAddress=%s", remoteAddress.c_str());
Nathan Harold420ceac2017-04-05 19:36:59 -0700388 ALOGD("underlyingNetworkHandle=%" PRIx64, underlyingNetworkHandle);
Nathan Harold1a371532017-01-30 12:30:48 -0800389 ALOGD("spi=%0.8x", spi);
390 ALOGD("authAlgo=%s", authAlgo.c_str());
391 ALOGD("authTruncBits=%d", authTruncBits);
392 ALOGD("cryptAlgo=%s", cryptAlgo.c_str());
393 ALOGD("cryptTruncBits=%d,", cryptTruncBits);
394 ALOGD("encapType=%d", encapType);
395 ALOGD("encapLocalPort=%d", encapLocalPort);
396 ALOGD("encapRemotePort=%d", encapRemotePort);
397
398 XfrmSaInfo saInfo{};
399 int ret;
400
401 if ((ret = fillXfrmSaId(direction, localAddress, remoteAddress, spi, &saInfo)) < 0) {
402 return ret;
403 }
404
405 saInfo.transformId = transformId;
406
407 // STOPSHIP : range check the key lengths to prevent puncturing and overflow
408 saInfo.auth = XfrmAlgo{
409 .name = authAlgo, .key = authKey, .truncLenBits = static_cast<uint16_t>(authTruncBits)};
410
411 saInfo.crypt = XfrmAlgo{
412 .name = cryptAlgo, .key = cryptKey, .truncLenBits = static_cast<uint16_t>(cryptTruncBits)};
413
414 saInfo.direction = static_cast<XfrmDirection>(direction);
415
416 switch (static_cast<XfrmMode>(mode)) {
417 case XfrmMode::TRANSPORT:
418 case XfrmMode::TUNNEL:
419 saInfo.mode = static_cast<XfrmMode>(mode);
420 break;
421 default:
422 return -EINVAL;
423 }
424
425 XfrmSocketImpl sock;
426 if (!sock.open()) {
427 ALOGD("Sock open failed for XFRM, line=%d", __LINE__);
428 return -1; // TODO: return right error; for whatever reason the sock
429 // failed to open
430 }
431
Nathan Harold420ceac2017-04-05 19:36:59 -0700432 switch (static_cast<XfrmEncapType>(encapType)) {
433 case XfrmEncapType::ESPINUDP:
434 case XfrmEncapType::ESPINUDP_NON_IKE:
435 if (saInfo.addrFamily != AF_INET) {
436 return -EAFNOSUPPORT;
437 }
438 switch (saInfo.direction) {
439 case XfrmDirection::IN:
440 saInfo.encap.srcPort = encapRemotePort;
441 saInfo.encap.dstPort = encapLocalPort;
442 break;
443 case XfrmDirection::OUT:
444 saInfo.encap.srcPort = encapLocalPort;
445 saInfo.encap.dstPort = encapRemotePort;
446 break;
447 default:
448 return -EINVAL;
449 }
450 // fall through
451 case XfrmEncapType::NONE:
452 saInfo.encap.type = static_cast<XfrmEncapType>(encapType);
453 break;
454 default:
455 return -EINVAL;
456 }
457
Nathan Harold1a371532017-01-30 12:30:48 -0800458 ret = createTransportModeSecurityAssociation(saInfo, sock);
459 if (ret < 0) {
460 ALOGD("Failed creating a Security Association, line=%d", __LINE__);
461 return ret; // something went wrong creating the SA
462 }
463
Nathan Harold1a371532017-01-30 12:30:48 -0800464 return 0;
465}
466
467int XfrmController::ipSecDeleteSecurityAssociation(int32_t transformId, int32_t direction,
468 const std::string& localAddress,
469 const std::string& remoteAddress, int32_t spi) {
Nathan Harold1a371532017-01-30 12:30:48 -0800470 ALOGD("XfrmController:%s, line=%d", __FUNCTION__, __LINE__);
471 ALOGD("transformId=%d", transformId);
472 ALOGD("direction=%d", direction);
473 ALOGD("localAddress=%s", localAddress.c_str());
474 ALOGD("remoteAddress=%s", remoteAddress.c_str());
475 ALOGD("spi=%0.8x", spi);
476
477 XfrmSaId saId;
478 int ret;
479
480 if ((ret = fillXfrmSaId(direction, localAddress, remoteAddress, spi, &saId)) < 0) {
481 return ret;
482 }
483
484 XfrmSocketImpl sock;
485 if (!sock.open()) {
486 ALOGD("Sock open failed for XFRM, line=%d", __LINE__);
487 return -1; // TODO: return right error; for whatever reason the sock
488 // failed to open
489 }
490
491 ret = deleteSecurityAssociation(saId, sock);
492 if (ret < 0) {
493 ALOGD("Failed to delete Security Association, line=%d", __LINE__);
494 return ret; // something went wrong deleting the SA
495 }
496
497 return ret;
498}
499
500int XfrmController::fillXfrmSaId(int32_t direction, const std::string& localAddress,
501 const std::string& remoteAddress, int32_t spi, XfrmSaId* xfrmId) {
502 xfrm_address_t localXfrmAddr{}, remoteXfrmAddr{};
503
504 int addrFamilyLocal, addrFamilyRemote;
505 addrFamilyRemote = convertToXfrmAddr(remoteAddress, &remoteXfrmAddr);
506 addrFamilyLocal = convertToXfrmAddr(localAddress, &localXfrmAddr);
507 if (addrFamilyRemote < 0 || addrFamilyLocal < 0) {
508 return -EINVAL;
509 }
510
511 if (addrFamilyRemote == AF_UNSPEC ||
512 (addrFamilyLocal != AF_UNSPEC && addrFamilyLocal != addrFamilyRemote)) {
513 ALOGD("Invalid or Mismatched Address Families, %d != %d, line=%d", addrFamilyLocal,
514 addrFamilyRemote, __LINE__);
515 return -EINVAL;
516 }
517
518 xfrmId->addrFamily = addrFamilyRemote;
519
520 xfrmId->spi = htonl(spi);
521
522 switch (static_cast<XfrmDirection>(direction)) {
523 case XfrmDirection::IN:
524 xfrmId->dstAddr = localXfrmAddr;
525 xfrmId->srcAddr = remoteXfrmAddr;
526 break;
527
528 case XfrmDirection::OUT:
529 xfrmId->dstAddr = remoteXfrmAddr;
530 xfrmId->srcAddr = localXfrmAddr;
531 break;
532
533 default:
534 ALOGD("Invalid XFRM direction, line=%d", __LINE__);
535 // Invalid direction for Transport mode transform: time to bail
536 return -EINVAL;
537 }
538 return 0;
539}
540
541int XfrmController::ipSecApplyTransportModeTransform(const android::base::unique_fd& socket,
542 int32_t transformId, int32_t direction,
543 const std::string& localAddress,
544 const std::string& remoteAddress,
545 int32_t spi) {
546 ALOGD("XfrmController::%s, line=%d", __FUNCTION__, __LINE__);
547 ALOGD("transformId=%d", transformId);
548 ALOGD("direction=%d", direction);
549 ALOGD("localAddress=%s", localAddress.c_str());
550 ALOGD("remoteAddress=%s", remoteAddress.c_str());
551 ALOGD("spi=%0.8x", spi);
552
553 struct sockaddr_storage saddr;
554
Nathan Harold1a371532017-01-30 12:30:48 -0800555 int err;
Nathan Harold1a371532017-01-30 12:30:48 -0800556
ludi4072ff22017-06-15 08:56:52 -0700557 StatusOr<sockaddr_storage> ret = getSyscallInstance().getsockname<sockaddr_storage>(Fd(socket));
558 if (!isOk(ret)) {
Nathan Harold1a371532017-01-30 12:30:48 -0800559 ALOGE("Failed to get socket info in %s", __FUNCTION__);
ludi4072ff22017-06-15 08:56:52 -0700560 return -ret.status().code();
Nathan Harold1a371532017-01-30 12:30:48 -0800561 }
562
ludi4072ff22017-06-15 08:56:52 -0700563 saddr = ret.value();
564
Nathan Harold1a371532017-01-30 12:30:48 -0800565 XfrmSaInfo saInfo{};
566 saInfo.transformId = transformId;
567 saInfo.direction = static_cast<XfrmDirection>(direction);
568 saInfo.spi = spi;
569
570 if ((err = fillXfrmSaId(direction, localAddress, remoteAddress, spi, &saInfo)) < 0) {
571 ALOGE("Couldn't build SA ID %s", __FUNCTION__);
572 return -err;
573 }
574
575 if (saInfo.addrFamily != saddr.ss_family) {
576 ALOGE("Transform address family(%d) differs from socket address "
Nathan Harold420ceac2017-04-05 19:36:59 -0700577 "family(%d)!",
578 saInfo.addrFamily, saddr.ss_family);
Nathan Harold1a371532017-01-30 12:30:48 -0800579 return -EINVAL;
580 }
581
582 struct {
583 xfrm_userpolicy_info info;
584 xfrm_user_tmpl tmpl;
585 } policy{};
586
587 fillTransportModeUserSpInfo(saInfo, &policy.info);
588 fillUserTemplate(saInfo, &policy.tmpl);
589
590 LOG_HEX("XfrmUserPolicy", reinterpret_cast<char*>(&policy), sizeof(policy));
591
592 int sockOpt, sockLayer;
593 switch (saInfo.addrFamily) {
594 case AF_INET:
595 sockOpt = IP_XFRM_POLICY;
596 sockLayer = SOL_IP;
597 break;
598 case AF_INET6:
599 sockOpt = IPV6_XFRM_POLICY;
600 sockLayer = SOL_IPV6;
601 break;
602 default:
603 return -EAFNOSUPPORT;
604 }
605
ludi4072ff22017-06-15 08:56:52 -0700606 Status status = getSyscallInstance().setsockopt(Fd(socket), sockLayer, sockOpt, policy);
607 if (!isOk(status)) {
608 ALOGE("Error setting socket option for XFRM! (%s)", toString(status).c_str());
Nathan Harold1a371532017-01-30 12:30:48 -0800609 }
ludi4072ff22017-06-15 08:56:52 -0700610 return -status.code();
Nathan Harold1a371532017-01-30 12:30:48 -0800611}
612
613int XfrmController::ipSecRemoveTransportModeTransform(const android::base::unique_fd& socket) {
614 (void)socket;
615 return 0;
616}
617
618void XfrmController::fillTransportModeSelector(const XfrmSaInfo& record, xfrm_selector* selector) {
619 selector->family = record.addrFamily;
620 selector->proto = AF_UNSPEC; // TODO: do we need to match the protocol? it's
621 // possible via the socket
622 selector->ifindex = record.netId; // TODO : still need to sort this out
623}
624
625int XfrmController::createTransportModeSecurityAssociation(const XfrmSaInfo& record,
626 const XfrmSocket& sock) {
627 xfrm_usersa_info usersa{};
628 nlattr_algo_crypt crypt{};
629 nlattr_algo_auth auth{};
Nathan Harold420ceac2017-04-05 19:36:59 -0700630 nlattr_encap_tmpl encap{};
Nathan Harold1a371532017-01-30 12:30:48 -0800631
ludie51e3862017-08-15 19:28:12 -0700632 enum { NLMSG_HDR, USERSA, USERSA_PAD, CRYPT, CRYPT_PAD, AUTH, AUTH_PAD, ENCAP, ENCAP_PAD };
Nathan Harold1a371532017-01-30 12:30:48 -0800633
ludie51e3862017-08-15 19:28:12 -0700634 std::vector<iovec> iov = {
Nathan Harold1a371532017-01-30 12:30:48 -0800635 {NULL, 0}, // reserved for the eventual addition of a NLMSG_HDR
636 {&usersa, 0}, // main usersa_info struct
637 {kPadBytes, 0}, // up to NLMSG_ALIGNTO pad bytes of padding
638 {&crypt, 0}, // adjust size if crypt algo is present
639 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
640 {&auth, 0}, // adjust size if auth algo is present
641 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
Nathan Harold420ceac2017-04-05 19:36:59 -0700642 {&encap, 0}, // adjust size if auth algo is present
643 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
Nathan Harold1a371532017-01-30 12:30:48 -0800644 };
645
646 int len;
647 len = iov[USERSA].iov_len = fillUserSaInfo(record, &usersa);
648 iov[USERSA_PAD].iov_len = NLMSG_ALIGN(len) - len;
649
650 len = iov[CRYPT].iov_len = fillNlAttrXfrmAlgoEnc(record.crypt, &crypt);
651 iov[CRYPT_PAD].iov_len = NLA_ALIGN(len) - len;
652
653 len = iov[AUTH].iov_len = fillNlAttrXfrmAlgoAuth(record.auth, &auth);
654 iov[AUTH_PAD].iov_len = NLA_ALIGN(len) - len;
655
Nathan Harold420ceac2017-04-05 19:36:59 -0700656 len = iov[ENCAP].iov_len = fillNlAttrXfrmEncapTmpl(record, &encap);
657 iov[ENCAP_PAD].iov_len = NLA_ALIGN(len) - len;
ludie51e3862017-08-15 19:28:12 -0700658 return sock.sendMessage(XFRM_MSG_UPDSA, NETLINK_REQUEST_FLAGS, 0, &iov);
Nathan Harold1a371532017-01-30 12:30:48 -0800659}
660
661int XfrmController::fillNlAttrXfrmAlgoEnc(const XfrmAlgo& inAlgo, nlattr_algo_crypt* algo) {
662 int len = NLA_HDRLEN + sizeof(xfrm_algo);
663 strncpy(algo->crypt.alg_name, inAlgo.name.c_str(), sizeof(algo->crypt.alg_name));
664 algo->crypt.alg_key_len = inAlgo.key.size() * 8; // bits
665 memcpy(algo->key, &inAlgo.key[0], inAlgo.key.size()); // FIXME :safety checks
666 len += inAlgo.key.size();
667 fillXfrmNlaHdr(&algo->hdr, XFRMA_ALG_CRYPT, len);
668 return len;
669}
670
671int XfrmController::fillNlAttrXfrmAlgoAuth(const XfrmAlgo& inAlgo, nlattr_algo_auth* algo) {
672 int len = NLA_HDRLEN + sizeof(xfrm_algo_auth);
673 strncpy(algo->auth.alg_name, inAlgo.name.c_str(), sizeof(algo->auth.alg_name));
674 algo->auth.alg_key_len = inAlgo.key.size() * 8; // bits
675
676 // This is the extra field for ALG_AUTH_TRUNC
677 algo->auth.alg_trunc_len = inAlgo.truncLenBits;
678
679 memcpy(algo->key, &inAlgo.key[0], inAlgo.key.size()); // FIXME :safety checks
680 len += inAlgo.key.size();
681
682 fillXfrmNlaHdr(&algo->hdr, XFRMA_ALG_AUTH_TRUNC, len);
683 return len;
684}
685
Nathan Harold420ceac2017-04-05 19:36:59 -0700686int XfrmController::fillNlAttrXfrmEncapTmpl(const XfrmSaInfo& record, nlattr_encap_tmpl* tmpl) {
687 if (record.encap.type == XfrmEncapType::NONE) {
688 return 0;
689 }
690
691 int len = NLA_HDRLEN + sizeof(xfrm_encap_tmpl);
692 tmpl->tmpl.encap_type = static_cast<uint16_t>(record.encap.type);
693 tmpl->tmpl.encap_sport = htons(record.encap.srcPort);
694 tmpl->tmpl.encap_dport = htons(record.encap.dstPort);
695 fillXfrmNlaHdr(&tmpl->hdr, XFRMA_ENCAP, len);
696 return len;
697}
698
Nathan Harold1a371532017-01-30 12:30:48 -0800699int XfrmController::fillUserSaInfo(const XfrmSaInfo& record, xfrm_usersa_info* usersa) {
700 fillTransportModeSelector(record, &usersa->sel);
701
702 usersa->id.proto = IPPROTO_ESP;
703 usersa->id.spi = record.spi;
704 usersa->id.daddr = record.dstAddr;
705
706 usersa->saddr = record.srcAddr;
707
708 fillXfrmLifetimeDefaults(&usersa->lft);
709 fillXfrmCurLifetimeDefaults(&usersa->curlft);
710 memset(&usersa->stats, 0, sizeof(usersa->stats)); // leave stats zeroed out
711 usersa->reqid = record.transformId;
712 usersa->family = record.addrFamily;
713 usersa->mode = static_cast<uint8_t>(record.mode);
714 usersa->replay_window = REPLAY_WINDOW_SIZE;
715 usersa->flags = 0; // TODO: should we actually set flags, XFRM_SA_XFLAG_DONT_ENCAP_DSCP?
716 return sizeof(*usersa);
717}
718
719int XfrmController::fillUserSaId(const XfrmSaId& record, xfrm_usersa_id* said) {
720 said->daddr = record.dstAddr;
721 said->spi = record.spi;
722 said->family = record.addrFamily;
723 said->proto = IPPROTO_ESP;
724
725 return sizeof(*said);
726}
727
728int XfrmController::deleteSecurityAssociation(const XfrmSaId& record, const XfrmSocket& sock) {
729 xfrm_usersa_id said{};
730
ludie51e3862017-08-15 19:28:12 -0700731 enum { NLMSG_HDR, USERSAID, USERSAID_PAD };
Nathan Harold1a371532017-01-30 12:30:48 -0800732
ludie51e3862017-08-15 19:28:12 -0700733 std::vector<iovec> iov = {
Nathan Harold1a371532017-01-30 12:30:48 -0800734 {NULL, 0}, // reserved for the eventual addition of a NLMSG_HDR
735 {&said, 0}, // main usersa_info struct
736 {kPadBytes, 0}, // up to NLMSG_ALIGNTO pad bytes of padding
737 };
738
739 int len;
740 len = iov[USERSAID].iov_len = fillUserSaId(record, &said);
741 iov[USERSAID_PAD].iov_len = NLMSG_ALIGN(len) - len;
742
ludie51e3862017-08-15 19:28:12 -0700743 return sock.sendMessage(XFRM_MSG_DELSA, NETLINK_REQUEST_FLAGS, 0, &iov);
Nathan Harold1a371532017-01-30 12:30:48 -0800744}
745
746int XfrmController::allocateSpi(const XfrmSaInfo& record, uint32_t minSpi, uint32_t maxSpi,
747 uint32_t* outSpi, const XfrmSocket& sock) {
748 xfrm_userspi_info spiInfo{};
749
ludie51e3862017-08-15 19:28:12 -0700750 enum { NLMSG_HDR, USERSAID, USERSAID_PAD };
Nathan Harold1a371532017-01-30 12:30:48 -0800751
ludie51e3862017-08-15 19:28:12 -0700752 std::vector<iovec> iov = {
Nathan Harold1a371532017-01-30 12:30:48 -0800753 {NULL, 0}, // reserved for the eventual addition of a NLMSG_HDR
754 {&spiInfo, 0}, // main userspi_info struct
755 {kPadBytes, 0}, // up to NLMSG_ALIGNTO pad bytes of padding
756 };
757
758 int len;
759 if (fillUserSaInfo(record, &spiInfo.info) == 0) {
760 ALOGE("Failed to fill transport SA Info");
761 }
762
763 len = iov[USERSAID].iov_len = sizeof(spiInfo);
764 iov[USERSAID_PAD].iov_len = NLMSG_ALIGN(len) - len;
765
766 RandomSpi spiGen = RandomSpi(minSpi, maxSpi);
767 int spi, ret;
768 while ((spi = spiGen.next()) != INVALID_SPI) {
769 spiInfo.min = spi;
770 spiInfo.max = spi;
ludie51e3862017-08-15 19:28:12 -0700771 ret = sock.sendMessage(XFRM_MSG_ALLOCSPI, NETLINK_REQUEST_FLAGS, 0, &iov);
Nathan Harold1a371532017-01-30 12:30:48 -0800772
773 /* If the SPI is in use, we'll get ENOENT */
774 if (ret == -ENOENT)
775 continue;
776
777 if (ret == 0) {
778 *outSpi = spi;
Nathan Harold420ceac2017-04-05 19:36:59 -0700779 ALOGD("Allocated an SPI: %x", *outSpi);
Nathan Harold1a371532017-01-30 12:30:48 -0800780 } else {
781 *outSpi = INVALID_SPI;
782 ALOGE("SPI Allocation Failed with error %d", ret);
783 }
784
785 return ret;
786 }
787
788 // Should always be -ENOENT if we get here
789 return ret;
790}
791
792int XfrmController::fillTransportModeUserSpInfo(const XfrmSaInfo& record,
793 xfrm_userpolicy_info* usersp) {
794 fillTransportModeSelector(record, &usersp->sel);
795 fillXfrmLifetimeDefaults(&usersp->lft);
796 fillXfrmCurLifetimeDefaults(&usersp->curlft);
Nathan Harold420ceac2017-04-05 19:36:59 -0700797 /* if (index) index & 0x3 == dir -- must be true
798 * xfrm_user.c:verify_newpolicy_info() */
Nathan Harold1a371532017-01-30 12:30:48 -0800799 usersp->index = 0;
800 usersp->dir = static_cast<uint8_t>(record.direction);
801 usersp->action = XFRM_POLICY_ALLOW;
802 usersp->flags = XFRM_POLICY_LOCALOK;
803 usersp->share = XFRM_SHARE_UNIQUE;
804 return sizeof(*usersp);
805}
806
807int XfrmController::fillUserTemplate(const XfrmSaInfo& record, xfrm_user_tmpl* tmpl) {
808 tmpl->id.daddr = record.dstAddr;
809 tmpl->id.spi = record.spi;
810 tmpl->id.proto = IPPROTO_ESP;
811
812 tmpl->family = record.addrFamily;
813 tmpl->saddr = record.srcAddr;
814 tmpl->reqid = record.transformId;
815 tmpl->mode = static_cast<uint8_t>(record.mode);
816 tmpl->share = XFRM_SHARE_UNIQUE;
817 tmpl->optional = 0; // if this is true, then a failed state lookup will be considered OK:
818 // http://lxr.free-electrons.com/source/net/xfrm/xfrm_policy.c#L1492
819 tmpl->aalgos = ALGO_MASK_AUTH_ALL; // TODO: if there's a bitmask somewhere of
820 // algos, we should find it and apply it.
821 // I can't find one.
822 tmpl->ealgos = ALGO_MASK_CRYPT_ALL; // TODO: if there's a bitmask somewhere...
823 return 0;
824}
825
826} // namespace net
827} // namespace android