blob: 55bbe46e1a855795315d54baa2304d2b43a3d8c9 [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() {
Elliott Hughes15632502023-07-10 22:03:11 +0000153 free(mPath);
154 free(mSubsystem);
155 for (auto param : mParams) {
156 free(param);
San Mehat168415b2009-05-06 11:14:21 -0700157 }
158}
159
San Mehatd6744132009-12-24 07:17:09 -0800160void NetlinkEvent::dump() {
161 int i;
162
163 for (i = 0; i < NL_PARAMS_MAX; i++) {
164 if (!mParams[i])
165 break;
San Mehat7e8529a2010-03-25 09:31:42 -0700166 SLOGD("NL param '%s'\n", mParams[i]);
San Mehatd6744132009-12-24 07:17:09 -0800167 }
168}
169
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700170/*
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900171 * Returns the message name for a message in the NETLINK_ROUTE family, or NULL
172 * if parsing that message is not supported.
173 */
174static const char *rtMessageName(int type) {
175#define NL_EVENT_RTM_NAME(rtm) case rtm: return #rtm;
176 switch (type) {
177 NL_EVENT_RTM_NAME(RTM_NEWLINK);
178 NL_EVENT_RTM_NAME(RTM_DELLINK);
179 NL_EVENT_RTM_NAME(RTM_NEWADDR);
180 NL_EVENT_RTM_NAME(RTM_DELADDR);
181 NL_EVENT_RTM_NAME(RTM_NEWROUTE);
182 NL_EVENT_RTM_NAME(RTM_DELROUTE);
183 NL_EVENT_RTM_NAME(RTM_NEWNDUSEROPT);
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700184 NL_EVENT_RTM_NAME(LOCAL_QLOG_NL_EVENT);
185 NL_EVENT_RTM_NAME(LOCAL_NFLOG_PACKET);
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900186 default:
Yi Kong48885252018-07-24 16:34:27 -0700187 return nullptr;
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900188 }
189#undef NL_EVENT_RTM_NAME
190}
191
192/*
193 * Checks that a binary NETLINK_ROUTE message is long enough for a payload of
194 * size bytes.
195 */
196static bool checkRtNetlinkLength(const struct nlmsghdr *nh, size_t size) {
197 if (nh->nlmsg_len < NLMSG_LENGTH(size)) {
198 SLOGE("Got a short %s message\n", rtMessageName(nh->nlmsg_type));
199 return false;
200 }
201 return true;
202}
203
204/*
205 * Utility function to log errors.
206 */
207static bool maybeLogDuplicateAttribute(bool isDup,
208 const char *attributeName,
209 const char *messageName) {
210 if (isDup) {
211 SLOGE("Multiple %s attributes in %s, ignoring\n", attributeName, messageName);
212 return true;
213 }
214 return false;
215}
216
217/*
218 * Parse a RTM_NEWLINK message.
219 */
220bool NetlinkEvent::parseIfInfoMessage(const struct nlmsghdr *nh) {
221 struct ifinfomsg *ifi = (struct ifinfomsg *) NLMSG_DATA(nh);
222 if (!checkRtNetlinkLength(nh, sizeof(*ifi)))
223 return false;
224
225 if ((ifi->ifi_flags & IFF_LOOPBACK) != 0) {
226 return false;
227 }
228
229 int len = IFLA_PAYLOAD(nh);
230 struct rtattr *rta;
231 for (rta = IFLA_RTA(ifi); RTA_OK(rta, len); rta = RTA_NEXT(rta, len)) {
232 switch(rta->rta_type) {
233 case IFLA_IFNAME:
234 asprintf(&mParams[0], "INTERFACE=%s", (char *) RTA_DATA(rta));
Chenbo Feng5e5e5e92018-03-02 01:32:53 -0800235 // We can get the interface change information from sysfs update
236 // already. But in case we missed those message when devices start.
237 // We do a update again when received a kLinkUp event. To make
238 // the message consistent, use IFINDEX here as well since sysfs
239 // uses IFINDEX.
240 asprintf(&mParams[1], "IFINDEX=%d", ifi->ifi_index);
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700241 mAction = (ifi->ifi_flags & IFF_LOWER_UP) ? Action::kLinkUp :
242 Action::kLinkDown;
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900243 mSubsystem = strdup("net");
244 return true;
245 }
246 }
247
248 return false;
249}
250
251/*
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900252 * Parse a RTM_NEWADDR or RTM_DELADDR message.
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900253 */
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900254bool NetlinkEvent::parseIfAddrMessage(const struct nlmsghdr *nh) {
255 struct ifaddrmsg *ifaddr = (struct ifaddrmsg *) NLMSG_DATA(nh);
Yi Kong48885252018-07-24 16:34:27 -0700256 struct ifa_cacheinfo *cacheinfo = nullptr;
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900257 char addrstr[INET6_ADDRSTRLEN] = "";
Lorenzo Colittief6454d2016-02-16 21:42:16 +0900258 char ifname[IFNAMSIZ] = "";
Lorenzo Colitti077d1ea2020-05-11 11:37:17 +0900259 uint32_t flags;
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900260
261 if (!checkRtNetlinkLength(nh, sizeof(*ifaddr)))
262 return false;
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900263
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900264 int type = nh->nlmsg_type;
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900265 if (type != RTM_NEWADDR && type != RTM_DELADDR) {
266 SLOGE("parseIfAddrMessage on incorrect message type 0x%x\n", type);
267 return false;
268 }
269
270 // For log messages.
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900271 const char *msgtype = rtMessageName(type);
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900272
Lorenzo Colitti077d1ea2020-05-11 11:37:17 +0900273 // First 8 bits of flags. In practice will always be overridden when parsing IFA_FLAGS below.
274 flags = ifaddr->ifa_flags;
275
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900276 struct rtattr *rta;
277 int len = IFA_PAYLOAD(nh);
278 for (rta = IFA_RTA(ifaddr); RTA_OK(rta, len); rta = RTA_NEXT(rta, len)) {
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900279 if (rta->rta_type == IFA_ADDRESS) {
280 // Only look at the first address, because we only support notifying
281 // one change at a time.
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900282 if (maybeLogDuplicateAttribute(*addrstr != '\0', "IFA_ADDRESS", msgtype))
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900283 continue;
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900284
285 // Convert the IP address to a string.
286 if (ifaddr->ifa_family == AF_INET) {
287 struct in_addr *addr4 = (struct in_addr *) RTA_DATA(rta);
288 if (RTA_PAYLOAD(rta) < sizeof(*addr4)) {
Mark Salyzyn80f63d42014-05-01 07:47:04 -0700289 SLOGE("Short IPv4 address (%zu bytes) in %s",
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900290 RTA_PAYLOAD(rta), msgtype);
291 continue;
292 }
293 inet_ntop(AF_INET, addr4, addrstr, sizeof(addrstr));
294 } else if (ifaddr->ifa_family == AF_INET6) {
295 struct in6_addr *addr6 = (struct in6_addr *) RTA_DATA(rta);
296 if (RTA_PAYLOAD(rta) < sizeof(*addr6)) {
Mark Salyzyn80f63d42014-05-01 07:47:04 -0700297 SLOGE("Short IPv6 address (%zu bytes) in %s",
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900298 RTA_PAYLOAD(rta), msgtype);
299 continue;
300 }
301 inet_ntop(AF_INET6, addr6, addrstr, sizeof(addrstr));
302 } else {
303 SLOGE("Unknown address family %d\n", ifaddr->ifa_family);
304 continue;
305 }
306
307 // Find the interface name.
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900308 if (!if_indextoname(ifaddr->ifa_index, ifname)) {
Lorenzo Colittief6454d2016-02-16 21:42:16 +0900309 SLOGD("Unknown ifindex %d in %s", ifaddr->ifa_index, msgtype);
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900310 }
311
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900312 } else if (rta->rta_type == IFA_CACHEINFO) {
313 // Address lifetime information.
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900314 if (maybeLogDuplicateAttribute(cacheinfo, "IFA_CACHEINFO", msgtype))
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900315 continue;
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900316
317 if (RTA_PAYLOAD(rta) < sizeof(*cacheinfo)) {
Mark Salyzyn80f63d42014-05-01 07:47:04 -0700318 SLOGE("Short IFA_CACHEINFO (%zu vs. %zu bytes) in %s",
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900319 RTA_PAYLOAD(rta), sizeof(cacheinfo), msgtype);
320 continue;
321 }
322
323 cacheinfo = (struct ifa_cacheinfo *) RTA_DATA(rta);
Lorenzo Colitti096fc532020-04-26 19:21:12 +0900324
325 } else if (rta->rta_type == IFA_FLAGS) {
Lorenzo Colitti096fc532020-04-26 19:21:12 +0900326 flags = *(uint32_t*)RTA_DATA(rta);
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900327 }
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900328 }
329
330 if (addrstr[0] == '\0') {
331 SLOGE("No IFA_ADDRESS in %s\n", msgtype);
332 return false;
333 }
334
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900335 // Fill in netlink event information.
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700336 mAction = (type == RTM_NEWADDR) ? Action::kAddressUpdated :
337 Action::kAddressRemoved;
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900338 mSubsystem = strdup("net");
Lorenzo Colittief6454d2016-02-16 21:42:16 +0900339 asprintf(&mParams[0], "ADDRESS=%s/%d", addrstr, ifaddr->ifa_prefixlen);
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900340 asprintf(&mParams[1], "INTERFACE=%s", ifname);
Lorenzo Colitti096fc532020-04-26 19:21:12 +0900341 asprintf(&mParams[2], "FLAGS=%u", flags);
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900342 asprintf(&mParams[3], "SCOPE=%u", ifaddr->ifa_scope);
Rubin Xu5f406242018-05-16 23:35:41 +0100343 asprintf(&mParams[4], "IFINDEX=%u", ifaddr->ifa_index);
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900344
345 if (cacheinfo) {
Rubin Xu5f406242018-05-16 23:35:41 +0100346 asprintf(&mParams[5], "PREFERRED=%u", cacheinfo->ifa_prefered);
347 asprintf(&mParams[6], "VALID=%u", cacheinfo->ifa_valid);
348 asprintf(&mParams[7], "CSTAMP=%u", cacheinfo->cstamp);
349 asprintf(&mParams[8], "TSTAMP=%u", cacheinfo->tstamp);
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900350 }
351
352 return true;
353}
354
355/*
356 * Parse a QLOG_NL_EVENT message.
357 */
358bool NetlinkEvent::parseUlogPacketMessage(const struct nlmsghdr *nh) {
Maciej Żenczykowski28b94af2021-10-25 15:24:18 -0700359 const char* alert;
360 const char* devname;
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900361
Maciej Żenczykowski28b94af2021-10-25 15:24:18 -0700362 if (isKernel64Bit()) {
363 ulog_packet_msg64_t* pm64 = (ulog_packet_msg64_t*)NLMSG_DATA(nh);
364 if (!checkRtNetlinkLength(nh, sizeof(*pm64))) return false;
365 alert = pm64->prefix;
366 devname = pm64->indev_name[0] ? pm64->indev_name : pm64->outdev_name;
367 } else {
368 ulog_packet_msg32_t* pm32 = (ulog_packet_msg32_t*)NLMSG_DATA(nh);
369 if (!checkRtNetlinkLength(nh, sizeof(*pm32))) return false;
370 alert = pm32->prefix;
371 devname = pm32->indev_name[0] ? pm32->indev_name : pm32->outdev_name;
372 }
373
374 asprintf(&mParams[0], "ALERT_NAME=%s", alert);
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900375 asprintf(&mParams[1], "INTERFACE=%s", devname);
376 mSubsystem = strdup("qlog");
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700377 mAction = Action::kChange;
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900378 return true;
379}
380
Lorenzo Colittie439ffc2017-10-03 18:44:11 +0900381static size_t nlAttrLen(const nlattr* nla) {
382 return nla->nla_len - NLA_HDRLEN;
383}
384
385static const uint8_t* nlAttrData(const nlattr* nla) {
386 return reinterpret_cast<const uint8_t*>(nla) + NLA_HDRLEN;
387}
388
389static uint32_t nlAttrU32(const nlattr* nla) {
390 return *reinterpret_cast<const uint32_t*>(nlAttrData(nla));
391}
392
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900393/*
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700394 * Parse a LOCAL_NFLOG_PACKET message.
395 */
396bool NetlinkEvent::parseNfPacketMessage(struct nlmsghdr *nh) {
397 int uid = -1;
398 int len = 0;
Yi Kong48885252018-07-24 16:34:27 -0700399 char* raw = nullptr;
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700400
Lorenzo Colittie439ffc2017-10-03 18:44:11 +0900401 struct nlattr* uid_attr = findNlAttr(nh, sizeof(struct genlmsghdr), NFULA_UID);
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700402 if (uid_attr) {
Lorenzo Colittie439ffc2017-10-03 18:44:11 +0900403 uid = ntohl(nlAttrU32(uid_attr));
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700404 }
405
Lorenzo Colittie439ffc2017-10-03 18:44:11 +0900406 struct nlattr* payload = findNlAttr(nh, sizeof(struct genlmsghdr), NFULA_PAYLOAD);
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700407 if (payload) {
408 /* First 256 bytes is plenty */
Lorenzo Colittie439ffc2017-10-03 18:44:11 +0900409 len = nlAttrLen(payload);
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700410 if (len > 256) len = 256;
Lorenzo Colittie439ffc2017-10-03 18:44:11 +0900411 raw = (char*)nlAttrData(payload);
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700412 }
413
Lorenzo Colittid0e49382019-04-10 23:04:41 +0900414 size_t hexSize = 5 + (len * 2);
415 char* hex = (char*)calloc(1, hexSize);
416 strlcpy(hex, "HEX=", hexSize);
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700417 for (int i = 0; i < len; i++) {
418 hex[4 + (i * 2)] = "0123456789abcdef"[(raw[i] >> 4) & 0xf];
419 hex[5 + (i * 2)] = "0123456789abcdef"[raw[i] & 0xf];
420 }
421
422 asprintf(&mParams[0], "UID=%d", uid);
423 mParams[1] = hex;
424 mSubsystem = strdup("strict");
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700425 mAction = Action::kChange;
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700426 return true;
427}
428
429/*
Lorenzo Colittid7ff7ea2014-06-11 17:37:12 +0900430 * Parse a RTM_NEWROUTE or RTM_DELROUTE message.
431 */
432bool NetlinkEvent::parseRtMessage(const struct nlmsghdr *nh) {
433 uint8_t type = nh->nlmsg_type;
434 const char *msgname = rtMessageName(type);
435
Lorenzo Colittid7ff7ea2014-06-11 17:37:12 +0900436 if (type != RTM_NEWROUTE && type != RTM_DELROUTE) {
437 SLOGE("%s: incorrect message type %d (%s)\n", __func__, type, msgname);
438 return false;
439 }
440
441 struct rtmsg *rtm = (struct rtmsg *) NLMSG_DATA(nh);
442 if (!checkRtNetlinkLength(nh, sizeof(*rtm)))
443 return false;
444
445 if (// Ignore static routes we've set up ourselves.
446 (rtm->rtm_protocol != RTPROT_KERNEL &&
447 rtm->rtm_protocol != RTPROT_RA) ||
448 // We're only interested in global unicast routes.
449 (rtm->rtm_scope != RT_SCOPE_UNIVERSE) ||
450 (rtm->rtm_type != RTN_UNICAST) ||
451 // We don't support source routing.
452 (rtm->rtm_src_len != 0) ||
453 // Cloned routes aren't real routes.
454 (rtm->rtm_flags & RTM_F_CLONED)) {
455 return false;
456 }
457
458 int family = rtm->rtm_family;
459 int prefixLength = rtm->rtm_dst_len;
460
461 // Currently we only support: destination, (one) next hop, ifindex.
462 char dst[INET6_ADDRSTRLEN] = "";
463 char gw[INET6_ADDRSTRLEN] = "";
464 char dev[IFNAMSIZ] = "";
465
466 size_t len = RTM_PAYLOAD(nh);
467 struct rtattr *rta;
468 for (rta = RTM_RTA(rtm); RTA_OK(rta, len); rta = RTA_NEXT(rta, len)) {
469 switch (rta->rta_type) {
470 case RTA_DST:
471 if (maybeLogDuplicateAttribute(*dst, "RTA_DST", msgname))
472 continue;
473 if (!inet_ntop(family, RTA_DATA(rta), dst, sizeof(dst)))
474 return false;
475 continue;
476 case RTA_GATEWAY:
477 if (maybeLogDuplicateAttribute(*gw, "RTA_GATEWAY", msgname))
478 continue;
479 if (!inet_ntop(family, RTA_DATA(rta), gw, sizeof(gw)))
480 return false;
481 continue;
482 case RTA_OIF:
483 if (maybeLogDuplicateAttribute(*dev, "RTA_OIF", msgname))
484 continue;
485 if (!if_indextoname(* (int *) RTA_DATA(rta), dev))
486 return false;
Chih-Hung Hsiehe6e2b3c2018-10-10 14:39:02 -0700487 continue;
Lorenzo Colittid7ff7ea2014-06-11 17:37:12 +0900488 default:
489 continue;
490 }
491 }
492
493 // If there's no RTA_DST attribute, then:
494 // - If the prefix length is zero, it's the default route.
495 // - If the prefix length is nonzero, there's something we don't understand.
496 // Ignore the event.
497 if (!*dst && !prefixLength) {
498 if (family == AF_INET) {
499 strncpy(dst, "0.0.0.0", sizeof(dst));
500 } else if (family == AF_INET6) {
501 strncpy(dst, "::", sizeof(dst));
502 }
503 }
504
505 // A useful route must have a destination and at least either a gateway or
506 // an interface.
507 if (!*dst || (!*gw && !*dev))
508 return false;
509
510 // Fill in netlink event information.
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700511 mAction = (type == RTM_NEWROUTE) ? Action::kRouteUpdated :
512 Action::kRouteRemoved;
Lorenzo Colittid7ff7ea2014-06-11 17:37:12 +0900513 mSubsystem = strdup("net");
514 asprintf(&mParams[0], "ROUTE=%s/%d", dst, prefixLength);
515 asprintf(&mParams[1], "GATEWAY=%s", (*gw) ? gw : "");
516 asprintf(&mParams[2], "INTERFACE=%s", (*dev) ? dev : "");
517
518 return true;
519}
520
521/*
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900522 * Parse a RTM_NEWNDUSEROPT message.
523 */
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900524bool NetlinkEvent::parseNdUserOptMessage(const struct nlmsghdr *nh) {
525 struct nduseroptmsg *msg = (struct nduseroptmsg *) NLMSG_DATA(nh);
526 if (!checkRtNetlinkLength(nh, sizeof(*msg)))
527 return false;
528
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900529 // Check the length is valid.
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900530 int len = NLMSG_PAYLOAD(nh, sizeof(*msg));
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900531 if (msg->nduseropt_opts_len > len) {
532 SLOGE("RTM_NEWNDUSEROPT invalid length %d > %d\n",
533 msg->nduseropt_opts_len, len);
534 return false;
535 }
536 len = msg->nduseropt_opts_len;
537
538 // Check address family and packet type.
539 if (msg->nduseropt_family != AF_INET6) {
540 SLOGE("RTM_NEWNDUSEROPT message for unknown family %d\n",
541 msg->nduseropt_family);
542 return false;
543 }
544
545 if (msg->nduseropt_icmp_type != ND_ROUTER_ADVERT ||
546 msg->nduseropt_icmp_code != 0) {
547 SLOGE("RTM_NEWNDUSEROPT message for unknown ICMPv6 type/code %d/%d\n",
548 msg->nduseropt_icmp_type, msg->nduseropt_icmp_code);
549 return false;
550 }
551
552 // Find the interface name.
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900553 char ifname[IFNAMSIZ];
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900554 if (!if_indextoname(msg->nduseropt_ifindex, ifname)) {
555 SLOGE("RTM_NEWNDUSEROPT on unknown ifindex %d\n",
556 msg->nduseropt_ifindex);
557 return false;
558 }
559
560 // The kernel sends a separate netlink message for each ND option in the RA.
561 // So only parse the first ND option in the message.
562 struct nd_opt_hdr *opthdr = (struct nd_opt_hdr *) (msg + 1);
563
564 // The length is in multiples of 8 octets.
565 uint16_t optlen = opthdr->nd_opt_len;
566 if (optlen * 8 > len) {
567 SLOGE("Invalid option length %d > %d for ND option %d\n",
568 optlen * 8, len, opthdr->nd_opt_type);
569 return false;
570 }
571
572 if (opthdr->nd_opt_type == ND_OPT_RDNSS) {
573 // DNS Servers (RFC 6106).
574 // Each address takes up 2*8 octets, and the header takes up 8 octets.
575 // So for a valid option with one or more addresses, optlen must be
576 // odd and greater than 1.
577 if ((optlen < 3) || !(optlen & 0x1)) {
578 SLOGE("Invalid optlen %d for RDNSS option\n", optlen);
579 return false;
580 }
Erik Klineba48ff72015-06-17 15:53:29 +0900581 const int numaddrs = (optlen - 1) / 2;
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900582
583 // Find the lifetime.
584 struct nd_opt_rdnss *rndss_opt = (struct nd_opt_rdnss *) opthdr;
Erik Klineba48ff72015-06-17 15:53:29 +0900585 const uint32_t lifetime = ntohl(rndss_opt->nd_opt_rdnss_lifetime);
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900586
Lorenzo Colittid0e49382019-04-10 23:04:41 +0900587 // Construct a comma-separated string of DNS addresses.
Erik Klineba48ff72015-06-17 15:53:29 +0900588 // Reserve sufficient space for an IPv6 link-local address: all but the
589 // last address are followed by ','; the last is followed by '\0'.
Erik Klinecc451782015-07-28 17:31:19 +0900590 static const size_t kMaxSingleAddressLength =
Erik Klineba48ff72015-06-17 15:53:29 +0900591 INET6_ADDRSTRLEN + strlen("%") + IFNAMSIZ + strlen(",");
Lorenzo Colittid0e49382019-04-10 23:04:41 +0900592 const size_t bufsize = numaddrs * kMaxSingleAddressLength;
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900593 char *buf = (char *) malloc(bufsize);
594 if (!buf) {
595 SLOGE("RDNSS option: out of memory\n");
596 return false;
597 }
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900598
599 struct in6_addr *addrs = (struct in6_addr *) (rndss_opt + 1);
Lorenzo Colittid0e49382019-04-10 23:04:41 +0900600 size_t pos = 0;
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900601 for (int i = 0; i < numaddrs; i++) {
602 if (i > 0) {
603 buf[pos++] = ',';
604 }
605 inet_ntop(AF_INET6, addrs + i, buf + pos, bufsize - pos);
606 pos += strlen(buf + pos);
Erik Klineba48ff72015-06-17 15:53:29 +0900607 if (IN6_IS_ADDR_LINKLOCAL(addrs + i)) {
608 buf[pos++] = '%';
609 pos += strlcpy(buf + pos, ifname, bufsize - pos);
610 }
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900611 }
612 buf[pos] = '\0';
613
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700614 mAction = Action::kRdnss;
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900615 mSubsystem = strdup("net");
616 asprintf(&mParams[0], "INTERFACE=%s", ifname);
617 asprintf(&mParams[1], "LIFETIME=%u", lifetime);
Lorenzo Colittid0e49382019-04-10 23:04:41 +0900618 asprintf(&mParams[2], "SERVERS=%s", buf);
619 free(buf);
Lorenzo Colitticbfd65d2017-11-28 15:32:40 +0900620 } else if (opthdr->nd_opt_type == ND_OPT_DNSSL) {
621 // TODO: support DNSSL.
Maciej Żenczykowskia806a712020-03-31 19:55:06 -0700622 } else if (opthdr->nd_opt_type == ND_OPT_CAPTIVE_PORTAL) {
623 // TODO: support CAPTIVE PORTAL.
624 } else if (opthdr->nd_opt_type == ND_OPT_PREF64) {
625 // TODO: support PREF64.
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900626 } else {
627 SLOGD("Unknown ND option type %d\n", opthdr->nd_opt_type);
628 return false;
629 }
630
631 return true;
632}
633
634/*
635 * Parse a binary message from a NETLINK_ROUTE netlink socket.
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900636 *
637 * Note that this function can only parse one message, because the message's
638 * content has to be stored in the class's member variables (mAction,
639 * mSubsystem, etc.). Invalid or unrecognized messages are skipped, but if
640 * there are multiple valid messages in the buffer, only the first one will be
641 * returned.
642 *
643 * TODO: consider only ever looking at the first message.
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700644 */
645bool NetlinkEvent::parseBinaryNetlinkMessage(char *buffer, int size) {
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700646 struct nlmsghdr *nh;
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700647
Lorenzo Colitti96834562013-08-17 03:40:31 +0900648 for (nh = (struct nlmsghdr *) buffer;
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900649 NLMSG_OK(nh, (unsigned) size) && (nh->nlmsg_type != NLMSG_DONE);
Lorenzo Colitti96834562013-08-17 03:40:31 +0900650 nh = NLMSG_NEXT(nh, size)) {
JP Abgralle6f80142011-07-14 16:46:32 -0700651
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900652 if (!rtMessageName(nh->nlmsg_type)) {
653 SLOGD("Unexpected netlink message type %d\n", nh->nlmsg_type);
654 continue;
655 }
656
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700657 if (nh->nlmsg_type == RTM_NEWLINK) {
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900658 if (parseIfInfoMessage(nh))
659 return true;
JP Abgralle6f80142011-07-14 16:46:32 -0700660
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700661 } else if (nh->nlmsg_type == LOCAL_QLOG_NL_EVENT) {
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900662 if (parseUlogPacketMessage(nh))
663 return true;
JP Abgralle6f80142011-07-14 16:46:32 -0700664
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900665 } else if (nh->nlmsg_type == RTM_NEWADDR ||
666 nh->nlmsg_type == RTM_DELADDR) {
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900667 if (parseIfAddrMessage(nh))
668 return true;
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900669
Lorenzo Colittid7ff7ea2014-06-11 17:37:12 +0900670 } else if (nh->nlmsg_type == RTM_NEWROUTE ||
671 nh->nlmsg_type == RTM_DELROUTE) {
672 if (parseRtMessage(nh))
673 return true;
674
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900675 } else if (nh->nlmsg_type == RTM_NEWNDUSEROPT) {
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900676 if (parseNdUserOptMessage(nh))
677 return true;
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900678
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700679 } else if (nh->nlmsg_type == LOCAL_NFLOG_PACKET) {
680 if (parseNfPacketMessage(nh))
681 return true;
682
JP Abgralle6f80142011-07-14 16:46:32 -0700683 }
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700684 }
685
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900686 return false;
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700687}
688
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100689/* If the string between 'str' and 'end' begins with 'prefixlen' characters
690 * from the 'prefix' array, then return 'str + prefixlen', otherwise return
691 * NULL.
692 */
693static const char*
694has_prefix(const char* str, const char* end, const char* prefix, size_t prefixlen)
695{
Yunlian Jiang33f67172017-02-07 15:39:25 -0800696 if ((end - str) >= (ptrdiff_t)prefixlen &&
697 (prefixlen == 0 || !memcmp(str, prefix, prefixlen))) {
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100698 return str + prefixlen;
Yunlian Jiang33f67172017-02-07 15:39:25 -0800699 } else {
Yi Kong48885252018-07-24 16:34:27 -0700700 return nullptr;
Yunlian Jiang33f67172017-02-07 15:39:25 -0800701 }
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100702}
703
704/* Same as strlen(x) for constant string literals ONLY */
705#define CONST_STRLEN(x) (sizeof(x)-1)
706
707/* Convenience macro to call has_prefix with a constant string literal */
708#define HAS_CONST_PREFIX(str,end,prefix) has_prefix((str),(end),prefix,CONST_STRLEN(prefix))
709
710
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700711/*
712 * Parse an ASCII-formatted message from a NETLINK_KOBJECT_UEVENT
713 * netlink socket.
714 */
715bool NetlinkEvent::parseAsciiNetlinkMessage(char *buffer, int size) {
Mike J. Chen17260b12011-06-23 15:00:30 -0700716 const char *s = buffer;
717 const char *end;
San Mehat168415b2009-05-06 11:14:21 -0700718 int param_idx = 0;
San Mehat168415b2009-05-06 11:14:21 -0700719 int first = 1;
720
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100721 if (size == 0)
722 return false;
723
724 /* Ensure the buffer is zero-terminated, the code below depends on this */
725 buffer[size-1] = '\0';
726
San Mehat168415b2009-05-06 11:14:21 -0700727 end = s + size;
728 while (s < end) {
729 if (first) {
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100730 const char *p;
731 /* buffer is 0-terminated, no need to check p < end */
732 for (p = s; *p != '@'; p++) {
733 if (!*p) { /* no '@', should not happen */
734 return false;
735 }
736 }
737 mPath = strdup(p+1);
San Mehat168415b2009-05-06 11:14:21 -0700738 first = 0;
739 } else {
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100740 const char* a;
Yi Kong48885252018-07-24 16:34:27 -0700741 if ((a = HAS_CONST_PREFIX(s, end, "ACTION=")) != nullptr) {
San Mehat168415b2009-05-06 11:14:21 -0700742 if (!strcmp(a, "add"))
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700743 mAction = Action::kAdd;
San Mehat168415b2009-05-06 11:14:21 -0700744 else if (!strcmp(a, "remove"))
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700745 mAction = Action::kRemove;
San Mehat168415b2009-05-06 11:14:21 -0700746 else if (!strcmp(a, "change"))
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700747 mAction = Action::kChange;
Yi Kong48885252018-07-24 16:34:27 -0700748 } else if ((a = HAS_CONST_PREFIX(s, end, "SEQNUM=")) != nullptr) {
Lorenzo Colittid0e49382019-04-10 23:04:41 +0900749 if (!ParseInt(a, &mSeq)) {
750 SLOGE("NetlinkEvent::parseAsciiNetlinkMessage: failed to parse SEQNUM=%s", a);
751 }
Yi Kong48885252018-07-24 16:34:27 -0700752 } else if ((a = HAS_CONST_PREFIX(s, end, "SUBSYSTEM=")) != nullptr) {
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100753 mSubsystem = strdup(a);
754 } else if (param_idx < NL_PARAMS_MAX) {
San Mehat168415b2009-05-06 11:14:21 -0700755 mParams[param_idx++] = strdup(s);
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100756 }
San Mehat168415b2009-05-06 11:14:21 -0700757 }
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100758 s += strlen(s) + 1;
San Mehat168415b2009-05-06 11:14:21 -0700759 }
760 return true;
761}
762
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700763bool NetlinkEvent::decode(char *buffer, int size, int format) {
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700764 if (format == NetlinkListener::NETLINK_FORMAT_BINARY
765 || format == NetlinkListener::NETLINK_FORMAT_BINARY_UNICAST) {
Mike J. Chen17260b12011-06-23 15:00:30 -0700766 return parseBinaryNetlinkMessage(buffer, size);
767 } else {
768 return parseAsciiNetlinkMessage(buffer, size);
769 }
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700770}
771
San Mehat168415b2009-05-06 11:14:21 -0700772const char *NetlinkEvent::findParam(const char *paramName) {
Chih-Wei Huang80ec37a2010-07-14 14:00:41 +0800773 size_t len = strlen(paramName);
Yi Kong48885252018-07-24 16:34:27 -0700774 for (int i = 0; i < NL_PARAMS_MAX && mParams[i] != nullptr; ++i) {
Chih-Wei Huang80ec37a2010-07-14 14:00:41 +0800775 const char *ptr = mParams[i] + len;
776 if (!strncmp(mParams[i], paramName, len) && *ptr == '=')
777 return ++ptr;
San Mehat168415b2009-05-06 11:14:21 -0700778 }
779
San Mehat7e8529a2010-03-25 09:31:42 -0700780 SLOGE("NetlinkEvent::FindParam(): Parameter '%s' not found", paramName);
Yi Kong48885252018-07-24 16:34:27 -0700781 return nullptr;
San Mehat168415b2009-05-06 11:14:21 -0700782}
Lorenzo Colittie439ffc2017-10-03 18:44:11 +0900783
784nlattr* NetlinkEvent::findNlAttr(const nlmsghdr* nh, size_t hdrlen, uint16_t attr) {
785 if (nh == nullptr || NLMSG_HDRLEN + NLMSG_ALIGN(hdrlen) > SSIZE_MAX) {
786 return nullptr;
787 }
788
789 // Skip header, padding, and family header.
790 const ssize_t NLA_START = NLMSG_HDRLEN + NLMSG_ALIGN(hdrlen);
791 ssize_t left = nh->nlmsg_len - NLA_START;
792 uint8_t* hdr = ((uint8_t*)nh) + NLA_START;
793
794 while (left >= NLA_HDRLEN) {
795 nlattr* nla = (nlattr*)hdr;
796 if (nla->nla_type == attr) {
797 return nla;
798 }
799
800 hdr += NLA_ALIGN(nla->nla_len);
801 left -= NLA_ALIGN(nla->nla_len);
802 }
803
804 return nullptr;
805}