blob: cd9db54fa6f4ca4d6422446e0b0a121d5c59ed85 [file] [log] [blame]
San Mehat168415b2009-05-06 11:14:21 -07001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
San Mehat168415b2009-05-06 11:14:21 -070016
17#define LOG_TAG "NetlinkEvent"
San Mehat168415b2009-05-06 11:14:21 -070018
Lorenzo Colitti381f70f2013-08-02 05:58:37 +090019#include <arpa/inet.h>
Lorenzo Colittie439ffc2017-10-03 18:44:11 +090020#include <limits.h>
21#include <linux/genetlink.h>
Mike J. Chenec16b9d2011-06-23 14:55:28 -070022#include <linux/if.h>
Lorenzo Colitti9b342932014-06-19 13:16:04 +090023#include <linux/if_addr.h>
24#include <linux/if_link.h>
JP Abgralle6f80142011-07-14 16:46:32 -070025#include <linux/netfilter/nfnetlink.h>
Jeff Sharkey9a20e672014-10-30 14:51:59 -070026#include <linux/netfilter/nfnetlink_log.h>
Mark Salyzyn66ce3e02016-09-28 10:07:20 -070027#include <linux/netlink.h>
28#include <linux/rtnetlink.h>
29#include <net/if.h>
Mark Salyzyn66ce3e02016-09-28 10:07:20 -070030#include <netinet/icmp6.h>
Lorenzo Colittie439ffc2017-10-03 18:44:11 +090031#include <netinet/in.h>
Mark Salyzyn66ce3e02016-09-28 10:07:20 -070032#include <stdlib.h>
33#include <string.h>
Maciej Żenczykowski28b94af2021-10-25 15:24:18 -070034#include <sys/personality.h>
Mark Salyzyn66ce3e02016-09-28 10:07:20 -070035#include <sys/socket.h>
36#include <sys/types.h>
Maciej Żenczykowski28b94af2021-10-25 15:24:18 -070037#include <sys/utsname.h>
38
39#include <android-base/parseint.h>
Patrick Rohreb13daf2023-05-18 14:36:02 -070040#include <bpf/KernelUtils.h>
Maciej Żenczykowski28b94af2021-10-25 15:24:18 -070041#include <log/log.h>
42#include <sysutils/NetlinkEvent.h>
43
44using android::base::ParseInt;
Patrick Rohreb13daf2023-05-18 14:36:02 -070045using android::bpf::isKernel64Bit;
Jeff Sharkey9a20e672014-10-30 14:51:59 -070046
JP Abgralle6f80142011-07-14 16:46:32 -070047/* From kernel's net/netfilter/xt_quota2.c */
Jeff Sharkey9a20e672014-10-30 14:51:59 -070048const int LOCAL_QLOG_NL_EVENT = 112;
49const int LOCAL_NFLOG_PACKET = NFNL_SUBSYS_ULOG << 8 | NFULNL_MSG_PACKET;
JP Abgralle6f80142011-07-14 16:46:32 -070050
Maciej Żenczykowski28b94af2021-10-25 15:24:18 -070051/******************************************************************************
52 * WARNING: HERE BE DRAGONS! *
53 * *
54 * This is here to provide for compatibility with both 32 and 64-bit kernels *
55 * from 32-bit userspace. *
56 * *
57 * The kernel definition of this struct uses types (like long) that are not *
58 * the same across 32-bit and 64-bit builds, and there is no compatibility *
59 * layer to fix it up before it reaches userspace. *
60 * As such we need to detect the bit-ness of the kernel and deal with it. *
61 * *
62 ******************************************************************************/
63
64/*
65 * This is the verbatim kernel declaration from net/netfilter/xt_quota2.c,
66 * it is *NOT* of a well defined layout and is included here for compile
67 * time assertions only.
68 *
69 * It got there from deprecated ipt_ULOG.h to parse QLOG_NL_EVENT.
70 */
Christopher Ferris71ac5c82019-12-09 15:10:06 -080071#define ULOG_MAC_LEN 80
72#define ULOG_PREFIX_LEN 32
73typedef struct ulog_packet_msg {
74 unsigned long mark;
75 long timestamp_sec;
76 long timestamp_usec;
77 unsigned int hook;
78 char indev_name[IFNAMSIZ];
79 char outdev_name[IFNAMSIZ];
80 size_t data_len;
81 char prefix[ULOG_PREFIX_LEN];
82 unsigned char mac_len;
83 unsigned char mac[ULOG_MAC_LEN];
84 unsigned char payload[0];
85} ulog_packet_msg_t;
86
Maciej Żenczykowski28b94af2021-10-25 15:24:18 -070087// On Linux int is always 32 bits, while sizeof(long) == sizeof(void*),
88// thus long on a 32-bit Linux kernel is 32-bits, like int always is
89typedef int long32;
90typedef unsigned int ulong32;
91static_assert(sizeof(long32) == 4);
92static_assert(sizeof(ulong32) == 4);
Jeff Sharkey9a20e672014-10-30 14:51:59 -070093
Maciej Żenczykowski28b94af2021-10-25 15:24:18 -070094// Here's the same structure definition with the assumption the kernel
95// is compiled for 32-bits.
96typedef struct {
97 ulong32 mark;
98 long32 timestamp_sec;
99 long32 timestamp_usec;
100 unsigned int hook;
101 char indev_name[IFNAMSIZ];
102 char outdev_name[IFNAMSIZ];
103 ulong32 data_len;
104 char prefix[ULOG_PREFIX_LEN];
105 unsigned char mac_len;
106 unsigned char mac[ULOG_MAC_LEN];
107 unsigned char payload[0];
108} ulog_packet_msg32_t;
109
110// long on a 64-bit kernel is 64-bits with 64-bit alignment,
111// while long long is 64-bit but may have 32-bit aligment.
112typedef long long __attribute__((__aligned__(8))) long64;
113typedef unsigned long long __attribute__((__aligned__(8))) ulong64;
114static_assert(sizeof(long64) == 8);
115static_assert(sizeof(ulong64) == 8);
116
117// Here's the same structure definition with the assumption the kernel
118// is compiled for 64-bits.
119typedef struct {
120 ulong64 mark;
121 long64 timestamp_sec;
122 long64 timestamp_usec;
123 unsigned int hook;
124 char indev_name[IFNAMSIZ];
125 char outdev_name[IFNAMSIZ];
126 ulong64 data_len;
127 char prefix[ULOG_PREFIX_LEN];
128 unsigned char mac_len;
129 unsigned char mac[ULOG_MAC_LEN];
130 unsigned char payload[0];
131} ulog_packet_msg64_t;
132
133// One expects the 32-bit version to be smaller than the 64-bit version.
134static_assert(sizeof(ulog_packet_msg32_t) < sizeof(ulog_packet_msg64_t));
135// And either way the 'native' version should match either the 32 or 64 bit one.
136static_assert(sizeof(ulog_packet_msg_t) == sizeof(ulog_packet_msg32_t) ||
137 sizeof(ulog_packet_msg_t) == sizeof(ulog_packet_msg64_t));
138
139// In practice these sizes are always simply (for both x86 and arm):
140static_assert(sizeof(ulog_packet_msg32_t) == 168);
141static_assert(sizeof(ulog_packet_msg64_t) == 192);
142
Maciej Żenczykowski28b94af2021-10-25 15:24:18 -0700143/******************************************************************************/
Lorenzo Colittid0e49382019-04-10 23:04:41 +0900144
San Mehat168415b2009-05-06 11:14:21 -0700145NetlinkEvent::NetlinkEvent() {
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700146 mAction = Action::kUnknown;
San Mehatebfe3db2009-10-10 17:35:13 -0700147 memset(mParams, 0, sizeof(mParams));
Yi Kong48885252018-07-24 16:34:27 -0700148 mPath = nullptr;
149 mSubsystem = nullptr;
San Mehat168415b2009-05-06 11:14:21 -0700150}
151
152NetlinkEvent::~NetlinkEvent() {
153 int i;
154 if (mPath)
155 free(mPath);
156 if (mSubsystem)
157 free(mSubsystem);
158 for (i = 0; i < NL_PARAMS_MAX; i++) {
159 if (!mParams[i])
160 break;
161 free(mParams[i]);
162 }
163}
164
San Mehatd6744132009-12-24 07:17:09 -0800165void NetlinkEvent::dump() {
166 int i;
167
168 for (i = 0; i < NL_PARAMS_MAX; i++) {
169 if (!mParams[i])
170 break;
San Mehat7e8529a2010-03-25 09:31:42 -0700171 SLOGD("NL param '%s'\n", mParams[i]);
San Mehatd6744132009-12-24 07:17:09 -0800172 }
173}
174
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700175/*
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900176 * Returns the message name for a message in the NETLINK_ROUTE family, or NULL
177 * if parsing that message is not supported.
178 */
179static const char *rtMessageName(int type) {
180#define NL_EVENT_RTM_NAME(rtm) case rtm: return #rtm;
181 switch (type) {
182 NL_EVENT_RTM_NAME(RTM_NEWLINK);
183 NL_EVENT_RTM_NAME(RTM_DELLINK);
184 NL_EVENT_RTM_NAME(RTM_NEWADDR);
185 NL_EVENT_RTM_NAME(RTM_DELADDR);
186 NL_EVENT_RTM_NAME(RTM_NEWROUTE);
187 NL_EVENT_RTM_NAME(RTM_DELROUTE);
188 NL_EVENT_RTM_NAME(RTM_NEWNDUSEROPT);
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700189 NL_EVENT_RTM_NAME(LOCAL_QLOG_NL_EVENT);
190 NL_EVENT_RTM_NAME(LOCAL_NFLOG_PACKET);
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900191 default:
Yi Kong48885252018-07-24 16:34:27 -0700192 return nullptr;
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900193 }
194#undef NL_EVENT_RTM_NAME
195}
196
197/*
198 * Checks that a binary NETLINK_ROUTE message is long enough for a payload of
199 * size bytes.
200 */
201static bool checkRtNetlinkLength(const struct nlmsghdr *nh, size_t size) {
202 if (nh->nlmsg_len < NLMSG_LENGTH(size)) {
203 SLOGE("Got a short %s message\n", rtMessageName(nh->nlmsg_type));
204 return false;
205 }
206 return true;
207}
208
209/*
210 * Utility function to log errors.
211 */
212static bool maybeLogDuplicateAttribute(bool isDup,
213 const char *attributeName,
214 const char *messageName) {
215 if (isDup) {
216 SLOGE("Multiple %s attributes in %s, ignoring\n", attributeName, messageName);
217 return true;
218 }
219 return false;
220}
221
222/*
223 * Parse a RTM_NEWLINK message.
224 */
225bool NetlinkEvent::parseIfInfoMessage(const struct nlmsghdr *nh) {
226 struct ifinfomsg *ifi = (struct ifinfomsg *) NLMSG_DATA(nh);
227 if (!checkRtNetlinkLength(nh, sizeof(*ifi)))
228 return false;
229
230 if ((ifi->ifi_flags & IFF_LOOPBACK) != 0) {
231 return false;
232 }
233
234 int len = IFLA_PAYLOAD(nh);
235 struct rtattr *rta;
236 for (rta = IFLA_RTA(ifi); RTA_OK(rta, len); rta = RTA_NEXT(rta, len)) {
237 switch(rta->rta_type) {
238 case IFLA_IFNAME:
239 asprintf(&mParams[0], "INTERFACE=%s", (char *) RTA_DATA(rta));
Chenbo Feng5e5e5e92018-03-02 01:32:53 -0800240 // We can get the interface change information from sysfs update
241 // already. But in case we missed those message when devices start.
242 // We do a update again when received a kLinkUp event. To make
243 // the message consistent, use IFINDEX here as well since sysfs
244 // uses IFINDEX.
245 asprintf(&mParams[1], "IFINDEX=%d", ifi->ifi_index);
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700246 mAction = (ifi->ifi_flags & IFF_LOWER_UP) ? Action::kLinkUp :
247 Action::kLinkDown;
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900248 mSubsystem = strdup("net");
249 return true;
250 }
251 }
252
253 return false;
254}
255
256/*
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900257 * Parse a RTM_NEWADDR or RTM_DELADDR message.
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900258 */
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900259bool NetlinkEvent::parseIfAddrMessage(const struct nlmsghdr *nh) {
260 struct ifaddrmsg *ifaddr = (struct ifaddrmsg *) NLMSG_DATA(nh);
Yi Kong48885252018-07-24 16:34:27 -0700261 struct ifa_cacheinfo *cacheinfo = nullptr;
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900262 char addrstr[INET6_ADDRSTRLEN] = "";
Lorenzo Colittief6454d2016-02-16 21:42:16 +0900263 char ifname[IFNAMSIZ] = "";
Lorenzo Colitti077d1ea2020-05-11 11:37:17 +0900264 uint32_t flags;
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900265
266 if (!checkRtNetlinkLength(nh, sizeof(*ifaddr)))
267 return false;
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900268
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900269 int type = nh->nlmsg_type;
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900270 if (type != RTM_NEWADDR && type != RTM_DELADDR) {
271 SLOGE("parseIfAddrMessage on incorrect message type 0x%x\n", type);
272 return false;
273 }
274
275 // For log messages.
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900276 const char *msgtype = rtMessageName(type);
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900277
Lorenzo Colitti077d1ea2020-05-11 11:37:17 +0900278 // First 8 bits of flags. In practice will always be overridden when parsing IFA_FLAGS below.
279 flags = ifaddr->ifa_flags;
280
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900281 struct rtattr *rta;
282 int len = IFA_PAYLOAD(nh);
283 for (rta = IFA_RTA(ifaddr); RTA_OK(rta, len); rta = RTA_NEXT(rta, len)) {
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900284 if (rta->rta_type == IFA_ADDRESS) {
285 // Only look at the first address, because we only support notifying
286 // one change at a time.
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900287 if (maybeLogDuplicateAttribute(*addrstr != '\0', "IFA_ADDRESS", msgtype))
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900288 continue;
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900289
290 // Convert the IP address to a string.
291 if (ifaddr->ifa_family == AF_INET) {
292 struct in_addr *addr4 = (struct in_addr *) RTA_DATA(rta);
293 if (RTA_PAYLOAD(rta) < sizeof(*addr4)) {
Mark Salyzyn80f63d42014-05-01 07:47:04 -0700294 SLOGE("Short IPv4 address (%zu bytes) in %s",
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900295 RTA_PAYLOAD(rta), msgtype);
296 continue;
297 }
298 inet_ntop(AF_INET, addr4, addrstr, sizeof(addrstr));
299 } else if (ifaddr->ifa_family == AF_INET6) {
300 struct in6_addr *addr6 = (struct in6_addr *) RTA_DATA(rta);
301 if (RTA_PAYLOAD(rta) < sizeof(*addr6)) {
Mark Salyzyn80f63d42014-05-01 07:47:04 -0700302 SLOGE("Short IPv6 address (%zu bytes) in %s",
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900303 RTA_PAYLOAD(rta), msgtype);
304 continue;
305 }
306 inet_ntop(AF_INET6, addr6, addrstr, sizeof(addrstr));
307 } else {
308 SLOGE("Unknown address family %d\n", ifaddr->ifa_family);
309 continue;
310 }
311
312 // Find the interface name.
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900313 if (!if_indextoname(ifaddr->ifa_index, ifname)) {
Lorenzo Colittief6454d2016-02-16 21:42:16 +0900314 SLOGD("Unknown ifindex %d in %s", ifaddr->ifa_index, msgtype);
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900315 }
316
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900317 } else if (rta->rta_type == IFA_CACHEINFO) {
318 // Address lifetime information.
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900319 if (maybeLogDuplicateAttribute(cacheinfo, "IFA_CACHEINFO", msgtype))
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900320 continue;
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900321
322 if (RTA_PAYLOAD(rta) < sizeof(*cacheinfo)) {
Mark Salyzyn80f63d42014-05-01 07:47:04 -0700323 SLOGE("Short IFA_CACHEINFO (%zu vs. %zu bytes) in %s",
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900324 RTA_PAYLOAD(rta), sizeof(cacheinfo), msgtype);
325 continue;
326 }
327
328 cacheinfo = (struct ifa_cacheinfo *) RTA_DATA(rta);
Lorenzo Colitti096fc532020-04-26 19:21:12 +0900329
330 } else if (rta->rta_type == IFA_FLAGS) {
Lorenzo Colitti096fc532020-04-26 19:21:12 +0900331 flags = *(uint32_t*)RTA_DATA(rta);
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900332 }
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900333 }
334
335 if (addrstr[0] == '\0') {
336 SLOGE("No IFA_ADDRESS in %s\n", msgtype);
337 return false;
338 }
339
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900340 // Fill in netlink event information.
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700341 mAction = (type == RTM_NEWADDR) ? Action::kAddressUpdated :
342 Action::kAddressRemoved;
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900343 mSubsystem = strdup("net");
Lorenzo Colittief6454d2016-02-16 21:42:16 +0900344 asprintf(&mParams[0], "ADDRESS=%s/%d", addrstr, ifaddr->ifa_prefixlen);
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900345 asprintf(&mParams[1], "INTERFACE=%s", ifname);
Lorenzo Colitti096fc532020-04-26 19:21:12 +0900346 asprintf(&mParams[2], "FLAGS=%u", flags);
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900347 asprintf(&mParams[3], "SCOPE=%u", ifaddr->ifa_scope);
Rubin Xu5f406242018-05-16 23:35:41 +0100348 asprintf(&mParams[4], "IFINDEX=%u", ifaddr->ifa_index);
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900349
350 if (cacheinfo) {
Rubin Xu5f406242018-05-16 23:35:41 +0100351 asprintf(&mParams[5], "PREFERRED=%u", cacheinfo->ifa_prefered);
352 asprintf(&mParams[6], "VALID=%u", cacheinfo->ifa_valid);
353 asprintf(&mParams[7], "CSTAMP=%u", cacheinfo->cstamp);
354 asprintf(&mParams[8], "TSTAMP=%u", cacheinfo->tstamp);
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900355 }
356
357 return true;
358}
359
360/*
361 * Parse a QLOG_NL_EVENT message.
362 */
363bool NetlinkEvent::parseUlogPacketMessage(const struct nlmsghdr *nh) {
Maciej Żenczykowski28b94af2021-10-25 15:24:18 -0700364 const char* alert;
365 const char* devname;
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900366
Maciej Żenczykowski28b94af2021-10-25 15:24:18 -0700367 if (isKernel64Bit()) {
368 ulog_packet_msg64_t* pm64 = (ulog_packet_msg64_t*)NLMSG_DATA(nh);
369 if (!checkRtNetlinkLength(nh, sizeof(*pm64))) return false;
370 alert = pm64->prefix;
371 devname = pm64->indev_name[0] ? pm64->indev_name : pm64->outdev_name;
372 } else {
373 ulog_packet_msg32_t* pm32 = (ulog_packet_msg32_t*)NLMSG_DATA(nh);
374 if (!checkRtNetlinkLength(nh, sizeof(*pm32))) return false;
375 alert = pm32->prefix;
376 devname = pm32->indev_name[0] ? pm32->indev_name : pm32->outdev_name;
377 }
378
379 asprintf(&mParams[0], "ALERT_NAME=%s", alert);
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900380 asprintf(&mParams[1], "INTERFACE=%s", devname);
381 mSubsystem = strdup("qlog");
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700382 mAction = Action::kChange;
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900383 return true;
384}
385
Lorenzo Colittie439ffc2017-10-03 18:44:11 +0900386static size_t nlAttrLen(const nlattr* nla) {
387 return nla->nla_len - NLA_HDRLEN;
388}
389
390static const uint8_t* nlAttrData(const nlattr* nla) {
391 return reinterpret_cast<const uint8_t*>(nla) + NLA_HDRLEN;
392}
393
394static uint32_t nlAttrU32(const nlattr* nla) {
395 return *reinterpret_cast<const uint32_t*>(nlAttrData(nla));
396}
397
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900398/*
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700399 * Parse a LOCAL_NFLOG_PACKET message.
400 */
401bool NetlinkEvent::parseNfPacketMessage(struct nlmsghdr *nh) {
402 int uid = -1;
403 int len = 0;
Yi Kong48885252018-07-24 16:34:27 -0700404 char* raw = nullptr;
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700405
Lorenzo Colittie439ffc2017-10-03 18:44:11 +0900406 struct nlattr* uid_attr = findNlAttr(nh, sizeof(struct genlmsghdr), NFULA_UID);
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700407 if (uid_attr) {
Lorenzo Colittie439ffc2017-10-03 18:44:11 +0900408 uid = ntohl(nlAttrU32(uid_attr));
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700409 }
410
Lorenzo Colittie439ffc2017-10-03 18:44:11 +0900411 struct nlattr* payload = findNlAttr(nh, sizeof(struct genlmsghdr), NFULA_PAYLOAD);
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700412 if (payload) {
413 /* First 256 bytes is plenty */
Lorenzo Colittie439ffc2017-10-03 18:44:11 +0900414 len = nlAttrLen(payload);
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700415 if (len > 256) len = 256;
Lorenzo Colittie439ffc2017-10-03 18:44:11 +0900416 raw = (char*)nlAttrData(payload);
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700417 }
418
Lorenzo Colittid0e49382019-04-10 23:04:41 +0900419 size_t hexSize = 5 + (len * 2);
420 char* hex = (char*)calloc(1, hexSize);
421 strlcpy(hex, "HEX=", hexSize);
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700422 for (int i = 0; i < len; i++) {
423 hex[4 + (i * 2)] = "0123456789abcdef"[(raw[i] >> 4) & 0xf];
424 hex[5 + (i * 2)] = "0123456789abcdef"[raw[i] & 0xf];
425 }
426
427 asprintf(&mParams[0], "UID=%d", uid);
428 mParams[1] = hex;
429 mSubsystem = strdup("strict");
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700430 mAction = Action::kChange;
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700431 return true;
432}
433
434/*
Lorenzo Colittid7ff7ea2014-06-11 17:37:12 +0900435 * Parse a RTM_NEWROUTE or RTM_DELROUTE message.
436 */
437bool NetlinkEvent::parseRtMessage(const struct nlmsghdr *nh) {
438 uint8_t type = nh->nlmsg_type;
439 const char *msgname = rtMessageName(type);
440
Lorenzo Colittid7ff7ea2014-06-11 17:37:12 +0900441 if (type != RTM_NEWROUTE && type != RTM_DELROUTE) {
442 SLOGE("%s: incorrect message type %d (%s)\n", __func__, type, msgname);
443 return false;
444 }
445
446 struct rtmsg *rtm = (struct rtmsg *) NLMSG_DATA(nh);
447 if (!checkRtNetlinkLength(nh, sizeof(*rtm)))
448 return false;
449
450 if (// Ignore static routes we've set up ourselves.
451 (rtm->rtm_protocol != RTPROT_KERNEL &&
452 rtm->rtm_protocol != RTPROT_RA) ||
453 // We're only interested in global unicast routes.
454 (rtm->rtm_scope != RT_SCOPE_UNIVERSE) ||
455 (rtm->rtm_type != RTN_UNICAST) ||
456 // We don't support source routing.
457 (rtm->rtm_src_len != 0) ||
458 // Cloned routes aren't real routes.
459 (rtm->rtm_flags & RTM_F_CLONED)) {
460 return false;
461 }
462
463 int family = rtm->rtm_family;
464 int prefixLength = rtm->rtm_dst_len;
465
466 // Currently we only support: destination, (one) next hop, ifindex.
467 char dst[INET6_ADDRSTRLEN] = "";
468 char gw[INET6_ADDRSTRLEN] = "";
469 char dev[IFNAMSIZ] = "";
470
471 size_t len = RTM_PAYLOAD(nh);
472 struct rtattr *rta;
473 for (rta = RTM_RTA(rtm); RTA_OK(rta, len); rta = RTA_NEXT(rta, len)) {
474 switch (rta->rta_type) {
475 case RTA_DST:
476 if (maybeLogDuplicateAttribute(*dst, "RTA_DST", msgname))
477 continue;
478 if (!inet_ntop(family, RTA_DATA(rta), dst, sizeof(dst)))
479 return false;
480 continue;
481 case RTA_GATEWAY:
482 if (maybeLogDuplicateAttribute(*gw, "RTA_GATEWAY", msgname))
483 continue;
484 if (!inet_ntop(family, RTA_DATA(rta), gw, sizeof(gw)))
485 return false;
486 continue;
487 case RTA_OIF:
488 if (maybeLogDuplicateAttribute(*dev, "RTA_OIF", msgname))
489 continue;
490 if (!if_indextoname(* (int *) RTA_DATA(rta), dev))
491 return false;
Chih-Hung Hsiehe6e2b3c2018-10-10 14:39:02 -0700492 continue;
Lorenzo Colittid7ff7ea2014-06-11 17:37:12 +0900493 default:
494 continue;
495 }
496 }
497
498 // If there's no RTA_DST attribute, then:
499 // - If the prefix length is zero, it's the default route.
500 // - If the prefix length is nonzero, there's something we don't understand.
501 // Ignore the event.
502 if (!*dst && !prefixLength) {
503 if (family == AF_INET) {
504 strncpy(dst, "0.0.0.0", sizeof(dst));
505 } else if (family == AF_INET6) {
506 strncpy(dst, "::", sizeof(dst));
507 }
508 }
509
510 // A useful route must have a destination and at least either a gateway or
511 // an interface.
512 if (!*dst || (!*gw && !*dev))
513 return false;
514
515 // Fill in netlink event information.
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700516 mAction = (type == RTM_NEWROUTE) ? Action::kRouteUpdated :
517 Action::kRouteRemoved;
Lorenzo Colittid7ff7ea2014-06-11 17:37:12 +0900518 mSubsystem = strdup("net");
519 asprintf(&mParams[0], "ROUTE=%s/%d", dst, prefixLength);
520 asprintf(&mParams[1], "GATEWAY=%s", (*gw) ? gw : "");
521 asprintf(&mParams[2], "INTERFACE=%s", (*dev) ? dev : "");
522
523 return true;
524}
525
526/*
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900527 * Parse a RTM_NEWNDUSEROPT message.
528 */
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900529bool NetlinkEvent::parseNdUserOptMessage(const struct nlmsghdr *nh) {
530 struct nduseroptmsg *msg = (struct nduseroptmsg *) NLMSG_DATA(nh);
531 if (!checkRtNetlinkLength(nh, sizeof(*msg)))
532 return false;
533
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900534 // Check the length is valid.
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900535 int len = NLMSG_PAYLOAD(nh, sizeof(*msg));
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900536 if (msg->nduseropt_opts_len > len) {
537 SLOGE("RTM_NEWNDUSEROPT invalid length %d > %d\n",
538 msg->nduseropt_opts_len, len);
539 return false;
540 }
541 len = msg->nduseropt_opts_len;
542
543 // Check address family and packet type.
544 if (msg->nduseropt_family != AF_INET6) {
545 SLOGE("RTM_NEWNDUSEROPT message for unknown family %d\n",
546 msg->nduseropt_family);
547 return false;
548 }
549
550 if (msg->nduseropt_icmp_type != ND_ROUTER_ADVERT ||
551 msg->nduseropt_icmp_code != 0) {
552 SLOGE("RTM_NEWNDUSEROPT message for unknown ICMPv6 type/code %d/%d\n",
553 msg->nduseropt_icmp_type, msg->nduseropt_icmp_code);
554 return false;
555 }
556
557 // Find the interface name.
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900558 char ifname[IFNAMSIZ];
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900559 if (!if_indextoname(msg->nduseropt_ifindex, ifname)) {
560 SLOGE("RTM_NEWNDUSEROPT on unknown ifindex %d\n",
561 msg->nduseropt_ifindex);
562 return false;
563 }
564
565 // The kernel sends a separate netlink message for each ND option in the RA.
566 // So only parse the first ND option in the message.
567 struct nd_opt_hdr *opthdr = (struct nd_opt_hdr *) (msg + 1);
568
569 // The length is in multiples of 8 octets.
570 uint16_t optlen = opthdr->nd_opt_len;
571 if (optlen * 8 > len) {
572 SLOGE("Invalid option length %d > %d for ND option %d\n",
573 optlen * 8, len, opthdr->nd_opt_type);
574 return false;
575 }
576
577 if (opthdr->nd_opt_type == ND_OPT_RDNSS) {
578 // DNS Servers (RFC 6106).
579 // Each address takes up 2*8 octets, and the header takes up 8 octets.
580 // So for a valid option with one or more addresses, optlen must be
581 // odd and greater than 1.
582 if ((optlen < 3) || !(optlen & 0x1)) {
583 SLOGE("Invalid optlen %d for RDNSS option\n", optlen);
584 return false;
585 }
Erik Klineba48ff72015-06-17 15:53:29 +0900586 const int numaddrs = (optlen - 1) / 2;
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900587
588 // Find the lifetime.
589 struct nd_opt_rdnss *rndss_opt = (struct nd_opt_rdnss *) opthdr;
Erik Klineba48ff72015-06-17 15:53:29 +0900590 const uint32_t lifetime = ntohl(rndss_opt->nd_opt_rdnss_lifetime);
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900591
Lorenzo Colittid0e49382019-04-10 23:04:41 +0900592 // Construct a comma-separated string of DNS addresses.
Erik Klineba48ff72015-06-17 15:53:29 +0900593 // Reserve sufficient space for an IPv6 link-local address: all but the
594 // last address are followed by ','; the last is followed by '\0'.
Erik Klinecc451782015-07-28 17:31:19 +0900595 static const size_t kMaxSingleAddressLength =
Erik Klineba48ff72015-06-17 15:53:29 +0900596 INET6_ADDRSTRLEN + strlen("%") + IFNAMSIZ + strlen(",");
Lorenzo Colittid0e49382019-04-10 23:04:41 +0900597 const size_t bufsize = numaddrs * kMaxSingleAddressLength;
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900598 char *buf = (char *) malloc(bufsize);
599 if (!buf) {
600 SLOGE("RDNSS option: out of memory\n");
601 return false;
602 }
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900603
604 struct in6_addr *addrs = (struct in6_addr *) (rndss_opt + 1);
Lorenzo Colittid0e49382019-04-10 23:04:41 +0900605 size_t pos = 0;
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900606 for (int i = 0; i < numaddrs; i++) {
607 if (i > 0) {
608 buf[pos++] = ',';
609 }
610 inet_ntop(AF_INET6, addrs + i, buf + pos, bufsize - pos);
611 pos += strlen(buf + pos);
Erik Klineba48ff72015-06-17 15:53:29 +0900612 if (IN6_IS_ADDR_LINKLOCAL(addrs + i)) {
613 buf[pos++] = '%';
614 pos += strlcpy(buf + pos, ifname, bufsize - pos);
615 }
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900616 }
617 buf[pos] = '\0';
618
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700619 mAction = Action::kRdnss;
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900620 mSubsystem = strdup("net");
621 asprintf(&mParams[0], "INTERFACE=%s", ifname);
622 asprintf(&mParams[1], "LIFETIME=%u", lifetime);
Lorenzo Colittid0e49382019-04-10 23:04:41 +0900623 asprintf(&mParams[2], "SERVERS=%s", buf);
624 free(buf);
Lorenzo Colitticbfd65d2017-11-28 15:32:40 +0900625 } else if (opthdr->nd_opt_type == ND_OPT_DNSSL) {
626 // TODO: support DNSSL.
Maciej Żenczykowskia806a712020-03-31 19:55:06 -0700627 } else if (opthdr->nd_opt_type == ND_OPT_CAPTIVE_PORTAL) {
628 // TODO: support CAPTIVE PORTAL.
629 } else if (opthdr->nd_opt_type == ND_OPT_PREF64) {
630 // TODO: support PREF64.
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900631 } else {
632 SLOGD("Unknown ND option type %d\n", opthdr->nd_opt_type);
633 return false;
634 }
635
636 return true;
637}
638
639/*
640 * Parse a binary message from a NETLINK_ROUTE netlink socket.
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900641 *
642 * Note that this function can only parse one message, because the message's
643 * content has to be stored in the class's member variables (mAction,
644 * mSubsystem, etc.). Invalid or unrecognized messages are skipped, but if
645 * there are multiple valid messages in the buffer, only the first one will be
646 * returned.
647 *
648 * TODO: consider only ever looking at the first message.
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700649 */
650bool NetlinkEvent::parseBinaryNetlinkMessage(char *buffer, int size) {
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700651 struct nlmsghdr *nh;
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700652
Lorenzo Colitti96834562013-08-17 03:40:31 +0900653 for (nh = (struct nlmsghdr *) buffer;
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900654 NLMSG_OK(nh, (unsigned) size) && (nh->nlmsg_type != NLMSG_DONE);
Lorenzo Colitti96834562013-08-17 03:40:31 +0900655 nh = NLMSG_NEXT(nh, size)) {
JP Abgralle6f80142011-07-14 16:46:32 -0700656
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900657 if (!rtMessageName(nh->nlmsg_type)) {
658 SLOGD("Unexpected netlink message type %d\n", nh->nlmsg_type);
659 continue;
660 }
661
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700662 if (nh->nlmsg_type == RTM_NEWLINK) {
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900663 if (parseIfInfoMessage(nh))
664 return true;
JP Abgralle6f80142011-07-14 16:46:32 -0700665
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700666 } else if (nh->nlmsg_type == LOCAL_QLOG_NL_EVENT) {
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900667 if (parseUlogPacketMessage(nh))
668 return true;
JP Abgralle6f80142011-07-14 16:46:32 -0700669
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900670 } else if (nh->nlmsg_type == RTM_NEWADDR ||
671 nh->nlmsg_type == RTM_DELADDR) {
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900672 if (parseIfAddrMessage(nh))
673 return true;
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900674
Lorenzo Colittid7ff7ea2014-06-11 17:37:12 +0900675 } else if (nh->nlmsg_type == RTM_NEWROUTE ||
676 nh->nlmsg_type == RTM_DELROUTE) {
677 if (parseRtMessage(nh))
678 return true;
679
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900680 } else if (nh->nlmsg_type == RTM_NEWNDUSEROPT) {
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900681 if (parseNdUserOptMessage(nh))
682 return true;
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900683
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700684 } else if (nh->nlmsg_type == LOCAL_NFLOG_PACKET) {
685 if (parseNfPacketMessage(nh))
686 return true;
687
JP Abgralle6f80142011-07-14 16:46:32 -0700688 }
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700689 }
690
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900691 return false;
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700692}
693
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100694/* If the string between 'str' and 'end' begins with 'prefixlen' characters
695 * from the 'prefix' array, then return 'str + prefixlen', otherwise return
696 * NULL.
697 */
698static const char*
699has_prefix(const char* str, const char* end, const char* prefix, size_t prefixlen)
700{
Yunlian Jiang33f67172017-02-07 15:39:25 -0800701 if ((end - str) >= (ptrdiff_t)prefixlen &&
702 (prefixlen == 0 || !memcmp(str, prefix, prefixlen))) {
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100703 return str + prefixlen;
Yunlian Jiang33f67172017-02-07 15:39:25 -0800704 } else {
Yi Kong48885252018-07-24 16:34:27 -0700705 return nullptr;
Yunlian Jiang33f67172017-02-07 15:39:25 -0800706 }
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100707}
708
709/* Same as strlen(x) for constant string literals ONLY */
710#define CONST_STRLEN(x) (sizeof(x)-1)
711
712/* Convenience macro to call has_prefix with a constant string literal */
713#define HAS_CONST_PREFIX(str,end,prefix) has_prefix((str),(end),prefix,CONST_STRLEN(prefix))
714
715
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700716/*
717 * Parse an ASCII-formatted message from a NETLINK_KOBJECT_UEVENT
718 * netlink socket.
719 */
720bool NetlinkEvent::parseAsciiNetlinkMessage(char *buffer, int size) {
Mike J. Chen17260b12011-06-23 15:00:30 -0700721 const char *s = buffer;
722 const char *end;
San Mehat168415b2009-05-06 11:14:21 -0700723 int param_idx = 0;
San Mehat168415b2009-05-06 11:14:21 -0700724 int first = 1;
725
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100726 if (size == 0)
727 return false;
728
729 /* Ensure the buffer is zero-terminated, the code below depends on this */
730 buffer[size-1] = '\0';
731
San Mehat168415b2009-05-06 11:14:21 -0700732 end = s + size;
733 while (s < end) {
734 if (first) {
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100735 const char *p;
736 /* buffer is 0-terminated, no need to check p < end */
737 for (p = s; *p != '@'; p++) {
738 if (!*p) { /* no '@', should not happen */
739 return false;
740 }
741 }
742 mPath = strdup(p+1);
San Mehat168415b2009-05-06 11:14:21 -0700743 first = 0;
744 } else {
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100745 const char* a;
Yi Kong48885252018-07-24 16:34:27 -0700746 if ((a = HAS_CONST_PREFIX(s, end, "ACTION=")) != nullptr) {
San Mehat168415b2009-05-06 11:14:21 -0700747 if (!strcmp(a, "add"))
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700748 mAction = Action::kAdd;
San Mehat168415b2009-05-06 11:14:21 -0700749 else if (!strcmp(a, "remove"))
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700750 mAction = Action::kRemove;
San Mehat168415b2009-05-06 11:14:21 -0700751 else if (!strcmp(a, "change"))
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700752 mAction = Action::kChange;
Yi Kong48885252018-07-24 16:34:27 -0700753 } else if ((a = HAS_CONST_PREFIX(s, end, "SEQNUM=")) != nullptr) {
Lorenzo Colittid0e49382019-04-10 23:04:41 +0900754 if (!ParseInt(a, &mSeq)) {
755 SLOGE("NetlinkEvent::parseAsciiNetlinkMessage: failed to parse SEQNUM=%s", a);
756 }
Yi Kong48885252018-07-24 16:34:27 -0700757 } else if ((a = HAS_CONST_PREFIX(s, end, "SUBSYSTEM=")) != nullptr) {
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100758 mSubsystem = strdup(a);
759 } else if (param_idx < NL_PARAMS_MAX) {
San Mehat168415b2009-05-06 11:14:21 -0700760 mParams[param_idx++] = strdup(s);
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100761 }
San Mehat168415b2009-05-06 11:14:21 -0700762 }
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100763 s += strlen(s) + 1;
San Mehat168415b2009-05-06 11:14:21 -0700764 }
765 return true;
766}
767
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700768bool NetlinkEvent::decode(char *buffer, int size, int format) {
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700769 if (format == NetlinkListener::NETLINK_FORMAT_BINARY
770 || format == NetlinkListener::NETLINK_FORMAT_BINARY_UNICAST) {
Mike J. Chen17260b12011-06-23 15:00:30 -0700771 return parseBinaryNetlinkMessage(buffer, size);
772 } else {
773 return parseAsciiNetlinkMessage(buffer, size);
774 }
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700775}
776
San Mehat168415b2009-05-06 11:14:21 -0700777const char *NetlinkEvent::findParam(const char *paramName) {
Chih-Wei Huang80ec37a2010-07-14 14:00:41 +0800778 size_t len = strlen(paramName);
Yi Kong48885252018-07-24 16:34:27 -0700779 for (int i = 0; i < NL_PARAMS_MAX && mParams[i] != nullptr; ++i) {
Chih-Wei Huang80ec37a2010-07-14 14:00:41 +0800780 const char *ptr = mParams[i] + len;
781 if (!strncmp(mParams[i], paramName, len) && *ptr == '=')
782 return ++ptr;
San Mehat168415b2009-05-06 11:14:21 -0700783 }
784
San Mehat7e8529a2010-03-25 09:31:42 -0700785 SLOGE("NetlinkEvent::FindParam(): Parameter '%s' not found", paramName);
Yi Kong48885252018-07-24 16:34:27 -0700786 return nullptr;
San Mehat168415b2009-05-06 11:14:21 -0700787}
Lorenzo Colittie439ffc2017-10-03 18:44:11 +0900788
789nlattr* NetlinkEvent::findNlAttr(const nlmsghdr* nh, size_t hdrlen, uint16_t attr) {
790 if (nh == nullptr || NLMSG_HDRLEN + NLMSG_ALIGN(hdrlen) > SSIZE_MAX) {
791 return nullptr;
792 }
793
794 // Skip header, padding, and family header.
795 const ssize_t NLA_START = NLMSG_HDRLEN + NLMSG_ALIGN(hdrlen);
796 ssize_t left = nh->nlmsg_len - NLA_START;
797 uint8_t* hdr = ((uint8_t*)nh) + NLA_START;
798
799 while (left >= NLA_HDRLEN) {
800 nlattr* nla = (nlattr*)hdr;
801 if (nla->nla_type == attr) {
802 return nla;
803 }
804
805 hdr += NLA_ALIGN(nla->nla_len);
806 left -= NLA_ALIGN(nla->nla_len);
807 }
808
809 return nullptr;
810}