blob: 34df936b05f07e24dc230f4ae60e3e6b1549a808 [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"
52#include <cutils/log.h>
53#include <cutils/properties.h>
54#include <logwrap/logwrap.h>
55
56#define VDBG 1 // STOPSHIP if true
57
58namespace android {
59namespace net {
60
61namespace {
62
63constexpr uint32_t ALGO_MASK_AUTH_ALL = ~0;
64constexpr uint32_t ALGO_MASK_CRYPT_ALL = ~0;
65
66constexpr uint8_t REPLAY_WINDOW_SIZE = 4;
67
68constexpr uint32_t RAND_SPI_MIN = 1;
69constexpr uint32_t RAND_SPI_MAX = 0xFFFFFFFE;
70
71constexpr uint32_t INVALID_SPI = 0;
72
73#define XFRM_MSG_TRANS(x) \
74 case x: \
75 return #x;
76
77const char* xfrmMsgTypeToString(uint16_t msg) {
78 switch (msg) {
79 XFRM_MSG_TRANS(XFRM_MSG_NEWSA)
80 XFRM_MSG_TRANS(XFRM_MSG_DELSA)
81 XFRM_MSG_TRANS(XFRM_MSG_GETSA)
82 XFRM_MSG_TRANS(XFRM_MSG_NEWPOLICY)
83 XFRM_MSG_TRANS(XFRM_MSG_DELPOLICY)
84 XFRM_MSG_TRANS(XFRM_MSG_GETPOLICY)
85 XFRM_MSG_TRANS(XFRM_MSG_ALLOCSPI)
86 XFRM_MSG_TRANS(XFRM_MSG_ACQUIRE)
87 XFRM_MSG_TRANS(XFRM_MSG_EXPIRE)
88 XFRM_MSG_TRANS(XFRM_MSG_UPDPOLICY)
89 XFRM_MSG_TRANS(XFRM_MSG_UPDSA)
90 XFRM_MSG_TRANS(XFRM_MSG_POLEXPIRE)
91 XFRM_MSG_TRANS(XFRM_MSG_FLUSHSA)
92 XFRM_MSG_TRANS(XFRM_MSG_FLUSHPOLICY)
93 XFRM_MSG_TRANS(XFRM_MSG_NEWAE)
94 XFRM_MSG_TRANS(XFRM_MSG_GETAE)
95 XFRM_MSG_TRANS(XFRM_MSG_REPORT)
96 XFRM_MSG_TRANS(XFRM_MSG_MIGRATE)
97 XFRM_MSG_TRANS(XFRM_MSG_NEWSADINFO)
98 XFRM_MSG_TRANS(XFRM_MSG_GETSADINFO)
99 XFRM_MSG_TRANS(XFRM_MSG_GETSPDINFO)
100 XFRM_MSG_TRANS(XFRM_MSG_NEWSPDINFO)
101 XFRM_MSG_TRANS(XFRM_MSG_MAPPING)
102 default:
103 return "XFRM_MSG UNKNOWN";
104 }
105}
106
107// actually const but cannot be declared as such for reasons
108uint8_t kPadBytesArray[] = {0, 0, 0};
109void* kPadBytes = static_cast<void*>(kPadBytesArray);
110
111#if VDBG
Nathan Harold420ceac2017-04-05 19:36:59 -0700112#define LOG_HEX(__desc16__, __buf__, __len__) \
113 do { \
114 logHex(__desc16__, __buf__, __len__); \
115 } while (0)
116#define LOG_IOV(__iov__, __iov_len__) \
117 do { \
118 logIov(__iov__, __iov_len__); \
119 } while (0)
Nathan Harold1a371532017-01-30 12:30:48 -0800120
121void logHex(const char* desc16, const char* buf, size_t len) {
122 char* printBuf = new char[len * 2 + 1 + 26]; // len->ascii, +newline, +prefix strlen
123 int offset = 0;
124 if (desc16) {
125 sprintf(printBuf, "{%-16s}", desc16);
126 offset += 18; // prefix string length
127 }
128 sprintf(printBuf + offset, "[%4.4u]: ", (len > 9999) ? 9999 : (unsigned)len);
129 offset += 8;
130
131 for (uint32_t j = 0; j < (uint32_t)len; j++) {
132 sprintf(&printBuf[j * 2 + offset], "%0.2x", buf[j]);
133 }
134 ALOGD("%s", printBuf);
135 delete[] printBuf;
136}
137
138void logIov(const iovec* iov, size_t iovLen) {
139 for (uint32_t i = 0; i < (uint32_t)iovLen; i++) {
140 const iovec* row = &iov[i];
141 logHex(0, reinterpret_cast<char*>(row->iov_base), row->iov_len);
142 }
143}
144
145#else
146#define LOG_HEX(__desc16__, __buf__, __len__)
147#define LOG_IOV(__iov__, __iov_len__)
148#endif
149
150class XfrmSocketImpl : public XfrmSocket {
151private:
152 static constexpr int NLMSG_DEFAULTSIZE = 8192;
153
154 union NetlinkResponse {
155 nlmsghdr hdr;
156 struct _err_ {
157 nlmsghdr hdr;
158 nlmsgerr err;
159 } err;
160
161 struct _buf_ {
162 nlmsghdr hdr;
163 char buf[NLMSG_DEFAULTSIZE];
164 } buf;
165 };
166
167public:
168 virtual bool open() {
169 mSock = openNetlinkSocket(NETLINK_XFRM);
170 if (mSock <= 0) {
171 ALOGW("Could not get a new socket, line=%d", __LINE__);
172 return false;
173 }
174
175 return true;
176 }
177
178 static int validateResponse(NetlinkResponse response, size_t len) {
179 if (len < sizeof(nlmsghdr)) {
180 ALOGW("Invalid response message received over netlink");
181 return -EBADMSG;
182 }
183
184 switch (response.hdr.nlmsg_type) {
185 case NLMSG_NOOP:
186 case NLMSG_DONE:
187 return 0;
188 case NLMSG_OVERRUN:
189 ALOGD("Netlink request overran kernel buffer");
190 return -EBADMSG;
191 case NLMSG_ERROR:
192 if (len < sizeof(NetlinkResponse::_err_)) {
193 ALOGD("Netlink message received malformed error response");
194 return -EBADMSG;
195 }
196 return response.err.err.error; // Netlink errors are negative errno.
197 case XFRM_MSG_NEWSA:
198 break;
199 }
200
201 if (response.hdr.nlmsg_type < XFRM_MSG_BASE /*== NLMSG_MIN_TYPE*/ ||
202 response.hdr.nlmsg_type > XFRM_MSG_MAX) {
203 ALOGD("Netlink message responded with an out-of-range message ID");
204 return -EBADMSG;
205 }
206
207 // TODO Add more message validation here
208 return 0;
209 }
210
211 virtual int sendMessage(uint16_t nlMsgType, uint16_t nlMsgFlags, uint16_t nlMsgSeqNum,
212 iovec* iov, int iovLen) const {
213 nlmsghdr nlMsg = {
214 .nlmsg_type = nlMsgType, .nlmsg_flags = nlMsgFlags, .nlmsg_seq = nlMsgSeqNum,
215 };
216
217 iov[0].iov_base = &nlMsg;
Nathan Harolde2dd4c72017-04-19 11:09:11 -0700218 iov[0].iov_len = NLMSG_HDRLEN;
Nathan Harold1a371532017-01-30 12:30:48 -0800219 for (int i = 0; i < iovLen; ++i) {
220 nlMsg.nlmsg_len += iov[i].iov_len;
221 }
222
223 ALOGD("Sending Netlink XFRM Message: %s", xfrmMsgTypeToString(nlMsgType));
224 if (VDBG)
225 LOG_IOV(iov, iovLen);
226
227 int ret;
228
229 if (writev(mSock, iov, iovLen) < 0) {
230 ALOGE("netlink socket writev failed (%s)", strerror(errno));
231 return -errno;
232 }
233
234 NetlinkResponse* response = new NetlinkResponse{};
235
236 if ((ret = recv(mSock, response, sizeof(*response), 0)) < 0) {
237 ALOGE("netlink response contains error (%s)", strerror(errno));
238 delete response;
239 return -errno;
240 }
241
242 LOG_HEX("netlink msg resp", reinterpret_cast<char*>(response), ret);
243
244 ret = validateResponse(*response, ret);
245 delete response;
246 if (ret < 0)
247 ALOGE("netlink response contains error (%s)", strerror(-ret));
248 return ret;
249 }
250};
251
252int convertToXfrmAddr(const std::string& strAddr, xfrm_address_t* xfrmAddr) {
253 if (strAddr.length() == 0) {
254 memset(xfrmAddr, 0, sizeof(*xfrmAddr));
255 return AF_UNSPEC;
256 }
257
258 if (inet_pton(AF_INET6, strAddr.c_str(), reinterpret_cast<void*>(xfrmAddr))) {
259 return AF_INET6;
260 } else if (inet_pton(AF_INET, strAddr.c_str(), reinterpret_cast<void*>(xfrmAddr))) {
261 return AF_INET;
262 } else {
263 return -EAFNOSUPPORT;
264 }
265}
266
267void fillXfrmNlaHdr(nlattr* hdr, uint16_t type, uint16_t len) {
268 hdr->nla_type = type;
269 hdr->nla_len = len;
270}
271
272void fillXfrmCurLifetimeDefaults(xfrm_lifetime_cur* cur) {
273 memset(reinterpret_cast<char*>(cur), 0, sizeof(*cur));
274}
275void fillXfrmLifetimeDefaults(xfrm_lifetime_cfg* cfg) {
276 cfg->soft_byte_limit = XFRM_INF;
277 cfg->hard_byte_limit = XFRM_INF;
278 cfg->soft_packet_limit = XFRM_INF;
279 cfg->hard_packet_limit = XFRM_INF;
280}
281
282/*
283 * Allocate SPIs within an (inclusive) range of min-max.
284 * returns 0 (INVALID_SPI) once the entire range has been parsed.
285 */
286class RandomSpi {
287public:
288 RandomSpi(int min, int max) : mMin(min) {
289 time_t t;
290 srand((unsigned int)time(&t));
291 // TODO: more random random
292 mNext = rand();
293 mSize = max - min + 1;
294 mCount = mSize;
295 }
296
297 uint32_t next() {
298 if (!mCount)
299 return 0;
300 mCount--;
301 return (mNext++ % mSize) + mMin;
302 }
303
304private:
305 uint32_t mNext;
306 uint32_t mSize;
307 uint32_t mMin;
308 uint32_t mCount;
309};
310
311} // namespace
312
313//
314// Begin XfrmController Impl
315//
316//
317XfrmController::XfrmController(void) {}
318
319int XfrmController::ipSecAllocateSpi(int32_t transformId, int32_t direction,
320 const std::string& localAddress,
321 const std::string& remoteAddress, int32_t inSpi,
322 int32_t* outSpi) {
Nathan Harold1a371532017-01-30 12:30:48 -0800323 ALOGD("XfrmController:%s, line=%d", __FUNCTION__, __LINE__);
324 ALOGD("transformId=%d", transformId);
325 ALOGD("direction=%d", direction);
326 ALOGD("localAddress=%s", localAddress.c_str());
327 ALOGD("remoteAddress=%s", remoteAddress.c_str());
328 ALOGD("inSpi=%0.8x", inSpi);
329
330 XfrmSaInfo saInfo{};
331 int ret;
332
333 if ((ret = fillXfrmSaId(direction, localAddress, remoteAddress, INVALID_SPI, &saInfo)) < 0) {
334 return ret;
335 }
336
337 XfrmSocketImpl sock;
338 if (!sock.open()) {
339 ALOGD("Sock open failed for XFRM, line=%d", __LINE__);
340 return -1; // TODO: return right error; for whatever reason the sock
341 // failed to open
342 }
343
344 int minSpi = RAND_SPI_MIN, maxSpi = RAND_SPI_MAX;
345
346 if (inSpi)
347 minSpi = maxSpi = inSpi;
348 ret = allocateSpi(saInfo, minSpi, maxSpi, reinterpret_cast<uint32_t*>(outSpi), sock);
349 if (ret < 0) {
350 ALOGD("Failed to Allocate an SPI, line=%d", __LINE__);
351 *outSpi = INVALID_SPI;
352 }
353
354 return ret;
355}
356
357int XfrmController::ipSecAddSecurityAssociation(
358 int32_t transformId, int32_t mode, int32_t direction, const std::string& localAddress,
Nathan Harold420ceac2017-04-05 19:36:59 -0700359 const std::string& remoteAddress, int64_t underlyingNetworkHandle, int32_t spi,
Nathan Harold1a371532017-01-30 12:30:48 -0800360 const std::string& authAlgo, const std::vector<uint8_t>& authKey, int32_t authTruncBits,
361 const std::string& cryptAlgo, const std::vector<uint8_t>& cryptKey, int32_t cryptTruncBits,
ludiec836052017-05-20 14:17:05 -0700362 int32_t encapType, int32_t encapLocalPort, int32_t encapRemotePort) {
Nathan Harold1a371532017-01-30 12:30:48 -0800363 android::RWLock::AutoWLock lock(mLock);
364
365 ALOGD("XfrmController::%s, line=%d", __FUNCTION__, __LINE__);
366 ALOGD("transformId=%d", transformId);
367 ALOGD("mode=%d", mode);
368 ALOGD("direction=%d", direction);
369 ALOGD("localAddress=%s", localAddress.c_str());
370 ALOGD("remoteAddress=%s", remoteAddress.c_str());
Nathan Harold420ceac2017-04-05 19:36:59 -0700371 ALOGD("underlyingNetworkHandle=%" PRIx64, underlyingNetworkHandle);
Nathan Harold1a371532017-01-30 12:30:48 -0800372 ALOGD("spi=%0.8x", spi);
373 ALOGD("authAlgo=%s", authAlgo.c_str());
374 ALOGD("authTruncBits=%d", authTruncBits);
375 ALOGD("cryptAlgo=%s", cryptAlgo.c_str());
376 ALOGD("cryptTruncBits=%d,", cryptTruncBits);
377 ALOGD("encapType=%d", encapType);
378 ALOGD("encapLocalPort=%d", encapLocalPort);
379 ALOGD("encapRemotePort=%d", encapRemotePort);
380
381 XfrmSaInfo saInfo{};
382 int ret;
383
384 if ((ret = fillXfrmSaId(direction, localAddress, remoteAddress, spi, &saInfo)) < 0) {
385 return ret;
386 }
387
388 saInfo.transformId = transformId;
389
390 // STOPSHIP : range check the key lengths to prevent puncturing and overflow
391 saInfo.auth = XfrmAlgo{
392 .name = authAlgo, .key = authKey, .truncLenBits = static_cast<uint16_t>(authTruncBits)};
393
394 saInfo.crypt = XfrmAlgo{
395 .name = cryptAlgo, .key = cryptKey, .truncLenBits = static_cast<uint16_t>(cryptTruncBits)};
396
397 saInfo.direction = static_cast<XfrmDirection>(direction);
398
399 switch (static_cast<XfrmMode>(mode)) {
400 case XfrmMode::TRANSPORT:
401 case XfrmMode::TUNNEL:
402 saInfo.mode = static_cast<XfrmMode>(mode);
403 break;
404 default:
405 return -EINVAL;
406 }
407
408 XfrmSocketImpl sock;
409 if (!sock.open()) {
410 ALOGD("Sock open failed for XFRM, line=%d", __LINE__);
411 return -1; // TODO: return right error; for whatever reason the sock
412 // failed to open
413 }
414
Nathan Harold420ceac2017-04-05 19:36:59 -0700415 switch (static_cast<XfrmEncapType>(encapType)) {
416 case XfrmEncapType::ESPINUDP:
417 case XfrmEncapType::ESPINUDP_NON_IKE:
418 if (saInfo.addrFamily != AF_INET) {
419 return -EAFNOSUPPORT;
420 }
421 switch (saInfo.direction) {
422 case XfrmDirection::IN:
423 saInfo.encap.srcPort = encapRemotePort;
424 saInfo.encap.dstPort = encapLocalPort;
425 break;
426 case XfrmDirection::OUT:
427 saInfo.encap.srcPort = encapLocalPort;
428 saInfo.encap.dstPort = encapRemotePort;
429 break;
430 default:
431 return -EINVAL;
432 }
433 // fall through
434 case XfrmEncapType::NONE:
435 saInfo.encap.type = static_cast<XfrmEncapType>(encapType);
436 break;
437 default:
438 return -EINVAL;
439 }
440
Nathan Harold1a371532017-01-30 12:30:48 -0800441 ret = createTransportModeSecurityAssociation(saInfo, sock);
442 if (ret < 0) {
443 ALOGD("Failed creating a Security Association, line=%d", __LINE__);
444 return ret; // something went wrong creating the SA
445 }
446
Nathan Harold1a371532017-01-30 12:30:48 -0800447 return 0;
448}
449
450int XfrmController::ipSecDeleteSecurityAssociation(int32_t transformId, int32_t direction,
451 const std::string& localAddress,
452 const std::string& remoteAddress, int32_t spi) {
Nathan Harold1a371532017-01-30 12:30:48 -0800453 ALOGD("XfrmController:%s, line=%d", __FUNCTION__, __LINE__);
454 ALOGD("transformId=%d", transformId);
455 ALOGD("direction=%d", direction);
456 ALOGD("localAddress=%s", localAddress.c_str());
457 ALOGD("remoteAddress=%s", remoteAddress.c_str());
458 ALOGD("spi=%0.8x", spi);
459
460 XfrmSaId saId;
461 int ret;
462
463 if ((ret = fillXfrmSaId(direction, localAddress, remoteAddress, spi, &saId)) < 0) {
464 return ret;
465 }
466
467 XfrmSocketImpl sock;
468 if (!sock.open()) {
469 ALOGD("Sock open failed for XFRM, line=%d", __LINE__);
470 return -1; // TODO: return right error; for whatever reason the sock
471 // failed to open
472 }
473
474 ret = deleteSecurityAssociation(saId, sock);
475 if (ret < 0) {
476 ALOGD("Failed to delete Security Association, line=%d", __LINE__);
477 return ret; // something went wrong deleting the SA
478 }
479
480 return ret;
481}
482
483int XfrmController::fillXfrmSaId(int32_t direction, const std::string& localAddress,
484 const std::string& remoteAddress, int32_t spi, XfrmSaId* xfrmId) {
485 xfrm_address_t localXfrmAddr{}, remoteXfrmAddr{};
486
487 int addrFamilyLocal, addrFamilyRemote;
488 addrFamilyRemote = convertToXfrmAddr(remoteAddress, &remoteXfrmAddr);
489 addrFamilyLocal = convertToXfrmAddr(localAddress, &localXfrmAddr);
490 if (addrFamilyRemote < 0 || addrFamilyLocal < 0) {
491 return -EINVAL;
492 }
493
494 if (addrFamilyRemote == AF_UNSPEC ||
495 (addrFamilyLocal != AF_UNSPEC && addrFamilyLocal != addrFamilyRemote)) {
496 ALOGD("Invalid or Mismatched Address Families, %d != %d, line=%d", addrFamilyLocal,
497 addrFamilyRemote, __LINE__);
498 return -EINVAL;
499 }
500
501 xfrmId->addrFamily = addrFamilyRemote;
502
503 xfrmId->spi = htonl(spi);
504
505 switch (static_cast<XfrmDirection>(direction)) {
506 case XfrmDirection::IN:
507 xfrmId->dstAddr = localXfrmAddr;
508 xfrmId->srcAddr = remoteXfrmAddr;
509 break;
510
511 case XfrmDirection::OUT:
512 xfrmId->dstAddr = remoteXfrmAddr;
513 xfrmId->srcAddr = localXfrmAddr;
514 break;
515
516 default:
517 ALOGD("Invalid XFRM direction, line=%d", __LINE__);
518 // Invalid direction for Transport mode transform: time to bail
519 return -EINVAL;
520 }
521 return 0;
522}
523
524int XfrmController::ipSecApplyTransportModeTransform(const android::base::unique_fd& socket,
525 int32_t transformId, int32_t direction,
526 const std::string& localAddress,
527 const std::string& remoteAddress,
528 int32_t spi) {
529 ALOGD("XfrmController::%s, line=%d", __FUNCTION__, __LINE__);
530 ALOGD("transformId=%d", transformId);
531 ALOGD("direction=%d", direction);
532 ALOGD("localAddress=%s", localAddress.c_str());
533 ALOGD("remoteAddress=%s", remoteAddress.c_str());
534 ALOGD("spi=%0.8x", spi);
535
536 struct sockaddr_storage saddr;
537
538 socklen_t len = sizeof(saddr);
539 int err;
540 int userSocket = socket.get();
541
542 if ((err = getsockname(userSocket, reinterpret_cast<struct sockaddr*>(&saddr), &len)) < 0) {
543 ALOGE("Failed to get socket info in %s", __FUNCTION__);
544 return -err;
545 }
546
547 XfrmSaInfo saInfo{};
548 saInfo.transformId = transformId;
549 saInfo.direction = static_cast<XfrmDirection>(direction);
550 saInfo.spi = spi;
551
552 if ((err = fillXfrmSaId(direction, localAddress, remoteAddress, spi, &saInfo)) < 0) {
553 ALOGE("Couldn't build SA ID %s", __FUNCTION__);
554 return -err;
555 }
556
557 if (saInfo.addrFamily != saddr.ss_family) {
558 ALOGE("Transform address family(%d) differs from socket address "
Nathan Harold420ceac2017-04-05 19:36:59 -0700559 "family(%d)!",
560 saInfo.addrFamily, saddr.ss_family);
Nathan Harold1a371532017-01-30 12:30:48 -0800561 return -EINVAL;
562 }
563
564 struct {
565 xfrm_userpolicy_info info;
566 xfrm_user_tmpl tmpl;
567 } policy{};
568
569 fillTransportModeUserSpInfo(saInfo, &policy.info);
570 fillUserTemplate(saInfo, &policy.tmpl);
571
572 LOG_HEX("XfrmUserPolicy", reinterpret_cast<char*>(&policy), sizeof(policy));
573
574 int sockOpt, sockLayer;
575 switch (saInfo.addrFamily) {
576 case AF_INET:
577 sockOpt = IP_XFRM_POLICY;
578 sockLayer = SOL_IP;
579 break;
580 case AF_INET6:
581 sockOpt = IPV6_XFRM_POLICY;
582 sockLayer = SOL_IPV6;
583 break;
584 default:
585 return -EAFNOSUPPORT;
586 }
587
588 err = setsockopt(userSocket, sockLayer, sockOpt, &policy, sizeof(policy));
589 if (err < 0) {
590 err = errno;
591 ALOGE("Error setting socket option for XFRM! (%s)", strerror(err));
592 }
593
594 return -err;
595}
596
597int XfrmController::ipSecRemoveTransportModeTransform(const android::base::unique_fd& socket) {
598 (void)socket;
599 return 0;
600}
601
602void XfrmController::fillTransportModeSelector(const XfrmSaInfo& record, xfrm_selector* selector) {
603 selector->family = record.addrFamily;
604 selector->proto = AF_UNSPEC; // TODO: do we need to match the protocol? it's
605 // possible via the socket
606 selector->ifindex = record.netId; // TODO : still need to sort this out
607}
608
609int XfrmController::createTransportModeSecurityAssociation(const XfrmSaInfo& record,
610 const XfrmSocket& sock) {
611 xfrm_usersa_info usersa{};
612 nlattr_algo_crypt crypt{};
613 nlattr_algo_auth auth{};
Nathan Harold420ceac2017-04-05 19:36:59 -0700614 nlattr_encap_tmpl encap{};
Nathan Harold1a371532017-01-30 12:30:48 -0800615
Nathan Harold420ceac2017-04-05 19:36:59 -0700616 enum {
617 NLMSG_HDR,
618 USERSA,
619 USERSA_PAD,
620 CRYPT,
621 CRYPT_PAD,
622 AUTH,
623 AUTH_PAD,
624 ENCAP,
625 ENCAP_PAD,
626 iovLen
627 };
Nathan Harold1a371532017-01-30 12:30:48 -0800628
629 iovec iov[] = {
630 {NULL, 0}, // reserved for the eventual addition of a NLMSG_HDR
631 {&usersa, 0}, // main usersa_info struct
632 {kPadBytes, 0}, // up to NLMSG_ALIGNTO pad bytes of padding
633 {&crypt, 0}, // adjust size if crypt algo is present
634 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
635 {&auth, 0}, // adjust size if auth algo is present
636 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
Nathan Harold420ceac2017-04-05 19:36:59 -0700637 {&encap, 0}, // adjust size if auth algo is present
638 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
Nathan Harold1a371532017-01-30 12:30:48 -0800639 };
640
641 int len;
642 len = iov[USERSA].iov_len = fillUserSaInfo(record, &usersa);
643 iov[USERSA_PAD].iov_len = NLMSG_ALIGN(len) - len;
644
645 len = iov[CRYPT].iov_len = fillNlAttrXfrmAlgoEnc(record.crypt, &crypt);
646 iov[CRYPT_PAD].iov_len = NLA_ALIGN(len) - len;
647
648 len = iov[AUTH].iov_len = fillNlAttrXfrmAlgoAuth(record.auth, &auth);
649 iov[AUTH_PAD].iov_len = NLA_ALIGN(len) - len;
650
Nathan Harold420ceac2017-04-05 19:36:59 -0700651 len = iov[ENCAP].iov_len = fillNlAttrXfrmEncapTmpl(record, &encap);
652 iov[ENCAP_PAD].iov_len = NLA_ALIGN(len) - len;
Nathan Harold1a371532017-01-30 12:30:48 -0800653 return sock.sendMessage(XFRM_MSG_UPDSA, NETLINK_REQUEST_FLAGS, 0, iov, iovLen);
654}
655
656int XfrmController::fillNlAttrXfrmAlgoEnc(const XfrmAlgo& inAlgo, nlattr_algo_crypt* algo) {
657 int len = NLA_HDRLEN + sizeof(xfrm_algo);
658 strncpy(algo->crypt.alg_name, inAlgo.name.c_str(), sizeof(algo->crypt.alg_name));
659 algo->crypt.alg_key_len = inAlgo.key.size() * 8; // bits
660 memcpy(algo->key, &inAlgo.key[0], inAlgo.key.size()); // FIXME :safety checks
661 len += inAlgo.key.size();
662 fillXfrmNlaHdr(&algo->hdr, XFRMA_ALG_CRYPT, len);
663 return len;
664}
665
666int XfrmController::fillNlAttrXfrmAlgoAuth(const XfrmAlgo& inAlgo, nlattr_algo_auth* algo) {
667 int len = NLA_HDRLEN + sizeof(xfrm_algo_auth);
668 strncpy(algo->auth.alg_name, inAlgo.name.c_str(), sizeof(algo->auth.alg_name));
669 algo->auth.alg_key_len = inAlgo.key.size() * 8; // bits
670
671 // This is the extra field for ALG_AUTH_TRUNC
672 algo->auth.alg_trunc_len = inAlgo.truncLenBits;
673
674 memcpy(algo->key, &inAlgo.key[0], inAlgo.key.size()); // FIXME :safety checks
675 len += inAlgo.key.size();
676
677 fillXfrmNlaHdr(&algo->hdr, XFRMA_ALG_AUTH_TRUNC, len);
678 return len;
679}
680
Nathan Harold420ceac2017-04-05 19:36:59 -0700681int XfrmController::fillNlAttrXfrmEncapTmpl(const XfrmSaInfo& record, nlattr_encap_tmpl* tmpl) {
682 if (record.encap.type == XfrmEncapType::NONE) {
683 return 0;
684 }
685
686 int len = NLA_HDRLEN + sizeof(xfrm_encap_tmpl);
687 tmpl->tmpl.encap_type = static_cast<uint16_t>(record.encap.type);
688 tmpl->tmpl.encap_sport = htons(record.encap.srcPort);
689 tmpl->tmpl.encap_dport = htons(record.encap.dstPort);
690 fillXfrmNlaHdr(&tmpl->hdr, XFRMA_ENCAP, len);
691 return len;
692}
693
Nathan Harold1a371532017-01-30 12:30:48 -0800694int XfrmController::fillUserSaInfo(const XfrmSaInfo& record, xfrm_usersa_info* usersa) {
695 fillTransportModeSelector(record, &usersa->sel);
696
697 usersa->id.proto = IPPROTO_ESP;
698 usersa->id.spi = record.spi;
699 usersa->id.daddr = record.dstAddr;
700
701 usersa->saddr = record.srcAddr;
702
703 fillXfrmLifetimeDefaults(&usersa->lft);
704 fillXfrmCurLifetimeDefaults(&usersa->curlft);
705 memset(&usersa->stats, 0, sizeof(usersa->stats)); // leave stats zeroed out
706 usersa->reqid = record.transformId;
707 usersa->family = record.addrFamily;
708 usersa->mode = static_cast<uint8_t>(record.mode);
709 usersa->replay_window = REPLAY_WINDOW_SIZE;
710 usersa->flags = 0; // TODO: should we actually set flags, XFRM_SA_XFLAG_DONT_ENCAP_DSCP?
711 return sizeof(*usersa);
712}
713
714int XfrmController::fillUserSaId(const XfrmSaId& record, xfrm_usersa_id* said) {
715 said->daddr = record.dstAddr;
716 said->spi = record.spi;
717 said->family = record.addrFamily;
718 said->proto = IPPROTO_ESP;
719
720 return sizeof(*said);
721}
722
723int XfrmController::deleteSecurityAssociation(const XfrmSaId& record, const XfrmSocket& sock) {
724 xfrm_usersa_id said{};
725
726 enum { NLMSG_HDR, USERSAID, USERSAID_PAD, iovLen };
727
728 iovec iov[] = {
729 {NULL, 0}, // reserved for the eventual addition of a NLMSG_HDR
730 {&said, 0}, // main usersa_info struct
731 {kPadBytes, 0}, // up to NLMSG_ALIGNTO pad bytes of padding
732 };
733
734 int len;
735 len = iov[USERSAID].iov_len = fillUserSaId(record, &said);
736 iov[USERSAID_PAD].iov_len = NLMSG_ALIGN(len) - len;
737
738 return sock.sendMessage(XFRM_MSG_DELSA, NETLINK_REQUEST_FLAGS, 0, iov, iovLen);
739}
740
741int XfrmController::allocateSpi(const XfrmSaInfo& record, uint32_t minSpi, uint32_t maxSpi,
742 uint32_t* outSpi, const XfrmSocket& sock) {
743 xfrm_userspi_info spiInfo{};
744
745 enum { NLMSG_HDR, USERSAID, USERSAID_PAD, iovLen };
746
747 iovec iov[] = {
748 {NULL, 0}, // reserved for the eventual addition of a NLMSG_HDR
749 {&spiInfo, 0}, // main userspi_info struct
750 {kPadBytes, 0}, // up to NLMSG_ALIGNTO pad bytes of padding
751 };
752
753 int len;
754 if (fillUserSaInfo(record, &spiInfo.info) == 0) {
755 ALOGE("Failed to fill transport SA Info");
756 }
757
758 len = iov[USERSAID].iov_len = sizeof(spiInfo);
759 iov[USERSAID_PAD].iov_len = NLMSG_ALIGN(len) - len;
760
761 RandomSpi spiGen = RandomSpi(minSpi, maxSpi);
762 int spi, ret;
763 while ((spi = spiGen.next()) != INVALID_SPI) {
764 spiInfo.min = spi;
765 spiInfo.max = spi;
766 ret = sock.sendMessage(XFRM_MSG_ALLOCSPI, NETLINK_REQUEST_FLAGS, 0, iov, iovLen);
767
768 /* If the SPI is in use, we'll get ENOENT */
769 if (ret == -ENOENT)
770 continue;
771
772 if (ret == 0) {
773 *outSpi = spi;
Nathan Harold420ceac2017-04-05 19:36:59 -0700774 ALOGD("Allocated an SPI: %x", *outSpi);
Nathan Harold1a371532017-01-30 12:30:48 -0800775 } else {
776 *outSpi = INVALID_SPI;
777 ALOGE("SPI Allocation Failed with error %d", ret);
778 }
779
780 return ret;
781 }
782
783 // Should always be -ENOENT if we get here
784 return ret;
785}
786
787int XfrmController::fillTransportModeUserSpInfo(const XfrmSaInfo& record,
788 xfrm_userpolicy_info* usersp) {
789 fillTransportModeSelector(record, &usersp->sel);
790 fillXfrmLifetimeDefaults(&usersp->lft);
791 fillXfrmCurLifetimeDefaults(&usersp->curlft);
Nathan Harold420ceac2017-04-05 19:36:59 -0700792 /* if (index) index & 0x3 == dir -- must be true
793 * xfrm_user.c:verify_newpolicy_info() */
Nathan Harold1a371532017-01-30 12:30:48 -0800794 usersp->index = 0;
795 usersp->dir = static_cast<uint8_t>(record.direction);
796 usersp->action = XFRM_POLICY_ALLOW;
797 usersp->flags = XFRM_POLICY_LOCALOK;
798 usersp->share = XFRM_SHARE_UNIQUE;
799 return sizeof(*usersp);
800}
801
802int XfrmController::fillUserTemplate(const XfrmSaInfo& record, xfrm_user_tmpl* tmpl) {
803 tmpl->id.daddr = record.dstAddr;
804 tmpl->id.spi = record.spi;
805 tmpl->id.proto = IPPROTO_ESP;
806
807 tmpl->family = record.addrFamily;
808 tmpl->saddr = record.srcAddr;
809 tmpl->reqid = record.transformId;
810 tmpl->mode = static_cast<uint8_t>(record.mode);
811 tmpl->share = XFRM_SHARE_UNIQUE;
812 tmpl->optional = 0; // if this is true, then a failed state lookup will be considered OK:
813 // http://lxr.free-electrons.com/source/net/xfrm/xfrm_policy.c#L1492
814 tmpl->aalgos = ALGO_MASK_AUTH_ALL; // TODO: if there's a bitmask somewhere of
815 // algos, we should find it and apply it.
816 // I can't find one.
817 tmpl->ealgos = ALGO_MASK_CRYPT_ALL; // TODO: if there's a bitmask somewhere...
818 return 0;
819}
820
821} // namespace net
822} // namespace android