blob: 344b268ae35d4017e6f3819150e525f8c371de9f [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,
362 int32_t encapType, int32_t encapLocalPort, int32_t encapRemotePort, int32_t* allocatedSpi) {
363 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
447 *allocatedSpi = spi;
448 return 0;
449}
450
451int XfrmController::ipSecDeleteSecurityAssociation(int32_t transformId, int32_t direction,
452 const std::string& localAddress,
453 const std::string& remoteAddress, int32_t spi) {
Nathan Harold1a371532017-01-30 12:30:48 -0800454 ALOGD("XfrmController:%s, line=%d", __FUNCTION__, __LINE__);
455 ALOGD("transformId=%d", transformId);
456 ALOGD("direction=%d", direction);
457 ALOGD("localAddress=%s", localAddress.c_str());
458 ALOGD("remoteAddress=%s", remoteAddress.c_str());
459 ALOGD("spi=%0.8x", spi);
460
461 XfrmSaId saId;
462 int ret;
463
464 if ((ret = fillXfrmSaId(direction, localAddress, remoteAddress, spi, &saId)) < 0) {
465 return ret;
466 }
467
468 XfrmSocketImpl sock;
469 if (!sock.open()) {
470 ALOGD("Sock open failed for XFRM, line=%d", __LINE__);
471 return -1; // TODO: return right error; for whatever reason the sock
472 // failed to open
473 }
474
475 ret = deleteSecurityAssociation(saId, sock);
476 if (ret < 0) {
477 ALOGD("Failed to delete Security Association, line=%d", __LINE__);
478 return ret; // something went wrong deleting the SA
479 }
480
481 return ret;
482}
483
484int XfrmController::fillXfrmSaId(int32_t direction, const std::string& localAddress,
485 const std::string& remoteAddress, int32_t spi, XfrmSaId* xfrmId) {
486 xfrm_address_t localXfrmAddr{}, remoteXfrmAddr{};
487
488 int addrFamilyLocal, addrFamilyRemote;
489 addrFamilyRemote = convertToXfrmAddr(remoteAddress, &remoteXfrmAddr);
490 addrFamilyLocal = convertToXfrmAddr(localAddress, &localXfrmAddr);
491 if (addrFamilyRemote < 0 || addrFamilyLocal < 0) {
492 return -EINVAL;
493 }
494
495 if (addrFamilyRemote == AF_UNSPEC ||
496 (addrFamilyLocal != AF_UNSPEC && addrFamilyLocal != addrFamilyRemote)) {
497 ALOGD("Invalid or Mismatched Address Families, %d != %d, line=%d", addrFamilyLocal,
498 addrFamilyRemote, __LINE__);
499 return -EINVAL;
500 }
501
502 xfrmId->addrFamily = addrFamilyRemote;
503
504 xfrmId->spi = htonl(spi);
505
506 switch (static_cast<XfrmDirection>(direction)) {
507 case XfrmDirection::IN:
508 xfrmId->dstAddr = localXfrmAddr;
509 xfrmId->srcAddr = remoteXfrmAddr;
510 break;
511
512 case XfrmDirection::OUT:
513 xfrmId->dstAddr = remoteXfrmAddr;
514 xfrmId->srcAddr = localXfrmAddr;
515 break;
516
517 default:
518 ALOGD("Invalid XFRM direction, line=%d", __LINE__);
519 // Invalid direction for Transport mode transform: time to bail
520 return -EINVAL;
521 }
522 return 0;
523}
524
525int XfrmController::ipSecApplyTransportModeTransform(const android::base::unique_fd& socket,
526 int32_t transformId, int32_t direction,
527 const std::string& localAddress,
528 const std::string& remoteAddress,
529 int32_t spi) {
530 ALOGD("XfrmController::%s, line=%d", __FUNCTION__, __LINE__);
531 ALOGD("transformId=%d", transformId);
532 ALOGD("direction=%d", direction);
533 ALOGD("localAddress=%s", localAddress.c_str());
534 ALOGD("remoteAddress=%s", remoteAddress.c_str());
535 ALOGD("spi=%0.8x", spi);
536
537 struct sockaddr_storage saddr;
538
539 socklen_t len = sizeof(saddr);
540 int err;
541 int userSocket = socket.get();
542
543 if ((err = getsockname(userSocket, reinterpret_cast<struct sockaddr*>(&saddr), &len)) < 0) {
544 ALOGE("Failed to get socket info in %s", __FUNCTION__);
545 return -err;
546 }
547
548 XfrmSaInfo saInfo{};
549 saInfo.transformId = transformId;
550 saInfo.direction = static_cast<XfrmDirection>(direction);
551 saInfo.spi = spi;
552
553 if ((err = fillXfrmSaId(direction, localAddress, remoteAddress, spi, &saInfo)) < 0) {
554 ALOGE("Couldn't build SA ID %s", __FUNCTION__);
555 return -err;
556 }
557
558 if (saInfo.addrFamily != saddr.ss_family) {
559 ALOGE("Transform address family(%d) differs from socket address "
Nathan Harold420ceac2017-04-05 19:36:59 -0700560 "family(%d)!",
561 saInfo.addrFamily, saddr.ss_family);
Nathan Harold1a371532017-01-30 12:30:48 -0800562 return -EINVAL;
563 }
564
565 struct {
566 xfrm_userpolicy_info info;
567 xfrm_user_tmpl tmpl;
568 } policy{};
569
570 fillTransportModeUserSpInfo(saInfo, &policy.info);
571 fillUserTemplate(saInfo, &policy.tmpl);
572
573 LOG_HEX("XfrmUserPolicy", reinterpret_cast<char*>(&policy), sizeof(policy));
574
575 int sockOpt, sockLayer;
576 switch (saInfo.addrFamily) {
577 case AF_INET:
578 sockOpt = IP_XFRM_POLICY;
579 sockLayer = SOL_IP;
580 break;
581 case AF_INET6:
582 sockOpt = IPV6_XFRM_POLICY;
583 sockLayer = SOL_IPV6;
584 break;
585 default:
586 return -EAFNOSUPPORT;
587 }
588
589 err = setsockopt(userSocket, sockLayer, sockOpt, &policy, sizeof(policy));
590 if (err < 0) {
591 err = errno;
592 ALOGE("Error setting socket option for XFRM! (%s)", strerror(err));
593 }
594
595 return -err;
596}
597
598int XfrmController::ipSecRemoveTransportModeTransform(const android::base::unique_fd& socket) {
599 (void)socket;
600 return 0;
601}
602
603void XfrmController::fillTransportModeSelector(const XfrmSaInfo& record, xfrm_selector* selector) {
604 selector->family = record.addrFamily;
605 selector->proto = AF_UNSPEC; // TODO: do we need to match the protocol? it's
606 // possible via the socket
607 selector->ifindex = record.netId; // TODO : still need to sort this out
608}
609
610int XfrmController::createTransportModeSecurityAssociation(const XfrmSaInfo& record,
611 const XfrmSocket& sock) {
612 xfrm_usersa_info usersa{};
613 nlattr_algo_crypt crypt{};
614 nlattr_algo_auth auth{};
Nathan Harold420ceac2017-04-05 19:36:59 -0700615 nlattr_encap_tmpl encap{};
Nathan Harold1a371532017-01-30 12:30:48 -0800616
Nathan Harold420ceac2017-04-05 19:36:59 -0700617 enum {
618 NLMSG_HDR,
619 USERSA,
620 USERSA_PAD,
621 CRYPT,
622 CRYPT_PAD,
623 AUTH,
624 AUTH_PAD,
625 ENCAP,
626 ENCAP_PAD,
627 iovLen
628 };
Nathan Harold1a371532017-01-30 12:30:48 -0800629
630 iovec iov[] = {
631 {NULL, 0}, // reserved for the eventual addition of a NLMSG_HDR
632 {&usersa, 0}, // main usersa_info struct
633 {kPadBytes, 0}, // up to NLMSG_ALIGNTO pad bytes of padding
634 {&crypt, 0}, // adjust size if crypt algo is present
635 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
636 {&auth, 0}, // adjust size if auth algo is present
637 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
Nathan Harold420ceac2017-04-05 19:36:59 -0700638 {&encap, 0}, // adjust size if auth algo is present
639 {kPadBytes, 0}, // up to NLATTR_ALIGNTO pad bytes
Nathan Harold1a371532017-01-30 12:30:48 -0800640 };
641
642 int len;
643 len = iov[USERSA].iov_len = fillUserSaInfo(record, &usersa);
644 iov[USERSA_PAD].iov_len = NLMSG_ALIGN(len) - len;
645
646 len = iov[CRYPT].iov_len = fillNlAttrXfrmAlgoEnc(record.crypt, &crypt);
647 iov[CRYPT_PAD].iov_len = NLA_ALIGN(len) - len;
648
649 len = iov[AUTH].iov_len = fillNlAttrXfrmAlgoAuth(record.auth, &auth);
650 iov[AUTH_PAD].iov_len = NLA_ALIGN(len) - len;
651
Nathan Harold420ceac2017-04-05 19:36:59 -0700652 len = iov[ENCAP].iov_len = fillNlAttrXfrmEncapTmpl(record, &encap);
653 iov[ENCAP_PAD].iov_len = NLA_ALIGN(len) - len;
Nathan Harold1a371532017-01-30 12:30:48 -0800654 return sock.sendMessage(XFRM_MSG_UPDSA, NETLINK_REQUEST_FLAGS, 0, iov, iovLen);
655}
656
657int XfrmController::fillNlAttrXfrmAlgoEnc(const XfrmAlgo& inAlgo, nlattr_algo_crypt* algo) {
658 int len = NLA_HDRLEN + sizeof(xfrm_algo);
659 strncpy(algo->crypt.alg_name, inAlgo.name.c_str(), sizeof(algo->crypt.alg_name));
660 algo->crypt.alg_key_len = inAlgo.key.size() * 8; // bits
661 memcpy(algo->key, &inAlgo.key[0], inAlgo.key.size()); // FIXME :safety checks
662 len += inAlgo.key.size();
663 fillXfrmNlaHdr(&algo->hdr, XFRMA_ALG_CRYPT, len);
664 return len;
665}
666
667int XfrmController::fillNlAttrXfrmAlgoAuth(const XfrmAlgo& inAlgo, nlattr_algo_auth* algo) {
668 int len = NLA_HDRLEN + sizeof(xfrm_algo_auth);
669 strncpy(algo->auth.alg_name, inAlgo.name.c_str(), sizeof(algo->auth.alg_name));
670 algo->auth.alg_key_len = inAlgo.key.size() * 8; // bits
671
672 // This is the extra field for ALG_AUTH_TRUNC
673 algo->auth.alg_trunc_len = inAlgo.truncLenBits;
674
675 memcpy(algo->key, &inAlgo.key[0], inAlgo.key.size()); // FIXME :safety checks
676 len += inAlgo.key.size();
677
678 fillXfrmNlaHdr(&algo->hdr, XFRMA_ALG_AUTH_TRUNC, len);
679 return len;
680}
681
Nathan Harold420ceac2017-04-05 19:36:59 -0700682int XfrmController::fillNlAttrXfrmEncapTmpl(const XfrmSaInfo& record, nlattr_encap_tmpl* tmpl) {
683 if (record.encap.type == XfrmEncapType::NONE) {
684 return 0;
685 }
686
687 int len = NLA_HDRLEN + sizeof(xfrm_encap_tmpl);
688 tmpl->tmpl.encap_type = static_cast<uint16_t>(record.encap.type);
689 tmpl->tmpl.encap_sport = htons(record.encap.srcPort);
690 tmpl->tmpl.encap_dport = htons(record.encap.dstPort);
691 fillXfrmNlaHdr(&tmpl->hdr, XFRMA_ENCAP, len);
692 return len;
693}
694
Nathan Harold1a371532017-01-30 12:30:48 -0800695int XfrmController::fillUserSaInfo(const XfrmSaInfo& record, xfrm_usersa_info* usersa) {
696 fillTransportModeSelector(record, &usersa->sel);
697
698 usersa->id.proto = IPPROTO_ESP;
699 usersa->id.spi = record.spi;
700 usersa->id.daddr = record.dstAddr;
701
702 usersa->saddr = record.srcAddr;
703
704 fillXfrmLifetimeDefaults(&usersa->lft);
705 fillXfrmCurLifetimeDefaults(&usersa->curlft);
706 memset(&usersa->stats, 0, sizeof(usersa->stats)); // leave stats zeroed out
707 usersa->reqid = record.transformId;
708 usersa->family = record.addrFamily;
709 usersa->mode = static_cast<uint8_t>(record.mode);
710 usersa->replay_window = REPLAY_WINDOW_SIZE;
711 usersa->flags = 0; // TODO: should we actually set flags, XFRM_SA_XFLAG_DONT_ENCAP_DSCP?
712 return sizeof(*usersa);
713}
714
715int XfrmController::fillUserSaId(const XfrmSaId& record, xfrm_usersa_id* said) {
716 said->daddr = record.dstAddr;
717 said->spi = record.spi;
718 said->family = record.addrFamily;
719 said->proto = IPPROTO_ESP;
720
721 return sizeof(*said);
722}
723
724int XfrmController::deleteSecurityAssociation(const XfrmSaId& record, const XfrmSocket& sock) {
725 xfrm_usersa_id said{};
726
727 enum { NLMSG_HDR, USERSAID, USERSAID_PAD, iovLen };
728
729 iovec iov[] = {
730 {NULL, 0}, // reserved for the eventual addition of a NLMSG_HDR
731 {&said, 0}, // main usersa_info struct
732 {kPadBytes, 0}, // up to NLMSG_ALIGNTO pad bytes of padding
733 };
734
735 int len;
736 len = iov[USERSAID].iov_len = fillUserSaId(record, &said);
737 iov[USERSAID_PAD].iov_len = NLMSG_ALIGN(len) - len;
738
739 return sock.sendMessage(XFRM_MSG_DELSA, NETLINK_REQUEST_FLAGS, 0, iov, iovLen);
740}
741
742int XfrmController::allocateSpi(const XfrmSaInfo& record, uint32_t minSpi, uint32_t maxSpi,
743 uint32_t* outSpi, const XfrmSocket& sock) {
744 xfrm_userspi_info spiInfo{};
745
746 enum { NLMSG_HDR, USERSAID, USERSAID_PAD, iovLen };
747
748 iovec iov[] = {
749 {NULL, 0}, // reserved for the eventual addition of a NLMSG_HDR
750 {&spiInfo, 0}, // main userspi_info struct
751 {kPadBytes, 0}, // up to NLMSG_ALIGNTO pad bytes of padding
752 };
753
754 int len;
755 if (fillUserSaInfo(record, &spiInfo.info) == 0) {
756 ALOGE("Failed to fill transport SA Info");
757 }
758
759 len = iov[USERSAID].iov_len = sizeof(spiInfo);
760 iov[USERSAID_PAD].iov_len = NLMSG_ALIGN(len) - len;
761
762 RandomSpi spiGen = RandomSpi(minSpi, maxSpi);
763 int spi, ret;
764 while ((spi = spiGen.next()) != INVALID_SPI) {
765 spiInfo.min = spi;
766 spiInfo.max = spi;
767 ret = sock.sendMessage(XFRM_MSG_ALLOCSPI, NETLINK_REQUEST_FLAGS, 0, iov, iovLen);
768
769 /* If the SPI is in use, we'll get ENOENT */
770 if (ret == -ENOENT)
771 continue;
772
773 if (ret == 0) {
774 *outSpi = spi;
Nathan Harold420ceac2017-04-05 19:36:59 -0700775 ALOGD("Allocated an SPI: %x", *outSpi);
Nathan Harold1a371532017-01-30 12:30:48 -0800776 } else {
777 *outSpi = INVALID_SPI;
778 ALOGE("SPI Allocation Failed with error %d", ret);
779 }
780
781 return ret;
782 }
783
784 // Should always be -ENOENT if we get here
785 return ret;
786}
787
788int XfrmController::fillTransportModeUserSpInfo(const XfrmSaInfo& record,
789 xfrm_userpolicy_info* usersp) {
790 fillTransportModeSelector(record, &usersp->sel);
791 fillXfrmLifetimeDefaults(&usersp->lft);
792 fillXfrmCurLifetimeDefaults(&usersp->curlft);
Nathan Harold420ceac2017-04-05 19:36:59 -0700793 /* if (index) index & 0x3 == dir -- must be true
794 * xfrm_user.c:verify_newpolicy_info() */
Nathan Harold1a371532017-01-30 12:30:48 -0800795 usersp->index = 0;
796 usersp->dir = static_cast<uint8_t>(record.direction);
797 usersp->action = XFRM_POLICY_ALLOW;
798 usersp->flags = XFRM_POLICY_LOCALOK;
799 usersp->share = XFRM_SHARE_UNIQUE;
800 return sizeof(*usersp);
801}
802
803int XfrmController::fillUserTemplate(const XfrmSaInfo& record, xfrm_user_tmpl* tmpl) {
804 tmpl->id.daddr = record.dstAddr;
805 tmpl->id.spi = record.spi;
806 tmpl->id.proto = IPPROTO_ESP;
807
808 tmpl->family = record.addrFamily;
809 tmpl->saddr = record.srcAddr;
810 tmpl->reqid = record.transformId;
811 tmpl->mode = static_cast<uint8_t>(record.mode);
812 tmpl->share = XFRM_SHARE_UNIQUE;
813 tmpl->optional = 0; // if this is true, then a failed state lookup will be considered OK:
814 // http://lxr.free-electrons.com/source/net/xfrm/xfrm_policy.c#L1492
815 tmpl->aalgos = ALGO_MASK_AUTH_ALL; // TODO: if there's a bitmask somewhere of
816 // algos, we should find it and apply it.
817 // I can't find one.
818 tmpl->ealgos = ALGO_MASK_CRYPT_ALL; // TODO: if there's a bitmask somewhere...
819 return 0;
820}
821
822} // namespace net
823} // namespace android