blob: 7f92904f2252edc535b98d8f8fd9f80246d31c01 [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>
JP Abgralle6f80142011-07-14 16:46:32 -070027#include <linux/netfilter_ipv4/ipt_ULOG.h>
Mark Salyzyn66ce3e02016-09-28 10:07:20 -070028#include <linux/netlink.h>
29#include <linux/rtnetlink.h>
30#include <net/if.h>
Mark Salyzyn66ce3e02016-09-28 10:07:20 -070031#include <netinet/icmp6.h>
Lorenzo Colittie439ffc2017-10-03 18:44:11 +090032#include <netinet/in.h>
Mark Salyzyn66ce3e02016-09-28 10:07:20 -070033#include <stdlib.h>
34#include <string.h>
35#include <sys/socket.h>
36#include <sys/types.h>
Jeff Sharkey9a20e672014-10-30 14:51:59 -070037
JP Abgralle6f80142011-07-14 16:46:32 -070038/* From kernel's net/netfilter/xt_quota2.c */
Jeff Sharkey9a20e672014-10-30 14:51:59 -070039const int LOCAL_QLOG_NL_EVENT = 112;
40const int LOCAL_NFLOG_PACKET = NFNL_SUBSYS_ULOG << 8 | NFULNL_MSG_PACKET;
JP Abgralle6f80142011-07-14 16:46:32 -070041
Mark Salyzyncfd5b082016-10-17 14:28:00 -070042#include <log/log.h>
Mark Salyzyn66ce3e02016-09-28 10:07:20 -070043#include <sysutils/NetlinkEvent.h>
Jeff Sharkey9a20e672014-10-30 14:51:59 -070044
San Mehat168415b2009-05-06 11:14:21 -070045NetlinkEvent::NetlinkEvent() {
Jeff Sharkeye4f39402015-03-13 13:27:33 -070046 mAction = Action::kUnknown;
San Mehatebfe3db2009-10-10 17:35:13 -070047 memset(mParams, 0, sizeof(mParams));
48 mPath = NULL;
49 mSubsystem = NULL;
San Mehat168415b2009-05-06 11:14:21 -070050}
51
52NetlinkEvent::~NetlinkEvent() {
53 int i;
54 if (mPath)
55 free(mPath);
56 if (mSubsystem)
57 free(mSubsystem);
58 for (i = 0; i < NL_PARAMS_MAX; i++) {
59 if (!mParams[i])
60 break;
61 free(mParams[i]);
62 }
63}
64
San Mehatd6744132009-12-24 07:17:09 -080065void NetlinkEvent::dump() {
66 int i;
67
68 for (i = 0; i < NL_PARAMS_MAX; i++) {
69 if (!mParams[i])
70 break;
San Mehat7e8529a2010-03-25 09:31:42 -070071 SLOGD("NL param '%s'\n", mParams[i]);
San Mehatd6744132009-12-24 07:17:09 -080072 }
73}
74
Mike J. Chenec16b9d2011-06-23 14:55:28 -070075/*
Lorenzo Colitti9b342932014-06-19 13:16:04 +090076 * Returns the message name for a message in the NETLINK_ROUTE family, or NULL
77 * if parsing that message is not supported.
78 */
79static const char *rtMessageName(int type) {
80#define NL_EVENT_RTM_NAME(rtm) case rtm: return #rtm;
81 switch (type) {
82 NL_EVENT_RTM_NAME(RTM_NEWLINK);
83 NL_EVENT_RTM_NAME(RTM_DELLINK);
84 NL_EVENT_RTM_NAME(RTM_NEWADDR);
85 NL_EVENT_RTM_NAME(RTM_DELADDR);
86 NL_EVENT_RTM_NAME(RTM_NEWROUTE);
87 NL_EVENT_RTM_NAME(RTM_DELROUTE);
88 NL_EVENT_RTM_NAME(RTM_NEWNDUSEROPT);
Jeff Sharkey9a20e672014-10-30 14:51:59 -070089 NL_EVENT_RTM_NAME(LOCAL_QLOG_NL_EVENT);
90 NL_EVENT_RTM_NAME(LOCAL_NFLOG_PACKET);
Lorenzo Colitti9b342932014-06-19 13:16:04 +090091 default:
92 return NULL;
93 }
94#undef NL_EVENT_RTM_NAME
95}
96
97/*
98 * Checks that a binary NETLINK_ROUTE message is long enough for a payload of
99 * size bytes.
100 */
101static bool checkRtNetlinkLength(const struct nlmsghdr *nh, size_t size) {
102 if (nh->nlmsg_len < NLMSG_LENGTH(size)) {
103 SLOGE("Got a short %s message\n", rtMessageName(nh->nlmsg_type));
104 return false;
105 }
106 return true;
107}
108
109/*
110 * Utility function to log errors.
111 */
112static bool maybeLogDuplicateAttribute(bool isDup,
113 const char *attributeName,
114 const char *messageName) {
115 if (isDup) {
116 SLOGE("Multiple %s attributes in %s, ignoring\n", attributeName, messageName);
117 return true;
118 }
119 return false;
120}
121
122/*
123 * Parse a RTM_NEWLINK message.
124 */
125bool NetlinkEvent::parseIfInfoMessage(const struct nlmsghdr *nh) {
126 struct ifinfomsg *ifi = (struct ifinfomsg *) NLMSG_DATA(nh);
127 if (!checkRtNetlinkLength(nh, sizeof(*ifi)))
128 return false;
129
130 if ((ifi->ifi_flags & IFF_LOOPBACK) != 0) {
131 return false;
132 }
133
134 int len = IFLA_PAYLOAD(nh);
135 struct rtattr *rta;
136 for (rta = IFLA_RTA(ifi); RTA_OK(rta, len); rta = RTA_NEXT(rta, len)) {
137 switch(rta->rta_type) {
138 case IFLA_IFNAME:
139 asprintf(&mParams[0], "INTERFACE=%s", (char *) RTA_DATA(rta));
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700140 mAction = (ifi->ifi_flags & IFF_LOWER_UP) ? Action::kLinkUp :
141 Action::kLinkDown;
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900142 mSubsystem = strdup("net");
143 return true;
144 }
145 }
146
147 return false;
148}
149
150/*
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900151 * Parse a RTM_NEWADDR or RTM_DELADDR message.
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900152 */
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900153bool NetlinkEvent::parseIfAddrMessage(const struct nlmsghdr *nh) {
154 struct ifaddrmsg *ifaddr = (struct ifaddrmsg *) NLMSG_DATA(nh);
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900155 struct ifa_cacheinfo *cacheinfo = NULL;
156 char addrstr[INET6_ADDRSTRLEN] = "";
Lorenzo Colittief6454d2016-02-16 21:42:16 +0900157 char ifname[IFNAMSIZ] = "";
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900158
159 if (!checkRtNetlinkLength(nh, sizeof(*ifaddr)))
160 return false;
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900161
162 // Sanity check.
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900163 int type = nh->nlmsg_type;
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900164 if (type != RTM_NEWADDR && type != RTM_DELADDR) {
165 SLOGE("parseIfAddrMessage on incorrect message type 0x%x\n", type);
166 return false;
167 }
168
169 // For log messages.
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900170 const char *msgtype = rtMessageName(type);
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900171
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900172 struct rtattr *rta;
173 int len = IFA_PAYLOAD(nh);
174 for (rta = IFA_RTA(ifaddr); RTA_OK(rta, len); rta = RTA_NEXT(rta, len)) {
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900175 if (rta->rta_type == IFA_ADDRESS) {
176 // Only look at the first address, because we only support notifying
177 // one change at a time.
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900178 if (maybeLogDuplicateAttribute(*addrstr != '\0', "IFA_ADDRESS", msgtype))
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900179 continue;
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900180
181 // Convert the IP address to a string.
182 if (ifaddr->ifa_family == AF_INET) {
183 struct in_addr *addr4 = (struct in_addr *) RTA_DATA(rta);
184 if (RTA_PAYLOAD(rta) < sizeof(*addr4)) {
Mark Salyzyn80f63d42014-05-01 07:47:04 -0700185 SLOGE("Short IPv4 address (%zu bytes) in %s",
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900186 RTA_PAYLOAD(rta), msgtype);
187 continue;
188 }
189 inet_ntop(AF_INET, addr4, addrstr, sizeof(addrstr));
190 } else if (ifaddr->ifa_family == AF_INET6) {
191 struct in6_addr *addr6 = (struct in6_addr *) RTA_DATA(rta);
192 if (RTA_PAYLOAD(rta) < sizeof(*addr6)) {
Mark Salyzyn80f63d42014-05-01 07:47:04 -0700193 SLOGE("Short IPv6 address (%zu bytes) in %s",
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900194 RTA_PAYLOAD(rta), msgtype);
195 continue;
196 }
197 inet_ntop(AF_INET6, addr6, addrstr, sizeof(addrstr));
198 } else {
199 SLOGE("Unknown address family %d\n", ifaddr->ifa_family);
200 continue;
201 }
202
203 // Find the interface name.
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900204 if (!if_indextoname(ifaddr->ifa_index, ifname)) {
Lorenzo Colittief6454d2016-02-16 21:42:16 +0900205 SLOGD("Unknown ifindex %d in %s", ifaddr->ifa_index, msgtype);
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900206 }
207
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900208 } else if (rta->rta_type == IFA_CACHEINFO) {
209 // Address lifetime information.
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900210 if (maybeLogDuplicateAttribute(cacheinfo, "IFA_CACHEINFO", msgtype))
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900211 continue;
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900212
213 if (RTA_PAYLOAD(rta) < sizeof(*cacheinfo)) {
Mark Salyzyn80f63d42014-05-01 07:47:04 -0700214 SLOGE("Short IFA_CACHEINFO (%zu vs. %zu bytes) in %s",
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900215 RTA_PAYLOAD(rta), sizeof(cacheinfo), msgtype);
216 continue;
217 }
218
219 cacheinfo = (struct ifa_cacheinfo *) RTA_DATA(rta);
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900220 }
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900221 }
222
223 if (addrstr[0] == '\0') {
224 SLOGE("No IFA_ADDRESS in %s\n", msgtype);
225 return false;
226 }
227
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900228 // Fill in netlink event information.
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700229 mAction = (type == RTM_NEWADDR) ? Action::kAddressUpdated :
230 Action::kAddressRemoved;
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900231 mSubsystem = strdup("net");
Lorenzo Colittief6454d2016-02-16 21:42:16 +0900232 asprintf(&mParams[0], "ADDRESS=%s/%d", addrstr, ifaddr->ifa_prefixlen);
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900233 asprintf(&mParams[1], "INTERFACE=%s", ifname);
234 asprintf(&mParams[2], "FLAGS=%u", ifaddr->ifa_flags);
235 asprintf(&mParams[3], "SCOPE=%u", ifaddr->ifa_scope);
236
237 if (cacheinfo) {
238 asprintf(&mParams[4], "PREFERRED=%u", cacheinfo->ifa_prefered);
239 asprintf(&mParams[5], "VALID=%u", cacheinfo->ifa_valid);
240 asprintf(&mParams[6], "CSTAMP=%u", cacheinfo->cstamp);
241 asprintf(&mParams[7], "TSTAMP=%u", cacheinfo->tstamp);
242 }
243
244 return true;
245}
246
247/*
248 * Parse a QLOG_NL_EVENT message.
249 */
250bool NetlinkEvent::parseUlogPacketMessage(const struct nlmsghdr *nh) {
251 const char *devname;
252 ulog_packet_msg_t *pm = (ulog_packet_msg_t *) NLMSG_DATA(nh);
253 if (!checkRtNetlinkLength(nh, sizeof(*pm)))
254 return false;
255
256 devname = pm->indev_name[0] ? pm->indev_name : pm->outdev_name;
257 asprintf(&mParams[0], "ALERT_NAME=%s", pm->prefix);
258 asprintf(&mParams[1], "INTERFACE=%s", devname);
259 mSubsystem = strdup("qlog");
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700260 mAction = Action::kChange;
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900261 return true;
262}
263
Lorenzo Colittie439ffc2017-10-03 18:44:11 +0900264static size_t nlAttrLen(const nlattr* nla) {
265 return nla->nla_len - NLA_HDRLEN;
266}
267
268static const uint8_t* nlAttrData(const nlattr* nla) {
269 return reinterpret_cast<const uint8_t*>(nla) + NLA_HDRLEN;
270}
271
272static uint32_t nlAttrU32(const nlattr* nla) {
273 return *reinterpret_cast<const uint32_t*>(nlAttrData(nla));
274}
275
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900276/*
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700277 * Parse a LOCAL_NFLOG_PACKET message.
278 */
279bool NetlinkEvent::parseNfPacketMessage(struct nlmsghdr *nh) {
280 int uid = -1;
281 int len = 0;
282 char* raw = NULL;
283
Lorenzo Colittie439ffc2017-10-03 18:44:11 +0900284 struct nlattr* uid_attr = findNlAttr(nh, sizeof(struct genlmsghdr), NFULA_UID);
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700285 if (uid_attr) {
Lorenzo Colittie439ffc2017-10-03 18:44:11 +0900286 uid = ntohl(nlAttrU32(uid_attr));
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700287 }
288
Lorenzo Colittie439ffc2017-10-03 18:44:11 +0900289 struct nlattr* payload = findNlAttr(nh, sizeof(struct genlmsghdr), NFULA_PAYLOAD);
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700290 if (payload) {
291 /* First 256 bytes is plenty */
Lorenzo Colittie439ffc2017-10-03 18:44:11 +0900292 len = nlAttrLen(payload);
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700293 if (len > 256) len = 256;
Lorenzo Colittie439ffc2017-10-03 18:44:11 +0900294 raw = (char*)nlAttrData(payload);
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700295 }
296
297 char* hex = (char*) calloc(1, 5 + (len * 2));
298 strcpy(hex, "HEX=");
299 for (int i = 0; i < len; i++) {
300 hex[4 + (i * 2)] = "0123456789abcdef"[(raw[i] >> 4) & 0xf];
301 hex[5 + (i * 2)] = "0123456789abcdef"[raw[i] & 0xf];
302 }
303
304 asprintf(&mParams[0], "UID=%d", uid);
305 mParams[1] = hex;
306 mSubsystem = strdup("strict");
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700307 mAction = Action::kChange;
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700308 return true;
309}
310
311/*
Lorenzo Colittid7ff7ea2014-06-11 17:37:12 +0900312 * Parse a RTM_NEWROUTE or RTM_DELROUTE message.
313 */
314bool NetlinkEvent::parseRtMessage(const struct nlmsghdr *nh) {
315 uint8_t type = nh->nlmsg_type;
316 const char *msgname = rtMessageName(type);
317
318 // Sanity check.
319 if (type != RTM_NEWROUTE && type != RTM_DELROUTE) {
320 SLOGE("%s: incorrect message type %d (%s)\n", __func__, type, msgname);
321 return false;
322 }
323
324 struct rtmsg *rtm = (struct rtmsg *) NLMSG_DATA(nh);
325 if (!checkRtNetlinkLength(nh, sizeof(*rtm)))
326 return false;
327
328 if (// Ignore static routes we've set up ourselves.
329 (rtm->rtm_protocol != RTPROT_KERNEL &&
330 rtm->rtm_protocol != RTPROT_RA) ||
331 // We're only interested in global unicast routes.
332 (rtm->rtm_scope != RT_SCOPE_UNIVERSE) ||
333 (rtm->rtm_type != RTN_UNICAST) ||
334 // We don't support source routing.
335 (rtm->rtm_src_len != 0) ||
336 // Cloned routes aren't real routes.
337 (rtm->rtm_flags & RTM_F_CLONED)) {
338 return false;
339 }
340
341 int family = rtm->rtm_family;
342 int prefixLength = rtm->rtm_dst_len;
343
344 // Currently we only support: destination, (one) next hop, ifindex.
345 char dst[INET6_ADDRSTRLEN] = "";
346 char gw[INET6_ADDRSTRLEN] = "";
347 char dev[IFNAMSIZ] = "";
348
349 size_t len = RTM_PAYLOAD(nh);
350 struct rtattr *rta;
351 for (rta = RTM_RTA(rtm); RTA_OK(rta, len); rta = RTA_NEXT(rta, len)) {
352 switch (rta->rta_type) {
353 case RTA_DST:
354 if (maybeLogDuplicateAttribute(*dst, "RTA_DST", msgname))
355 continue;
356 if (!inet_ntop(family, RTA_DATA(rta), dst, sizeof(dst)))
357 return false;
358 continue;
359 case RTA_GATEWAY:
360 if (maybeLogDuplicateAttribute(*gw, "RTA_GATEWAY", msgname))
361 continue;
362 if (!inet_ntop(family, RTA_DATA(rta), gw, sizeof(gw)))
363 return false;
364 continue;
365 case RTA_OIF:
366 if (maybeLogDuplicateAttribute(*dev, "RTA_OIF", msgname))
367 continue;
368 if (!if_indextoname(* (int *) RTA_DATA(rta), dev))
369 return false;
370 default:
371 continue;
372 }
373 }
374
375 // If there's no RTA_DST attribute, then:
376 // - If the prefix length is zero, it's the default route.
377 // - If the prefix length is nonzero, there's something we don't understand.
378 // Ignore the event.
379 if (!*dst && !prefixLength) {
380 if (family == AF_INET) {
381 strncpy(dst, "0.0.0.0", sizeof(dst));
382 } else if (family == AF_INET6) {
383 strncpy(dst, "::", sizeof(dst));
384 }
385 }
386
387 // A useful route must have a destination and at least either a gateway or
388 // an interface.
389 if (!*dst || (!*gw && !*dev))
390 return false;
391
392 // Fill in netlink event information.
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700393 mAction = (type == RTM_NEWROUTE) ? Action::kRouteUpdated :
394 Action::kRouteRemoved;
Lorenzo Colittid7ff7ea2014-06-11 17:37:12 +0900395 mSubsystem = strdup("net");
396 asprintf(&mParams[0], "ROUTE=%s/%d", dst, prefixLength);
397 asprintf(&mParams[1], "GATEWAY=%s", (*gw) ? gw : "");
398 asprintf(&mParams[2], "INTERFACE=%s", (*dev) ? dev : "");
399
400 return true;
401}
402
403/*
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900404 * Parse a RTM_NEWNDUSEROPT message.
405 */
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900406bool NetlinkEvent::parseNdUserOptMessage(const struct nlmsghdr *nh) {
407 struct nduseroptmsg *msg = (struct nduseroptmsg *) NLMSG_DATA(nh);
408 if (!checkRtNetlinkLength(nh, sizeof(*msg)))
409 return false;
410
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900411 // Check the length is valid.
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900412 int len = NLMSG_PAYLOAD(nh, sizeof(*msg));
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900413 if (msg->nduseropt_opts_len > len) {
414 SLOGE("RTM_NEWNDUSEROPT invalid length %d > %d\n",
415 msg->nduseropt_opts_len, len);
416 return false;
417 }
418 len = msg->nduseropt_opts_len;
419
420 // Check address family and packet type.
421 if (msg->nduseropt_family != AF_INET6) {
422 SLOGE("RTM_NEWNDUSEROPT message for unknown family %d\n",
423 msg->nduseropt_family);
424 return false;
425 }
426
427 if (msg->nduseropt_icmp_type != ND_ROUTER_ADVERT ||
428 msg->nduseropt_icmp_code != 0) {
429 SLOGE("RTM_NEWNDUSEROPT message for unknown ICMPv6 type/code %d/%d\n",
430 msg->nduseropt_icmp_type, msg->nduseropt_icmp_code);
431 return false;
432 }
433
434 // Find the interface name.
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900435 char ifname[IFNAMSIZ];
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900436 if (!if_indextoname(msg->nduseropt_ifindex, ifname)) {
437 SLOGE("RTM_NEWNDUSEROPT on unknown ifindex %d\n",
438 msg->nduseropt_ifindex);
439 return false;
440 }
441
442 // The kernel sends a separate netlink message for each ND option in the RA.
443 // So only parse the first ND option in the message.
444 struct nd_opt_hdr *opthdr = (struct nd_opt_hdr *) (msg + 1);
445
446 // The length is in multiples of 8 octets.
447 uint16_t optlen = opthdr->nd_opt_len;
448 if (optlen * 8 > len) {
449 SLOGE("Invalid option length %d > %d for ND option %d\n",
450 optlen * 8, len, opthdr->nd_opt_type);
451 return false;
452 }
453
454 if (opthdr->nd_opt_type == ND_OPT_RDNSS) {
455 // DNS Servers (RFC 6106).
456 // Each address takes up 2*8 octets, and the header takes up 8 octets.
457 // So for a valid option with one or more addresses, optlen must be
458 // odd and greater than 1.
459 if ((optlen < 3) || !(optlen & 0x1)) {
460 SLOGE("Invalid optlen %d for RDNSS option\n", optlen);
461 return false;
462 }
Erik Klineba48ff72015-06-17 15:53:29 +0900463 const int numaddrs = (optlen - 1) / 2;
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900464
465 // Find the lifetime.
466 struct nd_opt_rdnss *rndss_opt = (struct nd_opt_rdnss *) opthdr;
Erik Klineba48ff72015-06-17 15:53:29 +0900467 const uint32_t lifetime = ntohl(rndss_opt->nd_opt_rdnss_lifetime);
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900468
469 // Construct "SERVERS=<comma-separated string of DNS addresses>".
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900470 static const char kServerTag[] = "SERVERS=";
Erik Klinecc451782015-07-28 17:31:19 +0900471 static const size_t kTagLength = strlen(kServerTag);
Erik Klineba48ff72015-06-17 15:53:29 +0900472 // Reserve sufficient space for an IPv6 link-local address: all but the
473 // last address are followed by ','; the last is followed by '\0'.
Erik Klinecc451782015-07-28 17:31:19 +0900474 static const size_t kMaxSingleAddressLength =
Erik Klineba48ff72015-06-17 15:53:29 +0900475 INET6_ADDRSTRLEN + strlen("%") + IFNAMSIZ + strlen(",");
Erik Klinecc451782015-07-28 17:31:19 +0900476 const size_t bufsize = kTagLength + numaddrs * kMaxSingleAddressLength;
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900477 char *buf = (char *) malloc(bufsize);
478 if (!buf) {
479 SLOGE("RDNSS option: out of memory\n");
480 return false;
481 }
482 strcpy(buf, kServerTag);
Erik Klinecc451782015-07-28 17:31:19 +0900483 size_t pos = kTagLength;
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900484
485 struct in6_addr *addrs = (struct in6_addr *) (rndss_opt + 1);
486 for (int i = 0; i < numaddrs; i++) {
487 if (i > 0) {
488 buf[pos++] = ',';
489 }
490 inet_ntop(AF_INET6, addrs + i, buf + pos, bufsize - pos);
491 pos += strlen(buf + pos);
Erik Klineba48ff72015-06-17 15:53:29 +0900492 if (IN6_IS_ADDR_LINKLOCAL(addrs + i)) {
493 buf[pos++] = '%';
494 pos += strlcpy(buf + pos, ifname, bufsize - pos);
495 }
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900496 }
497 buf[pos] = '\0';
498
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700499 mAction = Action::kRdnss;
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900500 mSubsystem = strdup("net");
501 asprintf(&mParams[0], "INTERFACE=%s", ifname);
502 asprintf(&mParams[1], "LIFETIME=%u", lifetime);
503 mParams[2] = buf;
Lorenzo Colitticbfd65d2017-11-28 15:32:40 +0900504 } else if (opthdr->nd_opt_type == ND_OPT_DNSSL) {
505 // TODO: support DNSSL.
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900506 } else {
507 SLOGD("Unknown ND option type %d\n", opthdr->nd_opt_type);
508 return false;
509 }
510
511 return true;
512}
513
514/*
515 * Parse a binary message from a NETLINK_ROUTE netlink socket.
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900516 *
517 * Note that this function can only parse one message, because the message's
518 * content has to be stored in the class's member variables (mAction,
519 * mSubsystem, etc.). Invalid or unrecognized messages are skipped, but if
520 * there are multiple valid messages in the buffer, only the first one will be
521 * returned.
522 *
523 * TODO: consider only ever looking at the first message.
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700524 */
525bool NetlinkEvent::parseBinaryNetlinkMessage(char *buffer, int size) {
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700526 struct nlmsghdr *nh;
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700527
Lorenzo Colitti96834562013-08-17 03:40:31 +0900528 for (nh = (struct nlmsghdr *) buffer;
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900529 NLMSG_OK(nh, (unsigned) size) && (nh->nlmsg_type != NLMSG_DONE);
Lorenzo Colitti96834562013-08-17 03:40:31 +0900530 nh = NLMSG_NEXT(nh, size)) {
JP Abgralle6f80142011-07-14 16:46:32 -0700531
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900532 if (!rtMessageName(nh->nlmsg_type)) {
533 SLOGD("Unexpected netlink message type %d\n", nh->nlmsg_type);
534 continue;
535 }
536
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700537 if (nh->nlmsg_type == RTM_NEWLINK) {
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900538 if (parseIfInfoMessage(nh))
539 return true;
JP Abgralle6f80142011-07-14 16:46:32 -0700540
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700541 } else if (nh->nlmsg_type == LOCAL_QLOG_NL_EVENT) {
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900542 if (parseUlogPacketMessage(nh))
543 return true;
JP Abgralle6f80142011-07-14 16:46:32 -0700544
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900545 } else if (nh->nlmsg_type == RTM_NEWADDR ||
546 nh->nlmsg_type == RTM_DELADDR) {
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900547 if (parseIfAddrMessage(nh))
548 return true;
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900549
Lorenzo Colittid7ff7ea2014-06-11 17:37:12 +0900550 } else if (nh->nlmsg_type == RTM_NEWROUTE ||
551 nh->nlmsg_type == RTM_DELROUTE) {
552 if (parseRtMessage(nh))
553 return true;
554
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900555 } else if (nh->nlmsg_type == RTM_NEWNDUSEROPT) {
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900556 if (parseNdUserOptMessage(nh))
557 return true;
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900558
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700559 } else if (nh->nlmsg_type == LOCAL_NFLOG_PACKET) {
560 if (parseNfPacketMessage(nh))
561 return true;
562
JP Abgralle6f80142011-07-14 16:46:32 -0700563 }
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700564 }
565
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900566 return false;
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700567}
568
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100569/* If the string between 'str' and 'end' begins with 'prefixlen' characters
570 * from the 'prefix' array, then return 'str + prefixlen', otherwise return
571 * NULL.
572 */
573static const char*
574has_prefix(const char* str, const char* end, const char* prefix, size_t prefixlen)
575{
Yunlian Jiang33f67172017-02-07 15:39:25 -0800576 if ((end - str) >= (ptrdiff_t)prefixlen &&
577 (prefixlen == 0 || !memcmp(str, prefix, prefixlen))) {
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100578 return str + prefixlen;
Yunlian Jiang33f67172017-02-07 15:39:25 -0800579 } else {
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100580 return NULL;
Yunlian Jiang33f67172017-02-07 15:39:25 -0800581 }
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100582}
583
584/* Same as strlen(x) for constant string literals ONLY */
585#define CONST_STRLEN(x) (sizeof(x)-1)
586
587/* Convenience macro to call has_prefix with a constant string literal */
588#define HAS_CONST_PREFIX(str,end,prefix) has_prefix((str),(end),prefix,CONST_STRLEN(prefix))
589
590
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700591/*
592 * Parse an ASCII-formatted message from a NETLINK_KOBJECT_UEVENT
593 * netlink socket.
594 */
595bool NetlinkEvent::parseAsciiNetlinkMessage(char *buffer, int size) {
Mike J. Chen17260b12011-06-23 15:00:30 -0700596 const char *s = buffer;
597 const char *end;
San Mehat168415b2009-05-06 11:14:21 -0700598 int param_idx = 0;
San Mehat168415b2009-05-06 11:14:21 -0700599 int first = 1;
600
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100601 if (size == 0)
602 return false;
603
604 /* Ensure the buffer is zero-terminated, the code below depends on this */
605 buffer[size-1] = '\0';
606
San Mehat168415b2009-05-06 11:14:21 -0700607 end = s + size;
608 while (s < end) {
609 if (first) {
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100610 const char *p;
611 /* buffer is 0-terminated, no need to check p < end */
612 for (p = s; *p != '@'; p++) {
613 if (!*p) { /* no '@', should not happen */
614 return false;
615 }
616 }
617 mPath = strdup(p+1);
San Mehat168415b2009-05-06 11:14:21 -0700618 first = 0;
619 } else {
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100620 const char* a;
621 if ((a = HAS_CONST_PREFIX(s, end, "ACTION=")) != NULL) {
San Mehat168415b2009-05-06 11:14:21 -0700622 if (!strcmp(a, "add"))
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700623 mAction = Action::kAdd;
San Mehat168415b2009-05-06 11:14:21 -0700624 else if (!strcmp(a, "remove"))
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700625 mAction = Action::kRemove;
San Mehat168415b2009-05-06 11:14:21 -0700626 else if (!strcmp(a, "change"))
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700627 mAction = Action::kChange;
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100628 } else if ((a = HAS_CONST_PREFIX(s, end, "SEQNUM=")) != NULL) {
629 mSeq = atoi(a);
630 } else if ((a = HAS_CONST_PREFIX(s, end, "SUBSYSTEM=")) != NULL) {
631 mSubsystem = strdup(a);
632 } else if (param_idx < NL_PARAMS_MAX) {
San Mehat168415b2009-05-06 11:14:21 -0700633 mParams[param_idx++] = strdup(s);
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100634 }
San Mehat168415b2009-05-06 11:14:21 -0700635 }
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100636 s += strlen(s) + 1;
San Mehat168415b2009-05-06 11:14:21 -0700637 }
638 return true;
639}
640
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700641bool NetlinkEvent::decode(char *buffer, int size, int format) {
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700642 if (format == NetlinkListener::NETLINK_FORMAT_BINARY
643 || format == NetlinkListener::NETLINK_FORMAT_BINARY_UNICAST) {
Mike J. Chen17260b12011-06-23 15:00:30 -0700644 return parseBinaryNetlinkMessage(buffer, size);
645 } else {
646 return parseAsciiNetlinkMessage(buffer, size);
647 }
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700648}
649
San Mehat168415b2009-05-06 11:14:21 -0700650const char *NetlinkEvent::findParam(const char *paramName) {
Chih-Wei Huang80ec37a2010-07-14 14:00:41 +0800651 size_t len = strlen(paramName);
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100652 for (int i = 0; i < NL_PARAMS_MAX && mParams[i] != NULL; ++i) {
Chih-Wei Huang80ec37a2010-07-14 14:00:41 +0800653 const char *ptr = mParams[i] + len;
654 if (!strncmp(mParams[i], paramName, len) && *ptr == '=')
655 return ++ptr;
San Mehat168415b2009-05-06 11:14:21 -0700656 }
657
San Mehat7e8529a2010-03-25 09:31:42 -0700658 SLOGE("NetlinkEvent::FindParam(): Parameter '%s' not found", paramName);
San Mehat168415b2009-05-06 11:14:21 -0700659 return NULL;
660}
Lorenzo Colittie439ffc2017-10-03 18:44:11 +0900661
662nlattr* NetlinkEvent::findNlAttr(const nlmsghdr* nh, size_t hdrlen, uint16_t attr) {
663 if (nh == nullptr || NLMSG_HDRLEN + NLMSG_ALIGN(hdrlen) > SSIZE_MAX) {
664 return nullptr;
665 }
666
667 // Skip header, padding, and family header.
668 const ssize_t NLA_START = NLMSG_HDRLEN + NLMSG_ALIGN(hdrlen);
669 ssize_t left = nh->nlmsg_len - NLA_START;
670 uint8_t* hdr = ((uint8_t*)nh) + NLA_START;
671
672 while (left >= NLA_HDRLEN) {
673 nlattr* nla = (nlattr*)hdr;
674 if (nla->nla_type == attr) {
675 return nla;
676 }
677
678 hdr += NLA_ALIGN(nla->nla_len);
679 left -= NLA_ALIGN(nla->nla_len);
680 }
681
682 return nullptr;
683}