1 /*
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  */
16 
17 #define LOG_TAG "NetlinkEvent"
18 
19 #include <arpa/inet.h>
20 #include <limits.h>
21 #include <linux/genetlink.h>
22 #include <linux/if.h>
23 #include <linux/if_addr.h>
24 #include <linux/if_link.h>
25 #include <linux/netfilter/nfnetlink.h>
26 #include <linux/netfilter/nfnetlink_log.h>
27 #include <linux/netlink.h>
28 #include <linux/rtnetlink.h>
29 #include <net/if.h>
30 #include <netinet/icmp6.h>
31 #include <netinet/in.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <sys/personality.h>
35 #include <sys/socket.h>
36 #include <sys/types.h>
37 #include <sys/utsname.h>
38 
39 #include <android-base/parseint.h>
40 #include <bpf/KernelUtils.h>
41 #include <log/log.h>
42 #include <sysutils/NetlinkEvent.h>
43 
44 using android::base::ParseInt;
45 using android::bpf::isKernel64Bit;
46 
47 /* From kernel's net/netfilter/xt_quota2.c */
48 const int LOCAL_QLOG_NL_EVENT = 112;
49 const int LOCAL_NFLOG_PACKET = NFNL_SUBSYS_ULOG << 8 | NFULNL_MSG_PACKET;
50 
51 /******************************************************************************
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  */
71 #define ULOG_MAC_LEN 80
72 #define ULOG_PREFIX_LEN 32
73 typedef 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 
87 // 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
89 typedef int long32;
90 typedef unsigned int ulong32;
91 static_assert(sizeof(long32) == 4);
92 static_assert(sizeof(ulong32) == 4);
93 
94 // Here's the same structure definition with the assumption the kernel
95 // is compiled for 32-bits.
96 typedef 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.
112 typedef long long __attribute__((__aligned__(8))) long64;
113 typedef unsigned long long __attribute__((__aligned__(8))) ulong64;
114 static_assert(sizeof(long64) == 8);
115 static_assert(sizeof(ulong64) == 8);
116 
117 // Here's the same structure definition with the assumption the kernel
118 // is compiled for 64-bits.
119 typedef 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.
134 static_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.
136 static_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):
140 static_assert(sizeof(ulog_packet_msg32_t) == 168);
141 static_assert(sizeof(ulog_packet_msg64_t) == 192);
142 
143 /******************************************************************************/
144 
NetlinkEvent()145 NetlinkEvent::NetlinkEvent() {
146     mAction = Action::kUnknown;
147     memset(mParams, 0, sizeof(mParams));
148     mPath = nullptr;
149     mSubsystem = nullptr;
150 }
151 
~NetlinkEvent()152 NetlinkEvent::~NetlinkEvent() {
153     free(mPath);
154     free(mSubsystem);
155     for (auto param : mParams) {
156         free(param);
157     }
158 }
159 
dump()160 void NetlinkEvent::dump() {
161     int i;
162 
163     for (i = 0; i < NL_PARAMS_MAX; i++) {
164         if (!mParams[i])
165             break;
166         SLOGD("NL param '%s'\n", mParams[i]);
167     }
168 }
169 
170 /*
171  * Returns the message name for a message in the NETLINK_ROUTE family, or NULL
172  * if parsing that message is not supported.
173  */
rtMessageName(int type)174 static 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);
184         NL_EVENT_RTM_NAME(LOCAL_QLOG_NL_EVENT);
185         NL_EVENT_RTM_NAME(LOCAL_NFLOG_PACKET);
186         default:
187             return nullptr;
188     }
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  */
checkRtNetlinkLength(const struct nlmsghdr * nh,size_t size)196 static 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  */
maybeLogDuplicateAttribute(bool isDup,const char * attributeName,const char * messageName)207 static 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  */
parseIfInfoMessage(const struct nlmsghdr * nh)220 bool 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));
235                 // 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);
241                 mAction = (ifi->ifi_flags & IFF_LOWER_UP) ? Action::kLinkUp :
242                                                             Action::kLinkDown;
243                 mSubsystem = strdup("net");
244                 return true;
245         }
246     }
247 
248     return false;
249 }
250 
251 /*
252  * Parse a RTM_NEWADDR or RTM_DELADDR message.
253  */
parseIfAddrMessage(const struct nlmsghdr * nh)254 bool NetlinkEvent::parseIfAddrMessage(const struct nlmsghdr *nh) {
255     struct ifaddrmsg *ifaddr = (struct ifaddrmsg *) NLMSG_DATA(nh);
256     struct ifa_cacheinfo *cacheinfo = nullptr;
257     char addrstr[INET6_ADDRSTRLEN] = "";
258     char ifname[IFNAMSIZ] = "";
259     uint32_t flags;
260 
261     if (!checkRtNetlinkLength(nh, sizeof(*ifaddr)))
262         return false;
263 
264     int type = nh->nlmsg_type;
265     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.
271     const char *msgtype = rtMessageName(type);
272 
273     // First 8 bits of flags. In practice will always be overridden when parsing IFA_FLAGS below.
274     flags = ifaddr->ifa_flags;
275 
276     struct rtattr *rta;
277     int len = IFA_PAYLOAD(nh);
278     for (rta = IFA_RTA(ifaddr); RTA_OK(rta, len); rta = RTA_NEXT(rta, len)) {
279         if (rta->rta_type == IFA_ADDRESS) {
280             // Only look at the first address, because we only support notifying
281             // one change at a time.
282             if (maybeLogDuplicateAttribute(*addrstr != '\0', "IFA_ADDRESS", msgtype))
283                 continue;
284 
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)) {
289                     SLOGE("Short IPv4 address (%zu bytes) in %s",
290                           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)) {
297                     SLOGE("Short IPv6 address (%zu bytes) in %s",
298                           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.
308             if (!if_indextoname(ifaddr->ifa_index, ifname)) {
309                 SLOGD("Unknown ifindex %d in %s", ifaddr->ifa_index, msgtype);
310             }
311 
312         } else if (rta->rta_type == IFA_CACHEINFO) {
313             // Address lifetime information.
314             if (maybeLogDuplicateAttribute(cacheinfo, "IFA_CACHEINFO", msgtype))
315                 continue;
316 
317             if (RTA_PAYLOAD(rta) < sizeof(*cacheinfo)) {
318                 SLOGE("Short IFA_CACHEINFO (%zu vs. %zu bytes) in %s",
319                       RTA_PAYLOAD(rta), sizeof(cacheinfo), msgtype);
320                 continue;
321             }
322 
323             cacheinfo = (struct ifa_cacheinfo *) RTA_DATA(rta);
324 
325         } else if (rta->rta_type == IFA_FLAGS) {
326             flags = *(uint32_t*)RTA_DATA(rta);
327         }
328     }
329 
330     if (addrstr[0] == '\0') {
331         SLOGE("No IFA_ADDRESS in %s\n", msgtype);
332         return false;
333     }
334 
335     // Fill in netlink event information.
336     mAction = (type == RTM_NEWADDR) ? Action::kAddressUpdated :
337                                       Action::kAddressRemoved;
338     mSubsystem = strdup("net");
339     asprintf(&mParams[0], "ADDRESS=%s/%d", addrstr, ifaddr->ifa_prefixlen);
340     asprintf(&mParams[1], "INTERFACE=%s", ifname);
341     asprintf(&mParams[2], "FLAGS=%u", flags);
342     asprintf(&mParams[3], "SCOPE=%u", ifaddr->ifa_scope);
343     asprintf(&mParams[4], "IFINDEX=%u", ifaddr->ifa_index);
344 
345     if (cacheinfo) {
346         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);
350     }
351 
352     return true;
353 }
354 
355 /*
356  * Parse a QLOG_NL_EVENT message.
357  */
parseUlogPacketMessage(const struct nlmsghdr * nh)358 bool NetlinkEvent::parseUlogPacketMessage(const struct nlmsghdr *nh) {
359     const char* alert;
360     const char* devname;
361 
362     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);
375     asprintf(&mParams[1], "INTERFACE=%s", devname);
376     mSubsystem = strdup("qlog");
377     mAction = Action::kChange;
378     return true;
379 }
380 
nlAttrLen(const nlattr * nla)381 static size_t nlAttrLen(const nlattr* nla) {
382     return nla->nla_len - NLA_HDRLEN;
383 }
384 
nlAttrData(const nlattr * nla)385 static const uint8_t* nlAttrData(const nlattr* nla) {
386     return reinterpret_cast<const uint8_t*>(nla) + NLA_HDRLEN;
387 }
388 
nlAttrU32(const nlattr * nla)389 static uint32_t nlAttrU32(const nlattr* nla) {
390     return *reinterpret_cast<const uint32_t*>(nlAttrData(nla));
391 }
392 
393 /*
394  * Parse a LOCAL_NFLOG_PACKET message.
395  */
parseNfPacketMessage(struct nlmsghdr * nh)396 bool NetlinkEvent::parseNfPacketMessage(struct nlmsghdr *nh) {
397     int uid = -1;
398     int len = 0;
399     char* raw = nullptr;
400 
401     struct nlattr* uid_attr = findNlAttr(nh, sizeof(struct genlmsghdr), NFULA_UID);
402     if (uid_attr) {
403         uid = ntohl(nlAttrU32(uid_attr));
404     }
405 
406     struct nlattr* payload = findNlAttr(nh, sizeof(struct genlmsghdr), NFULA_PAYLOAD);
407     if (payload) {
408         /* First 256 bytes is plenty */
409         len = nlAttrLen(payload);
410         if (len > 256) len = 256;
411         raw = (char*)nlAttrData(payload);
412     }
413 
414     size_t hexSize = 5 + (len * 2);
415     char* hex = (char*)calloc(1, hexSize);
416     strlcpy(hex, "HEX=", hexSize);
417     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");
425     mAction = Action::kChange;
426     return true;
427 }
428 
429 /*
430  * Parse a RTM_NEWROUTE or RTM_DELROUTE message.
431  */
parseRtMessage(const struct nlmsghdr * nh)432 bool NetlinkEvent::parseRtMessage(const struct nlmsghdr *nh) {
433     uint8_t type = nh->nlmsg_type;
434     const char *msgname = rtMessageName(type);
435 
436     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;
487                 continue;
488             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.
511     mAction = (type == RTM_NEWROUTE) ? Action::kRouteUpdated :
512                                        Action::kRouteRemoved;
513     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 /*
522  * Parse a RTM_NEWNDUSEROPT message.
523  */
parseNdUserOptMessage(const struct nlmsghdr * nh)524 bool 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 
529     // Check the length is valid.
530     int len = NLMSG_PAYLOAD(nh, sizeof(*msg));
531     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.
553     char ifname[IFNAMSIZ];
554     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         }
581         const int numaddrs = (optlen - 1) / 2;
582 
583         // Find the lifetime.
584         struct nd_opt_rdnss *rndss_opt = (struct nd_opt_rdnss *) opthdr;
585         const uint32_t lifetime = ntohl(rndss_opt->nd_opt_rdnss_lifetime);
586 
587         // Construct a comma-separated string of DNS addresses.
588         // Reserve sufficient space for an IPv6 link-local address: all but the
589         // last address are followed by ','; the last is followed by '\0'.
590         static const size_t kMaxSingleAddressLength =
591                 INET6_ADDRSTRLEN + strlen("%") + IFNAMSIZ + strlen(",");
592         const size_t bufsize = numaddrs * kMaxSingleAddressLength;
593         char *buf = (char *) malloc(bufsize);
594         if (!buf) {
595             SLOGE("RDNSS option: out of memory\n");
596             return false;
597         }
598 
599         struct in6_addr *addrs = (struct in6_addr *) (rndss_opt + 1);
600         size_t pos = 0;
601         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);
607             if (IN6_IS_ADDR_LINKLOCAL(addrs + i)) {
608                 buf[pos++] = '%';
609                 pos += strlcpy(buf + pos, ifname, bufsize - pos);
610             }
611         }
612         buf[pos] = '\0';
613 
614         mAction = Action::kRdnss;
615         mSubsystem = strdup("net");
616         asprintf(&mParams[0], "INTERFACE=%s", ifname);
617         asprintf(&mParams[1], "LIFETIME=%u", lifetime);
618         asprintf(&mParams[2], "SERVERS=%s", buf);
619         free(buf);
620     } else if (opthdr->nd_opt_type == ND_OPT_DNSSL) {
621         // TODO: support DNSSL.
622     } 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.
626     } 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.
636  *
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.
644  */
parseBinaryNetlinkMessage(char * buffer,int size)645 bool NetlinkEvent::parseBinaryNetlinkMessage(char *buffer, int size) {
646     struct nlmsghdr *nh;
647 
648     for (nh = (struct nlmsghdr *) buffer;
649          NLMSG_OK(nh, (unsigned) size) && (nh->nlmsg_type != NLMSG_DONE);
650          nh = NLMSG_NEXT(nh, size)) {
651 
652         if (!rtMessageName(nh->nlmsg_type)) {
653             SLOGD("Unexpected netlink message type %d\n", nh->nlmsg_type);
654             continue;
655         }
656 
657         if (nh->nlmsg_type == RTM_NEWLINK) {
658             if (parseIfInfoMessage(nh))
659                 return true;
660 
661         } else if (nh->nlmsg_type == LOCAL_QLOG_NL_EVENT) {
662             if (parseUlogPacketMessage(nh))
663                 return true;
664 
665         } else if (nh->nlmsg_type == RTM_NEWADDR ||
666                    nh->nlmsg_type == RTM_DELADDR) {
667             if (parseIfAddrMessage(nh))
668                 return true;
669 
670         } else if (nh->nlmsg_type == RTM_NEWROUTE ||
671                    nh->nlmsg_type == RTM_DELROUTE) {
672             if (parseRtMessage(nh))
673                 return true;
674 
675         } else if (nh->nlmsg_type == RTM_NEWNDUSEROPT) {
676             if (parseNdUserOptMessage(nh))
677                 return true;
678 
679         } else if (nh->nlmsg_type == LOCAL_NFLOG_PACKET) {
680             if (parseNfPacketMessage(nh))
681                 return true;
682 
683         }
684     }
685 
686     return false;
687 }
688 
689 /* 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  */
693 static const char*
has_prefix(const char * str,const char * end,const char * prefix,size_t prefixlen)694 has_prefix(const char* str, const char* end, const char* prefix, size_t prefixlen)
695 {
696     if ((end - str) >= (ptrdiff_t)prefixlen &&
697         (prefixlen == 0 || !memcmp(str, prefix, prefixlen))) {
698         return str + prefixlen;
699     } else {
700         return nullptr;
701     }
702 }
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 
711 /*
712  * Parse an ASCII-formatted message from a NETLINK_KOBJECT_UEVENT
713  * netlink socket.
714  */
parseAsciiNetlinkMessage(char * buffer,int size)715 bool NetlinkEvent::parseAsciiNetlinkMessage(char *buffer, int size) {
716     const char *s = buffer;
717     const char *end;
718     int param_idx = 0;
719     int first = 1;
720 
721     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 
727     end = s + size;
728     while (s < end) {
729         if (first) {
730             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);
738             first = 0;
739         } else {
740             const char* a;
741             if ((a = HAS_CONST_PREFIX(s, end, "ACTION=")) != nullptr) {
742                 if (!strcmp(a, "add"))
743                     mAction = Action::kAdd;
744                 else if (!strcmp(a, "remove"))
745                     mAction = Action::kRemove;
746                 else if (!strcmp(a, "change"))
747                     mAction = Action::kChange;
748             } else if ((a = HAS_CONST_PREFIX(s, end, "SEQNUM=")) != nullptr) {
749                 if (!ParseInt(a, &mSeq)) {
750                     SLOGE("NetlinkEvent::parseAsciiNetlinkMessage: failed to parse SEQNUM=%s", a);
751                 }
752             } else if ((a = HAS_CONST_PREFIX(s, end, "SUBSYSTEM=")) != nullptr) {
753                 mSubsystem = strdup(a);
754             } else if (param_idx < NL_PARAMS_MAX) {
755                 mParams[param_idx++] = strdup(s);
756             }
757         }
758         s += strlen(s) + 1;
759     }
760     return true;
761 }
762 
decode(char * buffer,int size,int format)763 bool NetlinkEvent::decode(char *buffer, int size, int format) {
764     if (format == NetlinkListener::NETLINK_FORMAT_BINARY
765             || format == NetlinkListener::NETLINK_FORMAT_BINARY_UNICAST) {
766         return parseBinaryNetlinkMessage(buffer, size);
767     } else {
768         return parseAsciiNetlinkMessage(buffer, size);
769     }
770 }
771 
findParam(const char * paramName)772 const char *NetlinkEvent::findParam(const char *paramName) {
773     size_t len = strlen(paramName);
774     for (int i = 0; i < NL_PARAMS_MAX && mParams[i] != nullptr; ++i) {
775         const char *ptr = mParams[i] + len;
776         if (!strncmp(mParams[i], paramName, len) && *ptr == '=')
777             return ++ptr;
778     }
779 
780     SLOGE("NetlinkEvent::FindParam(): Parameter '%s' not found", paramName);
781     return nullptr;
782 }
783 
findNlAttr(const nlmsghdr * nh,size_t hdrlen,uint16_t attr)784 nlattr* 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 }
806