• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <log/log.h>
41 #include <sysutils/NetlinkEvent.h>
42 
43 using android::base::ParseInt;
44 
45 /* From kernel's net/netfilter/xt_quota2.c */
46 const int LOCAL_QLOG_NL_EVENT = 112;
47 const int LOCAL_NFLOG_PACKET = NFNL_SUBSYS_ULOG << 8 | NFULNL_MSG_PACKET;
48 
49 /******************************************************************************
50  * WARNING: HERE BE DRAGONS!                                                  *
51  *                                                                            *
52  * This is here to provide for compatibility with both 32 and 64-bit kernels  *
53  * from 32-bit userspace.                                                     *
54  *                                                                            *
55  * The kernel definition of this struct uses types (like long) that are not   *
56  * the same across 32-bit and 64-bit builds, and there is no compatibility    *
57  * layer to fix it up before it reaches userspace.                            *
58  * As such we need to detect the bit-ness of the kernel and deal with it.     *
59  *                                                                            *
60  ******************************************************************************/
61 
62 /*
63  * This is the verbatim kernel declaration from net/netfilter/xt_quota2.c,
64  * it is *NOT* of a well defined layout and is included here for compile
65  * time assertions only.
66  *
67  * It got there from deprecated ipt_ULOG.h to parse QLOG_NL_EVENT.
68  */
69 #define ULOG_MAC_LEN 80
70 #define ULOG_PREFIX_LEN 32
71 typedef struct ulog_packet_msg {
72     unsigned long mark;
73     long timestamp_sec;
74     long timestamp_usec;
75     unsigned int hook;
76     char indev_name[IFNAMSIZ];
77     char outdev_name[IFNAMSIZ];
78     size_t data_len;
79     char prefix[ULOG_PREFIX_LEN];
80     unsigned char mac_len;
81     unsigned char mac[ULOG_MAC_LEN];
82     unsigned char payload[0];
83 } ulog_packet_msg_t;
84 
85 // On Linux int is always 32 bits, while sizeof(long) == sizeof(void*),
86 // thus long on a 32-bit Linux kernel is 32-bits, like int always is
87 typedef int long32;
88 typedef unsigned int ulong32;
89 static_assert(sizeof(long32) == 4);
90 static_assert(sizeof(ulong32) == 4);
91 
92 // Here's the same structure definition with the assumption the kernel
93 // is compiled for 32-bits.
94 typedef struct {
95     ulong32 mark;
96     long32 timestamp_sec;
97     long32 timestamp_usec;
98     unsigned int hook;
99     char indev_name[IFNAMSIZ];
100     char outdev_name[IFNAMSIZ];
101     ulong32 data_len;
102     char prefix[ULOG_PREFIX_LEN];
103     unsigned char mac_len;
104     unsigned char mac[ULOG_MAC_LEN];
105     unsigned char payload[0];
106 } ulog_packet_msg32_t;
107 
108 // long on a 64-bit kernel is 64-bits with 64-bit alignment,
109 // while long long is 64-bit but may have 32-bit aligment.
110 typedef long long __attribute__((__aligned__(8))) long64;
111 typedef unsigned long long __attribute__((__aligned__(8))) ulong64;
112 static_assert(sizeof(long64) == 8);
113 static_assert(sizeof(ulong64) == 8);
114 
115 // Here's the same structure definition with the assumption the kernel
116 // is compiled for 64-bits.
117 typedef struct {
118     ulong64 mark;
119     long64 timestamp_sec;
120     long64 timestamp_usec;
121     unsigned int hook;
122     char indev_name[IFNAMSIZ];
123     char outdev_name[IFNAMSIZ];
124     ulong64 data_len;
125     char prefix[ULOG_PREFIX_LEN];
126     unsigned char mac_len;
127     unsigned char mac[ULOG_MAC_LEN];
128     unsigned char payload[0];
129 } ulog_packet_msg64_t;
130 
131 // One expects the 32-bit version to be smaller than the 64-bit version.
132 static_assert(sizeof(ulog_packet_msg32_t) < sizeof(ulog_packet_msg64_t));
133 // And either way the 'native' version should match either the 32 or 64 bit one.
134 static_assert(sizeof(ulog_packet_msg_t) == sizeof(ulog_packet_msg32_t) ||
135               sizeof(ulog_packet_msg_t) == sizeof(ulog_packet_msg64_t));
136 
137 // In practice these sizes are always simply (for both x86 and arm):
138 static_assert(sizeof(ulog_packet_msg32_t) == 168);
139 static_assert(sizeof(ulog_packet_msg64_t) == 192);
140 
141 // Figure out the bitness of userspace.
142 // Trivial and known at compile time.
isUserspace64bit(void)143 static bool isUserspace64bit(void) {
144     return sizeof(long) == 8;
145 }
146 
147 // Figure out the bitness of the kernel.
isKernel64Bit(void)148 static bool isKernel64Bit(void) {
149     // a 64-bit userspace requires a 64-bit kernel
150     if (isUserspace64bit()) return true;
151 
152     static bool init = false;
153     static bool cache = false;
154     if (init) return cache;
155 
156     // Retrieve current personality - on Linux this system call *cannot* fail.
157     int p = personality(0xffffffff);
158     // But if it does just assume kernel and userspace (which is 32-bit) match...
159     if (p == -1) return false;
160 
161     // This will effectively mask out the bottom 8 bits, and switch to 'native'
162     // personality, and then return the previous personality of this thread
163     // (likely PER_LINUX or PER_LINUX32) with any extra options unmodified.
164     int q = personality((p & ~PER_MASK) | PER_LINUX);
165     // Per man page this theoretically could error out with EINVAL,
166     // but kernel code analysis suggests setting PER_LINUX cannot fail.
167     // Either way, assume kernel and userspace (which is 32-bit) match...
168     if (q != p) return false;
169 
170     struct utsname u;
171     (void)uname(&u);  // only possible failure is EFAULT, but u is on stack.
172 
173     // Switch back to previous personality.
174     // Theoretically could fail with EINVAL on arm64 with no 32-bit support,
175     // but then we wouldn't have fetched 'p' from the kernel in the first place.
176     // Either way there's nothing meaningul we can do in case of error.
177     // Since PER_LINUX32 vs PER_LINUX only affects uname.machine it doesn't
178     // really hurt us either.  We're really just switching back to be 'clean'.
179     (void)personality(p);
180 
181     // Possible values of utsname.machine observed on x86_64 desktop (arm via qemu):
182     //   x86_64 i686 aarch64 armv7l
183     // additionally observed on arm device:
184     //   armv8l
185     // presumably also might just be possible:
186     //   i386 i486 i586
187     // and there might be other weird arm32 cases.
188     // We note that the 64 is present in both 64-bit archs,
189     // and in general is likely to be present in only 64-bit archs.
190     cache = !!strstr(u.machine, "64");
191     init = true;
192     return cache;
193 }
194 
195 /******************************************************************************/
196 
NetlinkEvent()197 NetlinkEvent::NetlinkEvent() {
198     mAction = Action::kUnknown;
199     memset(mParams, 0, sizeof(mParams));
200     mPath = nullptr;
201     mSubsystem = nullptr;
202 }
203 
~NetlinkEvent()204 NetlinkEvent::~NetlinkEvent() {
205     int i;
206     if (mPath)
207         free(mPath);
208     if (mSubsystem)
209         free(mSubsystem);
210     for (i = 0; i < NL_PARAMS_MAX; i++) {
211         if (!mParams[i])
212             break;
213         free(mParams[i]);
214     }
215 }
216 
dump()217 void NetlinkEvent::dump() {
218     int i;
219 
220     for (i = 0; i < NL_PARAMS_MAX; i++) {
221         if (!mParams[i])
222             break;
223         SLOGD("NL param '%s'\n", mParams[i]);
224     }
225 }
226 
227 /*
228  * Returns the message name for a message in the NETLINK_ROUTE family, or NULL
229  * if parsing that message is not supported.
230  */
rtMessageName(int type)231 static const char *rtMessageName(int type) {
232 #define NL_EVENT_RTM_NAME(rtm) case rtm: return #rtm;
233     switch (type) {
234         NL_EVENT_RTM_NAME(RTM_NEWLINK);
235         NL_EVENT_RTM_NAME(RTM_DELLINK);
236         NL_EVENT_RTM_NAME(RTM_NEWADDR);
237         NL_EVENT_RTM_NAME(RTM_DELADDR);
238         NL_EVENT_RTM_NAME(RTM_NEWROUTE);
239         NL_EVENT_RTM_NAME(RTM_DELROUTE);
240         NL_EVENT_RTM_NAME(RTM_NEWNDUSEROPT);
241         NL_EVENT_RTM_NAME(LOCAL_QLOG_NL_EVENT);
242         NL_EVENT_RTM_NAME(LOCAL_NFLOG_PACKET);
243         default:
244             return nullptr;
245     }
246 #undef NL_EVENT_RTM_NAME
247 }
248 
249 /*
250  * Checks that a binary NETLINK_ROUTE message is long enough for a payload of
251  * size bytes.
252  */
checkRtNetlinkLength(const struct nlmsghdr * nh,size_t size)253 static bool checkRtNetlinkLength(const struct nlmsghdr *nh, size_t size) {
254     if (nh->nlmsg_len < NLMSG_LENGTH(size)) {
255         SLOGE("Got a short %s message\n", rtMessageName(nh->nlmsg_type));
256         return false;
257     }
258     return true;
259 }
260 
261 /*
262  * Utility function to log errors.
263  */
maybeLogDuplicateAttribute(bool isDup,const char * attributeName,const char * messageName)264 static bool maybeLogDuplicateAttribute(bool isDup,
265                                        const char *attributeName,
266                                        const char *messageName) {
267     if (isDup) {
268         SLOGE("Multiple %s attributes in %s, ignoring\n", attributeName, messageName);
269         return true;
270     }
271     return false;
272 }
273 
274 /*
275  * Parse a RTM_NEWLINK message.
276  */
parseIfInfoMessage(const struct nlmsghdr * nh)277 bool NetlinkEvent::parseIfInfoMessage(const struct nlmsghdr *nh) {
278     struct ifinfomsg *ifi = (struct ifinfomsg *) NLMSG_DATA(nh);
279     if (!checkRtNetlinkLength(nh, sizeof(*ifi)))
280         return false;
281 
282     if ((ifi->ifi_flags & IFF_LOOPBACK) != 0) {
283         return false;
284     }
285 
286     int len = IFLA_PAYLOAD(nh);
287     struct rtattr *rta;
288     for (rta = IFLA_RTA(ifi); RTA_OK(rta, len); rta = RTA_NEXT(rta, len)) {
289         switch(rta->rta_type) {
290             case IFLA_IFNAME:
291                 asprintf(&mParams[0], "INTERFACE=%s", (char *) RTA_DATA(rta));
292                 // We can get the interface change information from sysfs update
293                 // already. But in case we missed those message when devices start.
294                 // We do a update again when received a kLinkUp event. To make
295                 // the message consistent, use IFINDEX here as well since sysfs
296                 // uses IFINDEX.
297                 asprintf(&mParams[1], "IFINDEX=%d", ifi->ifi_index);
298                 mAction = (ifi->ifi_flags & IFF_LOWER_UP) ? Action::kLinkUp :
299                                                             Action::kLinkDown;
300                 mSubsystem = strdup("net");
301                 return true;
302         }
303     }
304 
305     return false;
306 }
307 
308 /*
309  * Parse a RTM_NEWADDR or RTM_DELADDR message.
310  */
parseIfAddrMessage(const struct nlmsghdr * nh)311 bool NetlinkEvent::parseIfAddrMessage(const struct nlmsghdr *nh) {
312     struct ifaddrmsg *ifaddr = (struct ifaddrmsg *) NLMSG_DATA(nh);
313     struct ifa_cacheinfo *cacheinfo = nullptr;
314     char addrstr[INET6_ADDRSTRLEN] = "";
315     char ifname[IFNAMSIZ] = "";
316     uint32_t flags;
317 
318     if (!checkRtNetlinkLength(nh, sizeof(*ifaddr)))
319         return false;
320 
321     int type = nh->nlmsg_type;
322     if (type != RTM_NEWADDR && type != RTM_DELADDR) {
323         SLOGE("parseIfAddrMessage on incorrect message type 0x%x\n", type);
324         return false;
325     }
326 
327     // For log messages.
328     const char *msgtype = rtMessageName(type);
329 
330     // First 8 bits of flags. In practice will always be overridden when parsing IFA_FLAGS below.
331     flags = ifaddr->ifa_flags;
332 
333     struct rtattr *rta;
334     int len = IFA_PAYLOAD(nh);
335     for (rta = IFA_RTA(ifaddr); RTA_OK(rta, len); rta = RTA_NEXT(rta, len)) {
336         if (rta->rta_type == IFA_ADDRESS) {
337             // Only look at the first address, because we only support notifying
338             // one change at a time.
339             if (maybeLogDuplicateAttribute(*addrstr != '\0', "IFA_ADDRESS", msgtype))
340                 continue;
341 
342             // Convert the IP address to a string.
343             if (ifaddr->ifa_family == AF_INET) {
344                 struct in_addr *addr4 = (struct in_addr *) RTA_DATA(rta);
345                 if (RTA_PAYLOAD(rta) < sizeof(*addr4)) {
346                     SLOGE("Short IPv4 address (%zu bytes) in %s",
347                           RTA_PAYLOAD(rta), msgtype);
348                     continue;
349                 }
350                 inet_ntop(AF_INET, addr4, addrstr, sizeof(addrstr));
351             } else if (ifaddr->ifa_family == AF_INET6) {
352                 struct in6_addr *addr6 = (struct in6_addr *) RTA_DATA(rta);
353                 if (RTA_PAYLOAD(rta) < sizeof(*addr6)) {
354                     SLOGE("Short IPv6 address (%zu bytes) in %s",
355                           RTA_PAYLOAD(rta), msgtype);
356                     continue;
357                 }
358                 inet_ntop(AF_INET6, addr6, addrstr, sizeof(addrstr));
359             } else {
360                 SLOGE("Unknown address family %d\n", ifaddr->ifa_family);
361                 continue;
362             }
363 
364             // Find the interface name.
365             if (!if_indextoname(ifaddr->ifa_index, ifname)) {
366                 SLOGD("Unknown ifindex %d in %s", ifaddr->ifa_index, msgtype);
367             }
368 
369         } else if (rta->rta_type == IFA_CACHEINFO) {
370             // Address lifetime information.
371             if (maybeLogDuplicateAttribute(cacheinfo, "IFA_CACHEINFO", msgtype))
372                 continue;
373 
374             if (RTA_PAYLOAD(rta) < sizeof(*cacheinfo)) {
375                 SLOGE("Short IFA_CACHEINFO (%zu vs. %zu bytes) in %s",
376                       RTA_PAYLOAD(rta), sizeof(cacheinfo), msgtype);
377                 continue;
378             }
379 
380             cacheinfo = (struct ifa_cacheinfo *) RTA_DATA(rta);
381 
382         } else if (rta->rta_type == IFA_FLAGS) {
383             flags = *(uint32_t*)RTA_DATA(rta);
384         }
385     }
386 
387     if (addrstr[0] == '\0') {
388         SLOGE("No IFA_ADDRESS in %s\n", msgtype);
389         return false;
390     }
391 
392     // Fill in netlink event information.
393     mAction = (type == RTM_NEWADDR) ? Action::kAddressUpdated :
394                                       Action::kAddressRemoved;
395     mSubsystem = strdup("net");
396     asprintf(&mParams[0], "ADDRESS=%s/%d", addrstr, ifaddr->ifa_prefixlen);
397     asprintf(&mParams[1], "INTERFACE=%s", ifname);
398     asprintf(&mParams[2], "FLAGS=%u", flags);
399     asprintf(&mParams[3], "SCOPE=%u", ifaddr->ifa_scope);
400     asprintf(&mParams[4], "IFINDEX=%u", ifaddr->ifa_index);
401 
402     if (cacheinfo) {
403         asprintf(&mParams[5], "PREFERRED=%u", cacheinfo->ifa_prefered);
404         asprintf(&mParams[6], "VALID=%u", cacheinfo->ifa_valid);
405         asprintf(&mParams[7], "CSTAMP=%u", cacheinfo->cstamp);
406         asprintf(&mParams[8], "TSTAMP=%u", cacheinfo->tstamp);
407     }
408 
409     return true;
410 }
411 
412 /*
413  * Parse a QLOG_NL_EVENT message.
414  */
parseUlogPacketMessage(const struct nlmsghdr * nh)415 bool NetlinkEvent::parseUlogPacketMessage(const struct nlmsghdr *nh) {
416     const char* alert;
417     const char* devname;
418 
419     if (isKernel64Bit()) {
420         ulog_packet_msg64_t* pm64 = (ulog_packet_msg64_t*)NLMSG_DATA(nh);
421         if (!checkRtNetlinkLength(nh, sizeof(*pm64))) return false;
422         alert = pm64->prefix;
423         devname = pm64->indev_name[0] ? pm64->indev_name : pm64->outdev_name;
424     } else {
425         ulog_packet_msg32_t* pm32 = (ulog_packet_msg32_t*)NLMSG_DATA(nh);
426         if (!checkRtNetlinkLength(nh, sizeof(*pm32))) return false;
427         alert = pm32->prefix;
428         devname = pm32->indev_name[0] ? pm32->indev_name : pm32->outdev_name;
429     }
430 
431     asprintf(&mParams[0], "ALERT_NAME=%s", alert);
432     asprintf(&mParams[1], "INTERFACE=%s", devname);
433     mSubsystem = strdup("qlog");
434     mAction = Action::kChange;
435     return true;
436 }
437 
nlAttrLen(const nlattr * nla)438 static size_t nlAttrLen(const nlattr* nla) {
439     return nla->nla_len - NLA_HDRLEN;
440 }
441 
nlAttrData(const nlattr * nla)442 static const uint8_t* nlAttrData(const nlattr* nla) {
443     return reinterpret_cast<const uint8_t*>(nla) + NLA_HDRLEN;
444 }
445 
nlAttrU32(const nlattr * nla)446 static uint32_t nlAttrU32(const nlattr* nla) {
447     return *reinterpret_cast<const uint32_t*>(nlAttrData(nla));
448 }
449 
450 /*
451  * Parse a LOCAL_NFLOG_PACKET message.
452  */
parseNfPacketMessage(struct nlmsghdr * nh)453 bool NetlinkEvent::parseNfPacketMessage(struct nlmsghdr *nh) {
454     int uid = -1;
455     int len = 0;
456     char* raw = nullptr;
457 
458     struct nlattr* uid_attr = findNlAttr(nh, sizeof(struct genlmsghdr), NFULA_UID);
459     if (uid_attr) {
460         uid = ntohl(nlAttrU32(uid_attr));
461     }
462 
463     struct nlattr* payload = findNlAttr(nh, sizeof(struct genlmsghdr), NFULA_PAYLOAD);
464     if (payload) {
465         /* First 256 bytes is plenty */
466         len = nlAttrLen(payload);
467         if (len > 256) len = 256;
468         raw = (char*)nlAttrData(payload);
469     }
470 
471     size_t hexSize = 5 + (len * 2);
472     char* hex = (char*)calloc(1, hexSize);
473     strlcpy(hex, "HEX=", hexSize);
474     for (int i = 0; i < len; i++) {
475         hex[4 + (i * 2)] = "0123456789abcdef"[(raw[i] >> 4) & 0xf];
476         hex[5 + (i * 2)] = "0123456789abcdef"[raw[i] & 0xf];
477     }
478 
479     asprintf(&mParams[0], "UID=%d", uid);
480     mParams[1] = hex;
481     mSubsystem = strdup("strict");
482     mAction = Action::kChange;
483     return true;
484 }
485 
486 /*
487  * Parse a RTM_NEWROUTE or RTM_DELROUTE message.
488  */
parseRtMessage(const struct nlmsghdr * nh)489 bool NetlinkEvent::parseRtMessage(const struct nlmsghdr *nh) {
490     uint8_t type = nh->nlmsg_type;
491     const char *msgname = rtMessageName(type);
492 
493     if (type != RTM_NEWROUTE && type != RTM_DELROUTE) {
494         SLOGE("%s: incorrect message type %d (%s)\n", __func__, type, msgname);
495         return false;
496     }
497 
498     struct rtmsg *rtm = (struct rtmsg *) NLMSG_DATA(nh);
499     if (!checkRtNetlinkLength(nh, sizeof(*rtm)))
500         return false;
501 
502     if (// Ignore static routes we've set up ourselves.
503         (rtm->rtm_protocol != RTPROT_KERNEL &&
504          rtm->rtm_protocol != RTPROT_RA) ||
505         // We're only interested in global unicast routes.
506         (rtm->rtm_scope != RT_SCOPE_UNIVERSE) ||
507         (rtm->rtm_type != RTN_UNICAST) ||
508         // We don't support source routing.
509         (rtm->rtm_src_len != 0) ||
510         // Cloned routes aren't real routes.
511         (rtm->rtm_flags & RTM_F_CLONED)) {
512         return false;
513     }
514 
515     int family = rtm->rtm_family;
516     int prefixLength = rtm->rtm_dst_len;
517 
518     // Currently we only support: destination, (one) next hop, ifindex.
519     char dst[INET6_ADDRSTRLEN] = "";
520     char gw[INET6_ADDRSTRLEN] = "";
521     char dev[IFNAMSIZ] = "";
522 
523     size_t len = RTM_PAYLOAD(nh);
524     struct rtattr *rta;
525     for (rta = RTM_RTA(rtm); RTA_OK(rta, len); rta = RTA_NEXT(rta, len)) {
526         switch (rta->rta_type) {
527             case RTA_DST:
528                 if (maybeLogDuplicateAttribute(*dst, "RTA_DST", msgname))
529                     continue;
530                 if (!inet_ntop(family, RTA_DATA(rta), dst, sizeof(dst)))
531                     return false;
532                 continue;
533             case RTA_GATEWAY:
534                 if (maybeLogDuplicateAttribute(*gw, "RTA_GATEWAY", msgname))
535                     continue;
536                 if (!inet_ntop(family, RTA_DATA(rta), gw, sizeof(gw)))
537                     return false;
538                 continue;
539             case RTA_OIF:
540                 if (maybeLogDuplicateAttribute(*dev, "RTA_OIF", msgname))
541                     continue;
542                 if (!if_indextoname(* (int *) RTA_DATA(rta), dev))
543                     return false;
544                 continue;
545             default:
546                 continue;
547         }
548     }
549 
550    // If there's no RTA_DST attribute, then:
551    // - If the prefix length is zero, it's the default route.
552    // - If the prefix length is nonzero, there's something we don't understand.
553    //   Ignore the event.
554    if (!*dst && !prefixLength) {
555         if (family == AF_INET) {
556             strncpy(dst, "0.0.0.0", sizeof(dst));
557         } else if (family == AF_INET6) {
558             strncpy(dst, "::", sizeof(dst));
559         }
560     }
561 
562     // A useful route must have a destination and at least either a gateway or
563     // an interface.
564     if (!*dst || (!*gw && !*dev))
565         return false;
566 
567     // Fill in netlink event information.
568     mAction = (type == RTM_NEWROUTE) ? Action::kRouteUpdated :
569                                        Action::kRouteRemoved;
570     mSubsystem = strdup("net");
571     asprintf(&mParams[0], "ROUTE=%s/%d", dst, prefixLength);
572     asprintf(&mParams[1], "GATEWAY=%s", (*gw) ? gw : "");
573     asprintf(&mParams[2], "INTERFACE=%s", (*dev) ? dev : "");
574 
575     return true;
576 }
577 
578 /*
579  * Parse a RTM_NEWNDUSEROPT message.
580  */
parseNdUserOptMessage(const struct nlmsghdr * nh)581 bool NetlinkEvent::parseNdUserOptMessage(const struct nlmsghdr *nh) {
582     struct nduseroptmsg *msg = (struct nduseroptmsg *) NLMSG_DATA(nh);
583     if (!checkRtNetlinkLength(nh, sizeof(*msg)))
584         return false;
585 
586     // Check the length is valid.
587     int len = NLMSG_PAYLOAD(nh, sizeof(*msg));
588     if (msg->nduseropt_opts_len > len) {
589         SLOGE("RTM_NEWNDUSEROPT invalid length %d > %d\n",
590               msg->nduseropt_opts_len, len);
591         return false;
592     }
593     len = msg->nduseropt_opts_len;
594 
595     // Check address family and packet type.
596     if (msg->nduseropt_family != AF_INET6) {
597         SLOGE("RTM_NEWNDUSEROPT message for unknown family %d\n",
598               msg->nduseropt_family);
599         return false;
600     }
601 
602     if (msg->nduseropt_icmp_type != ND_ROUTER_ADVERT ||
603         msg->nduseropt_icmp_code != 0) {
604         SLOGE("RTM_NEWNDUSEROPT message for unknown ICMPv6 type/code %d/%d\n",
605               msg->nduseropt_icmp_type, msg->nduseropt_icmp_code);
606         return false;
607     }
608 
609     // Find the interface name.
610     char ifname[IFNAMSIZ];
611     if (!if_indextoname(msg->nduseropt_ifindex, ifname)) {
612         SLOGE("RTM_NEWNDUSEROPT on unknown ifindex %d\n",
613               msg->nduseropt_ifindex);
614         return false;
615     }
616 
617     // The kernel sends a separate netlink message for each ND option in the RA.
618     // So only parse the first ND option in the message.
619     struct nd_opt_hdr *opthdr = (struct nd_opt_hdr *) (msg + 1);
620 
621     // The length is in multiples of 8 octets.
622     uint16_t optlen = opthdr->nd_opt_len;
623     if (optlen * 8 > len) {
624         SLOGE("Invalid option length %d > %d for ND option %d\n",
625               optlen * 8, len, opthdr->nd_opt_type);
626         return false;
627     }
628 
629     if (opthdr->nd_opt_type == ND_OPT_RDNSS) {
630         // DNS Servers (RFC 6106).
631         // Each address takes up 2*8 octets, and the header takes up 8 octets.
632         // So for a valid option with one or more addresses, optlen must be
633         // odd and greater than 1.
634         if ((optlen < 3) || !(optlen & 0x1)) {
635             SLOGE("Invalid optlen %d for RDNSS option\n", optlen);
636             return false;
637         }
638         const int numaddrs = (optlen - 1) / 2;
639 
640         // Find the lifetime.
641         struct nd_opt_rdnss *rndss_opt = (struct nd_opt_rdnss *) opthdr;
642         const uint32_t lifetime = ntohl(rndss_opt->nd_opt_rdnss_lifetime);
643 
644         // Construct a comma-separated string of DNS addresses.
645         // Reserve sufficient space for an IPv6 link-local address: all but the
646         // last address are followed by ','; the last is followed by '\0'.
647         static const size_t kMaxSingleAddressLength =
648                 INET6_ADDRSTRLEN + strlen("%") + IFNAMSIZ + strlen(",");
649         const size_t bufsize = numaddrs * kMaxSingleAddressLength;
650         char *buf = (char *) malloc(bufsize);
651         if (!buf) {
652             SLOGE("RDNSS option: out of memory\n");
653             return false;
654         }
655 
656         struct in6_addr *addrs = (struct in6_addr *) (rndss_opt + 1);
657         size_t pos = 0;
658         for (int i = 0; i < numaddrs; i++) {
659             if (i > 0) {
660                 buf[pos++] = ',';
661             }
662             inet_ntop(AF_INET6, addrs + i, buf + pos, bufsize - pos);
663             pos += strlen(buf + pos);
664             if (IN6_IS_ADDR_LINKLOCAL(addrs + i)) {
665                 buf[pos++] = '%';
666                 pos += strlcpy(buf + pos, ifname, bufsize - pos);
667             }
668         }
669         buf[pos] = '\0';
670 
671         mAction = Action::kRdnss;
672         mSubsystem = strdup("net");
673         asprintf(&mParams[0], "INTERFACE=%s", ifname);
674         asprintf(&mParams[1], "LIFETIME=%u", lifetime);
675         asprintf(&mParams[2], "SERVERS=%s", buf);
676         free(buf);
677     } else if (opthdr->nd_opt_type == ND_OPT_DNSSL) {
678         // TODO: support DNSSL.
679     } else if (opthdr->nd_opt_type == ND_OPT_CAPTIVE_PORTAL) {
680         // TODO: support CAPTIVE PORTAL.
681     } else if (opthdr->nd_opt_type == ND_OPT_PREF64) {
682         // TODO: support PREF64.
683     } else {
684         SLOGD("Unknown ND option type %d\n", opthdr->nd_opt_type);
685         return false;
686     }
687 
688     return true;
689 }
690 
691 /*
692  * Parse a binary message from a NETLINK_ROUTE netlink socket.
693  *
694  * Note that this function can only parse one message, because the message's
695  * content has to be stored in the class's member variables (mAction,
696  * mSubsystem, etc.). Invalid or unrecognized messages are skipped, but if
697  * there are multiple valid messages in the buffer, only the first one will be
698  * returned.
699  *
700  * TODO: consider only ever looking at the first message.
701  */
parseBinaryNetlinkMessage(char * buffer,int size)702 bool NetlinkEvent::parseBinaryNetlinkMessage(char *buffer, int size) {
703     struct nlmsghdr *nh;
704 
705     for (nh = (struct nlmsghdr *) buffer;
706          NLMSG_OK(nh, (unsigned) size) && (nh->nlmsg_type != NLMSG_DONE);
707          nh = NLMSG_NEXT(nh, size)) {
708 
709         if (!rtMessageName(nh->nlmsg_type)) {
710             SLOGD("Unexpected netlink message type %d\n", nh->nlmsg_type);
711             continue;
712         }
713 
714         if (nh->nlmsg_type == RTM_NEWLINK) {
715             if (parseIfInfoMessage(nh))
716                 return true;
717 
718         } else if (nh->nlmsg_type == LOCAL_QLOG_NL_EVENT) {
719             if (parseUlogPacketMessage(nh))
720                 return true;
721 
722         } else if (nh->nlmsg_type == RTM_NEWADDR ||
723                    nh->nlmsg_type == RTM_DELADDR) {
724             if (parseIfAddrMessage(nh))
725                 return true;
726 
727         } else if (nh->nlmsg_type == RTM_NEWROUTE ||
728                    nh->nlmsg_type == RTM_DELROUTE) {
729             if (parseRtMessage(nh))
730                 return true;
731 
732         } else if (nh->nlmsg_type == RTM_NEWNDUSEROPT) {
733             if (parseNdUserOptMessage(nh))
734                 return true;
735 
736         } else if (nh->nlmsg_type == LOCAL_NFLOG_PACKET) {
737             if (parseNfPacketMessage(nh))
738                 return true;
739 
740         }
741     }
742 
743     return false;
744 }
745 
746 /* If the string between 'str' and 'end' begins with 'prefixlen' characters
747  * from the 'prefix' array, then return 'str + prefixlen', otherwise return
748  * NULL.
749  */
750 static const char*
has_prefix(const char * str,const char * end,const char * prefix,size_t prefixlen)751 has_prefix(const char* str, const char* end, const char* prefix, size_t prefixlen)
752 {
753     if ((end - str) >= (ptrdiff_t)prefixlen &&
754         (prefixlen == 0 || !memcmp(str, prefix, prefixlen))) {
755         return str + prefixlen;
756     } else {
757         return nullptr;
758     }
759 }
760 
761 /* Same as strlen(x) for constant string literals ONLY */
762 #define CONST_STRLEN(x)  (sizeof(x)-1)
763 
764 /* Convenience macro to call has_prefix with a constant string literal  */
765 #define HAS_CONST_PREFIX(str,end,prefix)  has_prefix((str),(end),prefix,CONST_STRLEN(prefix))
766 
767 
768 /*
769  * Parse an ASCII-formatted message from a NETLINK_KOBJECT_UEVENT
770  * netlink socket.
771  */
parseAsciiNetlinkMessage(char * buffer,int size)772 bool NetlinkEvent::parseAsciiNetlinkMessage(char *buffer, int size) {
773     const char *s = buffer;
774     const char *end;
775     int param_idx = 0;
776     int first = 1;
777 
778     if (size == 0)
779         return false;
780 
781     /* Ensure the buffer is zero-terminated, the code below depends on this */
782     buffer[size-1] = '\0';
783 
784     end = s + size;
785     while (s < end) {
786         if (first) {
787             const char *p;
788             /* buffer is 0-terminated, no need to check p < end */
789             for (p = s; *p != '@'; p++) {
790                 if (!*p) { /* no '@', should not happen */
791                     return false;
792                 }
793             }
794             mPath = strdup(p+1);
795             first = 0;
796         } else {
797             const char* a;
798             if ((a = HAS_CONST_PREFIX(s, end, "ACTION=")) != nullptr) {
799                 if (!strcmp(a, "add"))
800                     mAction = Action::kAdd;
801                 else if (!strcmp(a, "remove"))
802                     mAction = Action::kRemove;
803                 else if (!strcmp(a, "change"))
804                     mAction = Action::kChange;
805             } else if ((a = HAS_CONST_PREFIX(s, end, "SEQNUM=")) != nullptr) {
806                 if (!ParseInt(a, &mSeq)) {
807                     SLOGE("NetlinkEvent::parseAsciiNetlinkMessage: failed to parse SEQNUM=%s", a);
808                 }
809             } else if ((a = HAS_CONST_PREFIX(s, end, "SUBSYSTEM=")) != nullptr) {
810                 mSubsystem = strdup(a);
811             } else if (param_idx < NL_PARAMS_MAX) {
812                 mParams[param_idx++] = strdup(s);
813             }
814         }
815         s += strlen(s) + 1;
816     }
817     return true;
818 }
819 
decode(char * buffer,int size,int format)820 bool NetlinkEvent::decode(char *buffer, int size, int format) {
821     if (format == NetlinkListener::NETLINK_FORMAT_BINARY
822             || format == NetlinkListener::NETLINK_FORMAT_BINARY_UNICAST) {
823         return parseBinaryNetlinkMessage(buffer, size);
824     } else {
825         return parseAsciiNetlinkMessage(buffer, size);
826     }
827 }
828 
findParam(const char * paramName)829 const char *NetlinkEvent::findParam(const char *paramName) {
830     size_t len = strlen(paramName);
831     for (int i = 0; i < NL_PARAMS_MAX && mParams[i] != nullptr; ++i) {
832         const char *ptr = mParams[i] + len;
833         if (!strncmp(mParams[i], paramName, len) && *ptr == '=')
834             return ++ptr;
835     }
836 
837     SLOGE("NetlinkEvent::FindParam(): Parameter '%s' not found", paramName);
838     return nullptr;
839 }
840 
findNlAttr(const nlmsghdr * nh,size_t hdrlen,uint16_t attr)841 nlattr* NetlinkEvent::findNlAttr(const nlmsghdr* nh, size_t hdrlen, uint16_t attr) {
842     if (nh == nullptr || NLMSG_HDRLEN + NLMSG_ALIGN(hdrlen) > SSIZE_MAX) {
843         return nullptr;
844     }
845 
846     // Skip header, padding, and family header.
847     const ssize_t NLA_START = NLMSG_HDRLEN + NLMSG_ALIGN(hdrlen);
848     ssize_t left = nh->nlmsg_len - NLA_START;
849     uint8_t* hdr = ((uint8_t*)nh) + NLA_START;
850 
851     while (left >= NLA_HDRLEN) {
852         nlattr* nla = (nlattr*)hdr;
853         if (nla->nla_type == attr) {
854             return nla;
855         }
856 
857         hdr += NLA_ALIGN(nla->nla_len);
858         left -= NLA_ALIGN(nla->nla_len);
859     }
860 
861     return nullptr;
862 }
863