blob: 3340f8a45dca09dca7a2d68933bcc9543dda10f7 [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>
34#include <sys/socket.h>
35#include <sys/types.h>
Jeff Sharkey9a20e672014-10-30 14:51:59 -070036
JP Abgralle6f80142011-07-14 16:46:32 -070037/* From kernel's net/netfilter/xt_quota2.c */
Jeff Sharkey9a20e672014-10-30 14:51:59 -070038const int LOCAL_QLOG_NL_EVENT = 112;
39const int LOCAL_NFLOG_PACKET = NFNL_SUBSYS_ULOG << 8 | NFULNL_MSG_PACKET;
JP Abgralle6f80142011-07-14 16:46:32 -070040
Christopher Ferris71ac5c82019-12-09 15:10:06 -080041/* From deprecated ipt_ULOG.h to parse QLOG_NL_EVENT. */
42#define ULOG_MAC_LEN 80
43#define ULOG_PREFIX_LEN 32
44typedef struct ulog_packet_msg {
45 unsigned long mark;
46 long timestamp_sec;
47 long timestamp_usec;
48 unsigned int hook;
49 char indev_name[IFNAMSIZ];
50 char outdev_name[IFNAMSIZ];
51 size_t data_len;
52 char prefix[ULOG_PREFIX_LEN];
53 unsigned char mac_len;
54 unsigned char mac[ULOG_MAC_LEN];
55 unsigned char payload[0];
56} ulog_packet_msg_t;
57
Lorenzo Colittid0e49382019-04-10 23:04:41 +090058#include <android-base/parseint.h>
Mark Salyzyncfd5b082016-10-17 14:28:00 -070059#include <log/log.h>
Mark Salyzyn66ce3e02016-09-28 10:07:20 -070060#include <sysutils/NetlinkEvent.h>
Jeff Sharkey9a20e672014-10-30 14:51:59 -070061
Lorenzo Colittid0e49382019-04-10 23:04:41 +090062using android::base::ParseInt;
63
San Mehat168415b2009-05-06 11:14:21 -070064NetlinkEvent::NetlinkEvent() {
Jeff Sharkeye4f39402015-03-13 13:27:33 -070065 mAction = Action::kUnknown;
San Mehatebfe3db2009-10-10 17:35:13 -070066 memset(mParams, 0, sizeof(mParams));
Yi Kong48885252018-07-24 16:34:27 -070067 mPath = nullptr;
68 mSubsystem = nullptr;
San Mehat168415b2009-05-06 11:14:21 -070069}
70
71NetlinkEvent::~NetlinkEvent() {
72 int i;
73 if (mPath)
74 free(mPath);
75 if (mSubsystem)
76 free(mSubsystem);
77 for (i = 0; i < NL_PARAMS_MAX; i++) {
78 if (!mParams[i])
79 break;
80 free(mParams[i]);
81 }
82}
83
San Mehatd6744132009-12-24 07:17:09 -080084void NetlinkEvent::dump() {
85 int i;
86
87 for (i = 0; i < NL_PARAMS_MAX; i++) {
88 if (!mParams[i])
89 break;
San Mehat7e8529a2010-03-25 09:31:42 -070090 SLOGD("NL param '%s'\n", mParams[i]);
San Mehatd6744132009-12-24 07:17:09 -080091 }
92}
93
Mike J. Chenec16b9d2011-06-23 14:55:28 -070094/*
Lorenzo Colitti9b342932014-06-19 13:16:04 +090095 * Returns the message name for a message in the NETLINK_ROUTE family, or NULL
96 * if parsing that message is not supported.
97 */
98static const char *rtMessageName(int type) {
99#define NL_EVENT_RTM_NAME(rtm) case rtm: return #rtm;
100 switch (type) {
101 NL_EVENT_RTM_NAME(RTM_NEWLINK);
102 NL_EVENT_RTM_NAME(RTM_DELLINK);
103 NL_EVENT_RTM_NAME(RTM_NEWADDR);
104 NL_EVENT_RTM_NAME(RTM_DELADDR);
105 NL_EVENT_RTM_NAME(RTM_NEWROUTE);
106 NL_EVENT_RTM_NAME(RTM_DELROUTE);
107 NL_EVENT_RTM_NAME(RTM_NEWNDUSEROPT);
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700108 NL_EVENT_RTM_NAME(LOCAL_QLOG_NL_EVENT);
109 NL_EVENT_RTM_NAME(LOCAL_NFLOG_PACKET);
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900110 default:
Yi Kong48885252018-07-24 16:34:27 -0700111 return nullptr;
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900112 }
113#undef NL_EVENT_RTM_NAME
114}
115
116/*
117 * Checks that a binary NETLINK_ROUTE message is long enough for a payload of
118 * size bytes.
119 */
120static bool checkRtNetlinkLength(const struct nlmsghdr *nh, size_t size) {
121 if (nh->nlmsg_len < NLMSG_LENGTH(size)) {
122 SLOGE("Got a short %s message\n", rtMessageName(nh->nlmsg_type));
123 return false;
124 }
125 return true;
126}
127
128/*
129 * Utility function to log errors.
130 */
131static bool maybeLogDuplicateAttribute(bool isDup,
132 const char *attributeName,
133 const char *messageName) {
134 if (isDup) {
135 SLOGE("Multiple %s attributes in %s, ignoring\n", attributeName, messageName);
136 return true;
137 }
138 return false;
139}
140
141/*
142 * Parse a RTM_NEWLINK message.
143 */
144bool NetlinkEvent::parseIfInfoMessage(const struct nlmsghdr *nh) {
145 struct ifinfomsg *ifi = (struct ifinfomsg *) NLMSG_DATA(nh);
146 if (!checkRtNetlinkLength(nh, sizeof(*ifi)))
147 return false;
148
149 if ((ifi->ifi_flags & IFF_LOOPBACK) != 0) {
150 return false;
151 }
152
153 int len = IFLA_PAYLOAD(nh);
154 struct rtattr *rta;
155 for (rta = IFLA_RTA(ifi); RTA_OK(rta, len); rta = RTA_NEXT(rta, len)) {
156 switch(rta->rta_type) {
157 case IFLA_IFNAME:
158 asprintf(&mParams[0], "INTERFACE=%s", (char *) RTA_DATA(rta));
Chenbo Feng5e5e5e92018-03-02 01:32:53 -0800159 // We can get the interface change information from sysfs update
160 // already. But in case we missed those message when devices start.
161 // We do a update again when received a kLinkUp event. To make
162 // the message consistent, use IFINDEX here as well since sysfs
163 // uses IFINDEX.
164 asprintf(&mParams[1], "IFINDEX=%d", ifi->ifi_index);
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700165 mAction = (ifi->ifi_flags & IFF_LOWER_UP) ? Action::kLinkUp :
166 Action::kLinkDown;
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900167 mSubsystem = strdup("net");
168 return true;
169 }
170 }
171
172 return false;
173}
174
175/*
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900176 * Parse a RTM_NEWADDR or RTM_DELADDR message.
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900177 */
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900178bool NetlinkEvent::parseIfAddrMessage(const struct nlmsghdr *nh) {
179 struct ifaddrmsg *ifaddr = (struct ifaddrmsg *) NLMSG_DATA(nh);
Yi Kong48885252018-07-24 16:34:27 -0700180 struct ifa_cacheinfo *cacheinfo = nullptr;
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900181 char addrstr[INET6_ADDRSTRLEN] = "";
Lorenzo Colittief6454d2016-02-16 21:42:16 +0900182 char ifname[IFNAMSIZ] = "";
Lorenzo Colitti096fc532020-04-26 19:21:12 +0900183 uint32_t flags = 0;
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900184
185 if (!checkRtNetlinkLength(nh, sizeof(*ifaddr)))
186 return false;
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900187
188 // Sanity check.
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900189 int type = nh->nlmsg_type;
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900190 if (type != RTM_NEWADDR && type != RTM_DELADDR) {
191 SLOGE("parseIfAddrMessage on incorrect message type 0x%x\n", type);
192 return false;
193 }
194
195 // For log messages.
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900196 const char *msgtype = rtMessageName(type);
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900197
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900198 struct rtattr *rta;
199 int len = IFA_PAYLOAD(nh);
200 for (rta = IFA_RTA(ifaddr); RTA_OK(rta, len); rta = RTA_NEXT(rta, len)) {
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900201 if (rta->rta_type == IFA_ADDRESS) {
202 // Only look at the first address, because we only support notifying
203 // one change at a time.
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900204 if (maybeLogDuplicateAttribute(*addrstr != '\0', "IFA_ADDRESS", msgtype))
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900205 continue;
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900206
207 // Convert the IP address to a string.
208 if (ifaddr->ifa_family == AF_INET) {
209 struct in_addr *addr4 = (struct in_addr *) RTA_DATA(rta);
210 if (RTA_PAYLOAD(rta) < sizeof(*addr4)) {
Mark Salyzyn80f63d42014-05-01 07:47:04 -0700211 SLOGE("Short IPv4 address (%zu bytes) in %s",
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900212 RTA_PAYLOAD(rta), msgtype);
213 continue;
214 }
215 inet_ntop(AF_INET, addr4, addrstr, sizeof(addrstr));
216 } else if (ifaddr->ifa_family == AF_INET6) {
217 struct in6_addr *addr6 = (struct in6_addr *) RTA_DATA(rta);
218 if (RTA_PAYLOAD(rta) < sizeof(*addr6)) {
Mark Salyzyn80f63d42014-05-01 07:47:04 -0700219 SLOGE("Short IPv6 address (%zu bytes) in %s",
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900220 RTA_PAYLOAD(rta), msgtype);
221 continue;
222 }
223 inet_ntop(AF_INET6, addr6, addrstr, sizeof(addrstr));
224 } else {
225 SLOGE("Unknown address family %d\n", ifaddr->ifa_family);
226 continue;
227 }
228
229 // Find the interface name.
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900230 if (!if_indextoname(ifaddr->ifa_index, ifname)) {
Lorenzo Colittief6454d2016-02-16 21:42:16 +0900231 SLOGD("Unknown ifindex %d in %s", ifaddr->ifa_index, msgtype);
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900232 }
233
Lorenzo Colitti096fc532020-04-26 19:21:12 +0900234 // First 8 bits of flags. In practice will always be overridden by the IFA_FLAGS below,
235 // because that always appears after IFA_ADDRESS. But just in case, support both orders.
236 flags = (flags & 0xffffff00) | ifaddr->ifa_flags;
237
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900238 } else if (rta->rta_type == IFA_CACHEINFO) {
239 // Address lifetime information.
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900240 if (maybeLogDuplicateAttribute(cacheinfo, "IFA_CACHEINFO", msgtype))
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900241 continue;
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900242
243 if (RTA_PAYLOAD(rta) < sizeof(*cacheinfo)) {
Mark Salyzyn80f63d42014-05-01 07:47:04 -0700244 SLOGE("Short IFA_CACHEINFO (%zu vs. %zu bytes) in %s",
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900245 RTA_PAYLOAD(rta), sizeof(cacheinfo), msgtype);
246 continue;
247 }
248
249 cacheinfo = (struct ifa_cacheinfo *) RTA_DATA(rta);
Lorenzo Colitti096fc532020-04-26 19:21:12 +0900250
251 } else if (rta->rta_type == IFA_FLAGS) {
252 // In practice IFA_FLAGS is always after IFA_ADDRESS, so this will overwrite the flags.
253 flags = *(uint32_t*)RTA_DATA(rta);
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900254 }
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900255 }
256
257 if (addrstr[0] == '\0') {
258 SLOGE("No IFA_ADDRESS in %s\n", msgtype);
259 return false;
260 }
261
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900262 // Fill in netlink event information.
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700263 mAction = (type == RTM_NEWADDR) ? Action::kAddressUpdated :
264 Action::kAddressRemoved;
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900265 mSubsystem = strdup("net");
Lorenzo Colittief6454d2016-02-16 21:42:16 +0900266 asprintf(&mParams[0], "ADDRESS=%s/%d", addrstr, ifaddr->ifa_prefixlen);
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900267 asprintf(&mParams[1], "INTERFACE=%s", ifname);
Lorenzo Colitti096fc532020-04-26 19:21:12 +0900268 asprintf(&mParams[2], "FLAGS=%u", flags);
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900269 asprintf(&mParams[3], "SCOPE=%u", ifaddr->ifa_scope);
Rubin Xu5f406242018-05-16 23:35:41 +0100270 asprintf(&mParams[4], "IFINDEX=%u", ifaddr->ifa_index);
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900271
272 if (cacheinfo) {
Rubin Xu5f406242018-05-16 23:35:41 +0100273 asprintf(&mParams[5], "PREFERRED=%u", cacheinfo->ifa_prefered);
274 asprintf(&mParams[6], "VALID=%u", cacheinfo->ifa_valid);
275 asprintf(&mParams[7], "CSTAMP=%u", cacheinfo->cstamp);
276 asprintf(&mParams[8], "TSTAMP=%u", cacheinfo->tstamp);
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900277 }
278
279 return true;
280}
281
282/*
283 * Parse a QLOG_NL_EVENT message.
284 */
285bool NetlinkEvent::parseUlogPacketMessage(const struct nlmsghdr *nh) {
286 const char *devname;
287 ulog_packet_msg_t *pm = (ulog_packet_msg_t *) NLMSG_DATA(nh);
288 if (!checkRtNetlinkLength(nh, sizeof(*pm)))
289 return false;
290
291 devname = pm->indev_name[0] ? pm->indev_name : pm->outdev_name;
292 asprintf(&mParams[0], "ALERT_NAME=%s", pm->prefix);
293 asprintf(&mParams[1], "INTERFACE=%s", devname);
294 mSubsystem = strdup("qlog");
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700295 mAction = Action::kChange;
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900296 return true;
297}
298
Lorenzo Colittie439ffc2017-10-03 18:44:11 +0900299static size_t nlAttrLen(const nlattr* nla) {
300 return nla->nla_len - NLA_HDRLEN;
301}
302
303static const uint8_t* nlAttrData(const nlattr* nla) {
304 return reinterpret_cast<const uint8_t*>(nla) + NLA_HDRLEN;
305}
306
307static uint32_t nlAttrU32(const nlattr* nla) {
308 return *reinterpret_cast<const uint32_t*>(nlAttrData(nla));
309}
310
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900311/*
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700312 * Parse a LOCAL_NFLOG_PACKET message.
313 */
314bool NetlinkEvent::parseNfPacketMessage(struct nlmsghdr *nh) {
315 int uid = -1;
316 int len = 0;
Yi Kong48885252018-07-24 16:34:27 -0700317 char* raw = nullptr;
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700318
Lorenzo Colittie439ffc2017-10-03 18:44:11 +0900319 struct nlattr* uid_attr = findNlAttr(nh, sizeof(struct genlmsghdr), NFULA_UID);
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700320 if (uid_attr) {
Lorenzo Colittie439ffc2017-10-03 18:44:11 +0900321 uid = ntohl(nlAttrU32(uid_attr));
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700322 }
323
Lorenzo Colittie439ffc2017-10-03 18:44:11 +0900324 struct nlattr* payload = findNlAttr(nh, sizeof(struct genlmsghdr), NFULA_PAYLOAD);
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700325 if (payload) {
326 /* First 256 bytes is plenty */
Lorenzo Colittie439ffc2017-10-03 18:44:11 +0900327 len = nlAttrLen(payload);
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700328 if (len > 256) len = 256;
Lorenzo Colittie439ffc2017-10-03 18:44:11 +0900329 raw = (char*)nlAttrData(payload);
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700330 }
331
Lorenzo Colittid0e49382019-04-10 23:04:41 +0900332 size_t hexSize = 5 + (len * 2);
333 char* hex = (char*)calloc(1, hexSize);
334 strlcpy(hex, "HEX=", hexSize);
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700335 for (int i = 0; i < len; i++) {
336 hex[4 + (i * 2)] = "0123456789abcdef"[(raw[i] >> 4) & 0xf];
337 hex[5 + (i * 2)] = "0123456789abcdef"[raw[i] & 0xf];
338 }
339
340 asprintf(&mParams[0], "UID=%d", uid);
341 mParams[1] = hex;
342 mSubsystem = strdup("strict");
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700343 mAction = Action::kChange;
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700344 return true;
345}
346
347/*
Lorenzo Colittid7ff7ea2014-06-11 17:37:12 +0900348 * Parse a RTM_NEWROUTE or RTM_DELROUTE message.
349 */
350bool NetlinkEvent::parseRtMessage(const struct nlmsghdr *nh) {
351 uint8_t type = nh->nlmsg_type;
352 const char *msgname = rtMessageName(type);
353
354 // Sanity check.
355 if (type != RTM_NEWROUTE && type != RTM_DELROUTE) {
356 SLOGE("%s: incorrect message type %d (%s)\n", __func__, type, msgname);
357 return false;
358 }
359
360 struct rtmsg *rtm = (struct rtmsg *) NLMSG_DATA(nh);
361 if (!checkRtNetlinkLength(nh, sizeof(*rtm)))
362 return false;
363
364 if (// Ignore static routes we've set up ourselves.
365 (rtm->rtm_protocol != RTPROT_KERNEL &&
366 rtm->rtm_protocol != RTPROT_RA) ||
367 // We're only interested in global unicast routes.
368 (rtm->rtm_scope != RT_SCOPE_UNIVERSE) ||
369 (rtm->rtm_type != RTN_UNICAST) ||
370 // We don't support source routing.
371 (rtm->rtm_src_len != 0) ||
372 // Cloned routes aren't real routes.
373 (rtm->rtm_flags & RTM_F_CLONED)) {
374 return false;
375 }
376
377 int family = rtm->rtm_family;
378 int prefixLength = rtm->rtm_dst_len;
379
380 // Currently we only support: destination, (one) next hop, ifindex.
381 char dst[INET6_ADDRSTRLEN] = "";
382 char gw[INET6_ADDRSTRLEN] = "";
383 char dev[IFNAMSIZ] = "";
384
385 size_t len = RTM_PAYLOAD(nh);
386 struct rtattr *rta;
387 for (rta = RTM_RTA(rtm); RTA_OK(rta, len); rta = RTA_NEXT(rta, len)) {
388 switch (rta->rta_type) {
389 case RTA_DST:
390 if (maybeLogDuplicateAttribute(*dst, "RTA_DST", msgname))
391 continue;
392 if (!inet_ntop(family, RTA_DATA(rta), dst, sizeof(dst)))
393 return false;
394 continue;
395 case RTA_GATEWAY:
396 if (maybeLogDuplicateAttribute(*gw, "RTA_GATEWAY", msgname))
397 continue;
398 if (!inet_ntop(family, RTA_DATA(rta), gw, sizeof(gw)))
399 return false;
400 continue;
401 case RTA_OIF:
402 if (maybeLogDuplicateAttribute(*dev, "RTA_OIF", msgname))
403 continue;
404 if (!if_indextoname(* (int *) RTA_DATA(rta), dev))
405 return false;
Chih-Hung Hsiehe6e2b3c2018-10-10 14:39:02 -0700406 continue;
Lorenzo Colittid7ff7ea2014-06-11 17:37:12 +0900407 default:
408 continue;
409 }
410 }
411
412 // If there's no RTA_DST attribute, then:
413 // - If the prefix length is zero, it's the default route.
414 // - If the prefix length is nonzero, there's something we don't understand.
415 // Ignore the event.
416 if (!*dst && !prefixLength) {
417 if (family == AF_INET) {
418 strncpy(dst, "0.0.0.0", sizeof(dst));
419 } else if (family == AF_INET6) {
420 strncpy(dst, "::", sizeof(dst));
421 }
422 }
423
424 // A useful route must have a destination and at least either a gateway or
425 // an interface.
426 if (!*dst || (!*gw && !*dev))
427 return false;
428
429 // Fill in netlink event information.
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700430 mAction = (type == RTM_NEWROUTE) ? Action::kRouteUpdated :
431 Action::kRouteRemoved;
Lorenzo Colittid7ff7ea2014-06-11 17:37:12 +0900432 mSubsystem = strdup("net");
433 asprintf(&mParams[0], "ROUTE=%s/%d", dst, prefixLength);
434 asprintf(&mParams[1], "GATEWAY=%s", (*gw) ? gw : "");
435 asprintf(&mParams[2], "INTERFACE=%s", (*dev) ? dev : "");
436
437 return true;
438}
439
440/*
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900441 * Parse a RTM_NEWNDUSEROPT message.
442 */
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900443bool NetlinkEvent::parseNdUserOptMessage(const struct nlmsghdr *nh) {
444 struct nduseroptmsg *msg = (struct nduseroptmsg *) NLMSG_DATA(nh);
445 if (!checkRtNetlinkLength(nh, sizeof(*msg)))
446 return false;
447
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900448 // Check the length is valid.
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900449 int len = NLMSG_PAYLOAD(nh, sizeof(*msg));
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900450 if (msg->nduseropt_opts_len > len) {
451 SLOGE("RTM_NEWNDUSEROPT invalid length %d > %d\n",
452 msg->nduseropt_opts_len, len);
453 return false;
454 }
455 len = msg->nduseropt_opts_len;
456
457 // Check address family and packet type.
458 if (msg->nduseropt_family != AF_INET6) {
459 SLOGE("RTM_NEWNDUSEROPT message for unknown family %d\n",
460 msg->nduseropt_family);
461 return false;
462 }
463
464 if (msg->nduseropt_icmp_type != ND_ROUTER_ADVERT ||
465 msg->nduseropt_icmp_code != 0) {
466 SLOGE("RTM_NEWNDUSEROPT message for unknown ICMPv6 type/code %d/%d\n",
467 msg->nduseropt_icmp_type, msg->nduseropt_icmp_code);
468 return false;
469 }
470
471 // Find the interface name.
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900472 char ifname[IFNAMSIZ];
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900473 if (!if_indextoname(msg->nduseropt_ifindex, ifname)) {
474 SLOGE("RTM_NEWNDUSEROPT on unknown ifindex %d\n",
475 msg->nduseropt_ifindex);
476 return false;
477 }
478
479 // The kernel sends a separate netlink message for each ND option in the RA.
480 // So only parse the first ND option in the message.
481 struct nd_opt_hdr *opthdr = (struct nd_opt_hdr *) (msg + 1);
482
483 // The length is in multiples of 8 octets.
484 uint16_t optlen = opthdr->nd_opt_len;
485 if (optlen * 8 > len) {
486 SLOGE("Invalid option length %d > %d for ND option %d\n",
487 optlen * 8, len, opthdr->nd_opt_type);
488 return false;
489 }
490
491 if (opthdr->nd_opt_type == ND_OPT_RDNSS) {
492 // DNS Servers (RFC 6106).
493 // Each address takes up 2*8 octets, and the header takes up 8 octets.
494 // So for a valid option with one or more addresses, optlen must be
495 // odd and greater than 1.
496 if ((optlen < 3) || !(optlen & 0x1)) {
497 SLOGE("Invalid optlen %d for RDNSS option\n", optlen);
498 return false;
499 }
Erik Klineba48ff72015-06-17 15:53:29 +0900500 const int numaddrs = (optlen - 1) / 2;
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900501
502 // Find the lifetime.
503 struct nd_opt_rdnss *rndss_opt = (struct nd_opt_rdnss *) opthdr;
Erik Klineba48ff72015-06-17 15:53:29 +0900504 const uint32_t lifetime = ntohl(rndss_opt->nd_opt_rdnss_lifetime);
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900505
Lorenzo Colittid0e49382019-04-10 23:04:41 +0900506 // Construct a comma-separated string of DNS addresses.
Erik Klineba48ff72015-06-17 15:53:29 +0900507 // Reserve sufficient space for an IPv6 link-local address: all but the
508 // last address are followed by ','; the last is followed by '\0'.
Erik Klinecc451782015-07-28 17:31:19 +0900509 static const size_t kMaxSingleAddressLength =
Erik Klineba48ff72015-06-17 15:53:29 +0900510 INET6_ADDRSTRLEN + strlen("%") + IFNAMSIZ + strlen(",");
Lorenzo Colittid0e49382019-04-10 23:04:41 +0900511 const size_t bufsize = numaddrs * kMaxSingleAddressLength;
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900512 char *buf = (char *) malloc(bufsize);
513 if (!buf) {
514 SLOGE("RDNSS option: out of memory\n");
515 return false;
516 }
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900517
518 struct in6_addr *addrs = (struct in6_addr *) (rndss_opt + 1);
Lorenzo Colittid0e49382019-04-10 23:04:41 +0900519 size_t pos = 0;
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900520 for (int i = 0; i < numaddrs; i++) {
521 if (i > 0) {
522 buf[pos++] = ',';
523 }
524 inet_ntop(AF_INET6, addrs + i, buf + pos, bufsize - pos);
525 pos += strlen(buf + pos);
Erik Klineba48ff72015-06-17 15:53:29 +0900526 if (IN6_IS_ADDR_LINKLOCAL(addrs + i)) {
527 buf[pos++] = '%';
528 pos += strlcpy(buf + pos, ifname, bufsize - pos);
529 }
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900530 }
531 buf[pos] = '\0';
532
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700533 mAction = Action::kRdnss;
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900534 mSubsystem = strdup("net");
535 asprintf(&mParams[0], "INTERFACE=%s", ifname);
536 asprintf(&mParams[1], "LIFETIME=%u", lifetime);
Lorenzo Colittid0e49382019-04-10 23:04:41 +0900537 asprintf(&mParams[2], "SERVERS=%s", buf);
538 free(buf);
Lorenzo Colitticbfd65d2017-11-28 15:32:40 +0900539 } else if (opthdr->nd_opt_type == ND_OPT_DNSSL) {
540 // TODO: support DNSSL.
Maciej Żenczykowskia806a712020-03-31 19:55:06 -0700541 } else if (opthdr->nd_opt_type == ND_OPT_CAPTIVE_PORTAL) {
542 // TODO: support CAPTIVE PORTAL.
543 } else if (opthdr->nd_opt_type == ND_OPT_PREF64) {
544 // TODO: support PREF64.
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900545 } else {
546 SLOGD("Unknown ND option type %d\n", opthdr->nd_opt_type);
547 return false;
548 }
549
550 return true;
551}
552
553/*
554 * Parse a binary message from a NETLINK_ROUTE netlink socket.
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900555 *
556 * Note that this function can only parse one message, because the message's
557 * content has to be stored in the class's member variables (mAction,
558 * mSubsystem, etc.). Invalid or unrecognized messages are skipped, but if
559 * there are multiple valid messages in the buffer, only the first one will be
560 * returned.
561 *
562 * TODO: consider only ever looking at the first message.
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700563 */
564bool NetlinkEvent::parseBinaryNetlinkMessage(char *buffer, int size) {
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700565 struct nlmsghdr *nh;
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700566
Lorenzo Colitti96834562013-08-17 03:40:31 +0900567 for (nh = (struct nlmsghdr *) buffer;
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900568 NLMSG_OK(nh, (unsigned) size) && (nh->nlmsg_type != NLMSG_DONE);
Lorenzo Colitti96834562013-08-17 03:40:31 +0900569 nh = NLMSG_NEXT(nh, size)) {
JP Abgralle6f80142011-07-14 16:46:32 -0700570
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900571 if (!rtMessageName(nh->nlmsg_type)) {
572 SLOGD("Unexpected netlink message type %d\n", nh->nlmsg_type);
573 continue;
574 }
575
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700576 if (nh->nlmsg_type == RTM_NEWLINK) {
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900577 if (parseIfInfoMessage(nh))
578 return true;
JP Abgralle6f80142011-07-14 16:46:32 -0700579
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700580 } else if (nh->nlmsg_type == LOCAL_QLOG_NL_EVENT) {
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900581 if (parseUlogPacketMessage(nh))
582 return true;
JP Abgralle6f80142011-07-14 16:46:32 -0700583
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900584 } else if (nh->nlmsg_type == RTM_NEWADDR ||
585 nh->nlmsg_type == RTM_DELADDR) {
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900586 if (parseIfAddrMessage(nh))
587 return true;
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900588
Lorenzo Colittid7ff7ea2014-06-11 17:37:12 +0900589 } else if (nh->nlmsg_type == RTM_NEWROUTE ||
590 nh->nlmsg_type == RTM_DELROUTE) {
591 if (parseRtMessage(nh))
592 return true;
593
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900594 } else if (nh->nlmsg_type == RTM_NEWNDUSEROPT) {
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900595 if (parseNdUserOptMessage(nh))
596 return true;
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900597
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700598 } else if (nh->nlmsg_type == LOCAL_NFLOG_PACKET) {
599 if (parseNfPacketMessage(nh))
600 return true;
601
JP Abgralle6f80142011-07-14 16:46:32 -0700602 }
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700603 }
604
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900605 return false;
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700606}
607
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100608/* If the string between 'str' and 'end' begins with 'prefixlen' characters
609 * from the 'prefix' array, then return 'str + prefixlen', otherwise return
610 * NULL.
611 */
612static const char*
613has_prefix(const char* str, const char* end, const char* prefix, size_t prefixlen)
614{
Yunlian Jiang33f67172017-02-07 15:39:25 -0800615 if ((end - str) >= (ptrdiff_t)prefixlen &&
616 (prefixlen == 0 || !memcmp(str, prefix, prefixlen))) {
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100617 return str + prefixlen;
Yunlian Jiang33f67172017-02-07 15:39:25 -0800618 } else {
Yi Kong48885252018-07-24 16:34:27 -0700619 return nullptr;
Yunlian Jiang33f67172017-02-07 15:39:25 -0800620 }
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100621}
622
623/* Same as strlen(x) for constant string literals ONLY */
624#define CONST_STRLEN(x) (sizeof(x)-1)
625
626/* Convenience macro to call has_prefix with a constant string literal */
627#define HAS_CONST_PREFIX(str,end,prefix) has_prefix((str),(end),prefix,CONST_STRLEN(prefix))
628
629
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700630/*
631 * Parse an ASCII-formatted message from a NETLINK_KOBJECT_UEVENT
632 * netlink socket.
633 */
634bool NetlinkEvent::parseAsciiNetlinkMessage(char *buffer, int size) {
Mike J. Chen17260b12011-06-23 15:00:30 -0700635 const char *s = buffer;
636 const char *end;
San Mehat168415b2009-05-06 11:14:21 -0700637 int param_idx = 0;
San Mehat168415b2009-05-06 11:14:21 -0700638 int first = 1;
639
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100640 if (size == 0)
641 return false;
642
643 /* Ensure the buffer is zero-terminated, the code below depends on this */
644 buffer[size-1] = '\0';
645
San Mehat168415b2009-05-06 11:14:21 -0700646 end = s + size;
647 while (s < end) {
648 if (first) {
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100649 const char *p;
650 /* buffer is 0-terminated, no need to check p < end */
651 for (p = s; *p != '@'; p++) {
652 if (!*p) { /* no '@', should not happen */
653 return false;
654 }
655 }
656 mPath = strdup(p+1);
San Mehat168415b2009-05-06 11:14:21 -0700657 first = 0;
658 } else {
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100659 const char* a;
Yi Kong48885252018-07-24 16:34:27 -0700660 if ((a = HAS_CONST_PREFIX(s, end, "ACTION=")) != nullptr) {
San Mehat168415b2009-05-06 11:14:21 -0700661 if (!strcmp(a, "add"))
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700662 mAction = Action::kAdd;
San Mehat168415b2009-05-06 11:14:21 -0700663 else if (!strcmp(a, "remove"))
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700664 mAction = Action::kRemove;
San Mehat168415b2009-05-06 11:14:21 -0700665 else if (!strcmp(a, "change"))
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700666 mAction = Action::kChange;
Yi Kong48885252018-07-24 16:34:27 -0700667 } else if ((a = HAS_CONST_PREFIX(s, end, "SEQNUM=")) != nullptr) {
Lorenzo Colittid0e49382019-04-10 23:04:41 +0900668 if (!ParseInt(a, &mSeq)) {
669 SLOGE("NetlinkEvent::parseAsciiNetlinkMessage: failed to parse SEQNUM=%s", a);
670 }
Yi Kong48885252018-07-24 16:34:27 -0700671 } else if ((a = HAS_CONST_PREFIX(s, end, "SUBSYSTEM=")) != nullptr) {
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100672 mSubsystem = strdup(a);
673 } else if (param_idx < NL_PARAMS_MAX) {
San Mehat168415b2009-05-06 11:14:21 -0700674 mParams[param_idx++] = strdup(s);
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100675 }
San Mehat168415b2009-05-06 11:14:21 -0700676 }
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100677 s += strlen(s) + 1;
San Mehat168415b2009-05-06 11:14:21 -0700678 }
679 return true;
680}
681
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700682bool NetlinkEvent::decode(char *buffer, int size, int format) {
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700683 if (format == NetlinkListener::NETLINK_FORMAT_BINARY
684 || format == NetlinkListener::NETLINK_FORMAT_BINARY_UNICAST) {
Mike J. Chen17260b12011-06-23 15:00:30 -0700685 return parseBinaryNetlinkMessage(buffer, size);
686 } else {
687 return parseAsciiNetlinkMessage(buffer, size);
688 }
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700689}
690
San Mehat168415b2009-05-06 11:14:21 -0700691const char *NetlinkEvent::findParam(const char *paramName) {
Chih-Wei Huang80ec37a2010-07-14 14:00:41 +0800692 size_t len = strlen(paramName);
Yi Kong48885252018-07-24 16:34:27 -0700693 for (int i = 0; i < NL_PARAMS_MAX && mParams[i] != nullptr; ++i) {
Chih-Wei Huang80ec37a2010-07-14 14:00:41 +0800694 const char *ptr = mParams[i] + len;
695 if (!strncmp(mParams[i], paramName, len) && *ptr == '=')
696 return ++ptr;
San Mehat168415b2009-05-06 11:14:21 -0700697 }
698
San Mehat7e8529a2010-03-25 09:31:42 -0700699 SLOGE("NetlinkEvent::FindParam(): Parameter '%s' not found", paramName);
Yi Kong48885252018-07-24 16:34:27 -0700700 return nullptr;
San Mehat168415b2009-05-06 11:14:21 -0700701}
Lorenzo Colittie439ffc2017-10-03 18:44:11 +0900702
703nlattr* NetlinkEvent::findNlAttr(const nlmsghdr* nh, size_t hdrlen, uint16_t attr) {
704 if (nh == nullptr || NLMSG_HDRLEN + NLMSG_ALIGN(hdrlen) > SSIZE_MAX) {
705 return nullptr;
706 }
707
708 // Skip header, padding, and family header.
709 const ssize_t NLA_START = NLMSG_HDRLEN + NLMSG_ALIGN(hdrlen);
710 ssize_t left = nh->nlmsg_len - NLA_START;
711 uint8_t* hdr = ((uint8_t*)nh) + NLA_START;
712
713 while (left >= NLA_HDRLEN) {
714 nlattr* nla = (nlattr*)hdr;
715 if (nla->nla_type == attr) {
716 return nla;
717 }
718
719 hdr += NLA_ALIGN(nla->nla_len);
720 left -= NLA_ALIGN(nla->nla_len);
721 }
722
723 return nullptr;
724}