blob: 8fe785421a79a0985a67a37cd15f614a240ad593 [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
Lorenzo Colittid0e49382019-04-10 23:04:41 +090042#include <android-base/parseint.h>
Mark Salyzyncfd5b082016-10-17 14:28:00 -070043#include <log/log.h>
Mark Salyzyn66ce3e02016-09-28 10:07:20 -070044#include <sysutils/NetlinkEvent.h>
Jeff Sharkey9a20e672014-10-30 14:51:59 -070045
Lorenzo Colittid0e49382019-04-10 23:04:41 +090046using android::base::ParseInt;
47
San Mehat168415b2009-05-06 11:14:21 -070048NetlinkEvent::NetlinkEvent() {
Jeff Sharkeye4f39402015-03-13 13:27:33 -070049 mAction = Action::kUnknown;
San Mehatebfe3db2009-10-10 17:35:13 -070050 memset(mParams, 0, sizeof(mParams));
Yi Kong48885252018-07-24 16:34:27 -070051 mPath = nullptr;
52 mSubsystem = nullptr;
San Mehat168415b2009-05-06 11:14:21 -070053}
54
55NetlinkEvent::~NetlinkEvent() {
56 int i;
57 if (mPath)
58 free(mPath);
59 if (mSubsystem)
60 free(mSubsystem);
61 for (i = 0; i < NL_PARAMS_MAX; i++) {
62 if (!mParams[i])
63 break;
64 free(mParams[i]);
65 }
66}
67
San Mehatd6744132009-12-24 07:17:09 -080068void NetlinkEvent::dump() {
69 int i;
70
71 for (i = 0; i < NL_PARAMS_MAX; i++) {
72 if (!mParams[i])
73 break;
San Mehat7e8529a2010-03-25 09:31:42 -070074 SLOGD("NL param '%s'\n", mParams[i]);
San Mehatd6744132009-12-24 07:17:09 -080075 }
76}
77
Mike J. Chenec16b9d2011-06-23 14:55:28 -070078/*
Lorenzo Colitti9b342932014-06-19 13:16:04 +090079 * Returns the message name for a message in the NETLINK_ROUTE family, or NULL
80 * if parsing that message is not supported.
81 */
82static const char *rtMessageName(int type) {
83#define NL_EVENT_RTM_NAME(rtm) case rtm: return #rtm;
84 switch (type) {
85 NL_EVENT_RTM_NAME(RTM_NEWLINK);
86 NL_EVENT_RTM_NAME(RTM_DELLINK);
87 NL_EVENT_RTM_NAME(RTM_NEWADDR);
88 NL_EVENT_RTM_NAME(RTM_DELADDR);
89 NL_EVENT_RTM_NAME(RTM_NEWROUTE);
90 NL_EVENT_RTM_NAME(RTM_DELROUTE);
91 NL_EVENT_RTM_NAME(RTM_NEWNDUSEROPT);
Jeff Sharkey9a20e672014-10-30 14:51:59 -070092 NL_EVENT_RTM_NAME(LOCAL_QLOG_NL_EVENT);
93 NL_EVENT_RTM_NAME(LOCAL_NFLOG_PACKET);
Lorenzo Colitti9b342932014-06-19 13:16:04 +090094 default:
Yi Kong48885252018-07-24 16:34:27 -070095 return nullptr;
Lorenzo Colitti9b342932014-06-19 13:16:04 +090096 }
97#undef NL_EVENT_RTM_NAME
98}
99
100/*
101 * Checks that a binary NETLINK_ROUTE message is long enough for a payload of
102 * size bytes.
103 */
104static bool checkRtNetlinkLength(const struct nlmsghdr *nh, size_t size) {
105 if (nh->nlmsg_len < NLMSG_LENGTH(size)) {
106 SLOGE("Got a short %s message\n", rtMessageName(nh->nlmsg_type));
107 return false;
108 }
109 return true;
110}
111
112/*
113 * Utility function to log errors.
114 */
115static bool maybeLogDuplicateAttribute(bool isDup,
116 const char *attributeName,
117 const char *messageName) {
118 if (isDup) {
119 SLOGE("Multiple %s attributes in %s, ignoring\n", attributeName, messageName);
120 return true;
121 }
122 return false;
123}
124
125/*
126 * Parse a RTM_NEWLINK message.
127 */
128bool NetlinkEvent::parseIfInfoMessage(const struct nlmsghdr *nh) {
129 struct ifinfomsg *ifi = (struct ifinfomsg *) NLMSG_DATA(nh);
130 if (!checkRtNetlinkLength(nh, sizeof(*ifi)))
131 return false;
132
133 if ((ifi->ifi_flags & IFF_LOOPBACK) != 0) {
134 return false;
135 }
136
137 int len = IFLA_PAYLOAD(nh);
138 struct rtattr *rta;
139 for (rta = IFLA_RTA(ifi); RTA_OK(rta, len); rta = RTA_NEXT(rta, len)) {
140 switch(rta->rta_type) {
141 case IFLA_IFNAME:
142 asprintf(&mParams[0], "INTERFACE=%s", (char *) RTA_DATA(rta));
Chenbo Feng5e5e5e92018-03-02 01:32:53 -0800143 // We can get the interface change information from sysfs update
144 // already. But in case we missed those message when devices start.
145 // We do a update again when received a kLinkUp event. To make
146 // the message consistent, use IFINDEX here as well since sysfs
147 // uses IFINDEX.
148 asprintf(&mParams[1], "IFINDEX=%d", ifi->ifi_index);
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700149 mAction = (ifi->ifi_flags & IFF_LOWER_UP) ? Action::kLinkUp :
150 Action::kLinkDown;
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900151 mSubsystem = strdup("net");
152 return true;
153 }
154 }
155
156 return false;
157}
158
159/*
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900160 * Parse a RTM_NEWADDR or RTM_DELADDR message.
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900161 */
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900162bool NetlinkEvent::parseIfAddrMessage(const struct nlmsghdr *nh) {
163 struct ifaddrmsg *ifaddr = (struct ifaddrmsg *) NLMSG_DATA(nh);
Yi Kong48885252018-07-24 16:34:27 -0700164 struct ifa_cacheinfo *cacheinfo = nullptr;
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900165 char addrstr[INET6_ADDRSTRLEN] = "";
Lorenzo Colittief6454d2016-02-16 21:42:16 +0900166 char ifname[IFNAMSIZ] = "";
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900167
168 if (!checkRtNetlinkLength(nh, sizeof(*ifaddr)))
169 return false;
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900170
171 // Sanity check.
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900172 int type = nh->nlmsg_type;
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900173 if (type != RTM_NEWADDR && type != RTM_DELADDR) {
174 SLOGE("parseIfAddrMessage on incorrect message type 0x%x\n", type);
175 return false;
176 }
177
178 // For log messages.
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900179 const char *msgtype = rtMessageName(type);
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900180
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900181 struct rtattr *rta;
182 int len = IFA_PAYLOAD(nh);
183 for (rta = IFA_RTA(ifaddr); RTA_OK(rta, len); rta = RTA_NEXT(rta, len)) {
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900184 if (rta->rta_type == IFA_ADDRESS) {
185 // Only look at the first address, because we only support notifying
186 // one change at a time.
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900187 if (maybeLogDuplicateAttribute(*addrstr != '\0', "IFA_ADDRESS", msgtype))
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900188 continue;
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900189
190 // Convert the IP address to a string.
191 if (ifaddr->ifa_family == AF_INET) {
192 struct in_addr *addr4 = (struct in_addr *) RTA_DATA(rta);
193 if (RTA_PAYLOAD(rta) < sizeof(*addr4)) {
Mark Salyzyn80f63d42014-05-01 07:47:04 -0700194 SLOGE("Short IPv4 address (%zu bytes) in %s",
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900195 RTA_PAYLOAD(rta), msgtype);
196 continue;
197 }
198 inet_ntop(AF_INET, addr4, addrstr, sizeof(addrstr));
199 } else if (ifaddr->ifa_family == AF_INET6) {
200 struct in6_addr *addr6 = (struct in6_addr *) RTA_DATA(rta);
201 if (RTA_PAYLOAD(rta) < sizeof(*addr6)) {
Mark Salyzyn80f63d42014-05-01 07:47:04 -0700202 SLOGE("Short IPv6 address (%zu bytes) in %s",
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900203 RTA_PAYLOAD(rta), msgtype);
204 continue;
205 }
206 inet_ntop(AF_INET6, addr6, addrstr, sizeof(addrstr));
207 } else {
208 SLOGE("Unknown address family %d\n", ifaddr->ifa_family);
209 continue;
210 }
211
212 // Find the interface name.
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900213 if (!if_indextoname(ifaddr->ifa_index, ifname)) {
Lorenzo Colittief6454d2016-02-16 21:42:16 +0900214 SLOGD("Unknown ifindex %d in %s", ifaddr->ifa_index, msgtype);
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900215 }
216
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900217 } else if (rta->rta_type == IFA_CACHEINFO) {
218 // Address lifetime information.
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900219 if (maybeLogDuplicateAttribute(cacheinfo, "IFA_CACHEINFO", msgtype))
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900220 continue;
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900221
222 if (RTA_PAYLOAD(rta) < sizeof(*cacheinfo)) {
Mark Salyzyn80f63d42014-05-01 07:47:04 -0700223 SLOGE("Short IFA_CACHEINFO (%zu vs. %zu bytes) in %s",
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900224 RTA_PAYLOAD(rta), sizeof(cacheinfo), msgtype);
225 continue;
226 }
227
228 cacheinfo = (struct ifa_cacheinfo *) RTA_DATA(rta);
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900229 }
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900230 }
231
232 if (addrstr[0] == '\0') {
233 SLOGE("No IFA_ADDRESS in %s\n", msgtype);
234 return false;
235 }
236
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900237 // Fill in netlink event information.
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700238 mAction = (type == RTM_NEWADDR) ? Action::kAddressUpdated :
239 Action::kAddressRemoved;
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900240 mSubsystem = strdup("net");
Lorenzo Colittief6454d2016-02-16 21:42:16 +0900241 asprintf(&mParams[0], "ADDRESS=%s/%d", addrstr, ifaddr->ifa_prefixlen);
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900242 asprintf(&mParams[1], "INTERFACE=%s", ifname);
243 asprintf(&mParams[2], "FLAGS=%u", ifaddr->ifa_flags);
244 asprintf(&mParams[3], "SCOPE=%u", ifaddr->ifa_scope);
Rubin Xu5f406242018-05-16 23:35:41 +0100245 asprintf(&mParams[4], "IFINDEX=%u", ifaddr->ifa_index);
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900246
247 if (cacheinfo) {
Rubin Xu5f406242018-05-16 23:35:41 +0100248 asprintf(&mParams[5], "PREFERRED=%u", cacheinfo->ifa_prefered);
249 asprintf(&mParams[6], "VALID=%u", cacheinfo->ifa_valid);
250 asprintf(&mParams[7], "CSTAMP=%u", cacheinfo->cstamp);
251 asprintf(&mParams[8], "TSTAMP=%u", cacheinfo->tstamp);
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900252 }
253
254 return true;
255}
256
257/*
258 * Parse a QLOG_NL_EVENT message.
259 */
260bool NetlinkEvent::parseUlogPacketMessage(const struct nlmsghdr *nh) {
261 const char *devname;
262 ulog_packet_msg_t *pm = (ulog_packet_msg_t *) NLMSG_DATA(nh);
263 if (!checkRtNetlinkLength(nh, sizeof(*pm)))
264 return false;
265
266 devname = pm->indev_name[0] ? pm->indev_name : pm->outdev_name;
267 asprintf(&mParams[0], "ALERT_NAME=%s", pm->prefix);
268 asprintf(&mParams[1], "INTERFACE=%s", devname);
269 mSubsystem = strdup("qlog");
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700270 mAction = Action::kChange;
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900271 return true;
272}
273
Lorenzo Colittie439ffc2017-10-03 18:44:11 +0900274static size_t nlAttrLen(const nlattr* nla) {
275 return nla->nla_len - NLA_HDRLEN;
276}
277
278static const uint8_t* nlAttrData(const nlattr* nla) {
279 return reinterpret_cast<const uint8_t*>(nla) + NLA_HDRLEN;
280}
281
282static uint32_t nlAttrU32(const nlattr* nla) {
283 return *reinterpret_cast<const uint32_t*>(nlAttrData(nla));
284}
285
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900286/*
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700287 * Parse a LOCAL_NFLOG_PACKET message.
288 */
289bool NetlinkEvent::parseNfPacketMessage(struct nlmsghdr *nh) {
290 int uid = -1;
291 int len = 0;
Yi Kong48885252018-07-24 16:34:27 -0700292 char* raw = nullptr;
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700293
Lorenzo Colittie439ffc2017-10-03 18:44:11 +0900294 struct nlattr* uid_attr = findNlAttr(nh, sizeof(struct genlmsghdr), NFULA_UID);
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700295 if (uid_attr) {
Lorenzo Colittie439ffc2017-10-03 18:44:11 +0900296 uid = ntohl(nlAttrU32(uid_attr));
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700297 }
298
Lorenzo Colittie439ffc2017-10-03 18:44:11 +0900299 struct nlattr* payload = findNlAttr(nh, sizeof(struct genlmsghdr), NFULA_PAYLOAD);
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700300 if (payload) {
301 /* First 256 bytes is plenty */
Lorenzo Colittie439ffc2017-10-03 18:44:11 +0900302 len = nlAttrLen(payload);
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700303 if (len > 256) len = 256;
Lorenzo Colittie439ffc2017-10-03 18:44:11 +0900304 raw = (char*)nlAttrData(payload);
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700305 }
306
Lorenzo Colittid0e49382019-04-10 23:04:41 +0900307 size_t hexSize = 5 + (len * 2);
308 char* hex = (char*)calloc(1, hexSize);
309 strlcpy(hex, "HEX=", hexSize);
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700310 for (int i = 0; i < len; i++) {
311 hex[4 + (i * 2)] = "0123456789abcdef"[(raw[i] >> 4) & 0xf];
312 hex[5 + (i * 2)] = "0123456789abcdef"[raw[i] & 0xf];
313 }
314
315 asprintf(&mParams[0], "UID=%d", uid);
316 mParams[1] = hex;
317 mSubsystem = strdup("strict");
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700318 mAction = Action::kChange;
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700319 return true;
320}
321
322/*
Lorenzo Colittid7ff7ea2014-06-11 17:37:12 +0900323 * Parse a RTM_NEWROUTE or RTM_DELROUTE message.
324 */
325bool NetlinkEvent::parseRtMessage(const struct nlmsghdr *nh) {
326 uint8_t type = nh->nlmsg_type;
327 const char *msgname = rtMessageName(type);
328
329 // Sanity check.
330 if (type != RTM_NEWROUTE && type != RTM_DELROUTE) {
331 SLOGE("%s: incorrect message type %d (%s)\n", __func__, type, msgname);
332 return false;
333 }
334
335 struct rtmsg *rtm = (struct rtmsg *) NLMSG_DATA(nh);
336 if (!checkRtNetlinkLength(nh, sizeof(*rtm)))
337 return false;
338
339 if (// Ignore static routes we've set up ourselves.
340 (rtm->rtm_protocol != RTPROT_KERNEL &&
341 rtm->rtm_protocol != RTPROT_RA) ||
342 // We're only interested in global unicast routes.
343 (rtm->rtm_scope != RT_SCOPE_UNIVERSE) ||
344 (rtm->rtm_type != RTN_UNICAST) ||
345 // We don't support source routing.
346 (rtm->rtm_src_len != 0) ||
347 // Cloned routes aren't real routes.
348 (rtm->rtm_flags & RTM_F_CLONED)) {
349 return false;
350 }
351
352 int family = rtm->rtm_family;
353 int prefixLength = rtm->rtm_dst_len;
354
355 // Currently we only support: destination, (one) next hop, ifindex.
356 char dst[INET6_ADDRSTRLEN] = "";
357 char gw[INET6_ADDRSTRLEN] = "";
358 char dev[IFNAMSIZ] = "";
359
360 size_t len = RTM_PAYLOAD(nh);
361 struct rtattr *rta;
362 for (rta = RTM_RTA(rtm); RTA_OK(rta, len); rta = RTA_NEXT(rta, len)) {
363 switch (rta->rta_type) {
364 case RTA_DST:
365 if (maybeLogDuplicateAttribute(*dst, "RTA_DST", msgname))
366 continue;
367 if (!inet_ntop(family, RTA_DATA(rta), dst, sizeof(dst)))
368 return false;
369 continue;
370 case RTA_GATEWAY:
371 if (maybeLogDuplicateAttribute(*gw, "RTA_GATEWAY", msgname))
372 continue;
373 if (!inet_ntop(family, RTA_DATA(rta), gw, sizeof(gw)))
374 return false;
375 continue;
376 case RTA_OIF:
377 if (maybeLogDuplicateAttribute(*dev, "RTA_OIF", msgname))
378 continue;
379 if (!if_indextoname(* (int *) RTA_DATA(rta), dev))
380 return false;
Chih-Hung Hsiehe6e2b3c2018-10-10 14:39:02 -0700381 continue;
Lorenzo Colittid7ff7ea2014-06-11 17:37:12 +0900382 default:
383 continue;
384 }
385 }
386
387 // If there's no RTA_DST attribute, then:
388 // - If the prefix length is zero, it's the default route.
389 // - If the prefix length is nonzero, there's something we don't understand.
390 // Ignore the event.
391 if (!*dst && !prefixLength) {
392 if (family == AF_INET) {
393 strncpy(dst, "0.0.0.0", sizeof(dst));
394 } else if (family == AF_INET6) {
395 strncpy(dst, "::", sizeof(dst));
396 }
397 }
398
399 // A useful route must have a destination and at least either a gateway or
400 // an interface.
401 if (!*dst || (!*gw && !*dev))
402 return false;
403
404 // Fill in netlink event information.
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700405 mAction = (type == RTM_NEWROUTE) ? Action::kRouteUpdated :
406 Action::kRouteRemoved;
Lorenzo Colittid7ff7ea2014-06-11 17:37:12 +0900407 mSubsystem = strdup("net");
408 asprintf(&mParams[0], "ROUTE=%s/%d", dst, prefixLength);
409 asprintf(&mParams[1], "GATEWAY=%s", (*gw) ? gw : "");
410 asprintf(&mParams[2], "INTERFACE=%s", (*dev) ? dev : "");
411
412 return true;
413}
414
415/*
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900416 * Parse a RTM_NEWNDUSEROPT message.
417 */
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900418bool NetlinkEvent::parseNdUserOptMessage(const struct nlmsghdr *nh) {
419 struct nduseroptmsg *msg = (struct nduseroptmsg *) NLMSG_DATA(nh);
420 if (!checkRtNetlinkLength(nh, sizeof(*msg)))
421 return false;
422
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900423 // Check the length is valid.
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900424 int len = NLMSG_PAYLOAD(nh, sizeof(*msg));
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900425 if (msg->nduseropt_opts_len > len) {
426 SLOGE("RTM_NEWNDUSEROPT invalid length %d > %d\n",
427 msg->nduseropt_opts_len, len);
428 return false;
429 }
430 len = msg->nduseropt_opts_len;
431
432 // Check address family and packet type.
433 if (msg->nduseropt_family != AF_INET6) {
434 SLOGE("RTM_NEWNDUSEROPT message for unknown family %d\n",
435 msg->nduseropt_family);
436 return false;
437 }
438
439 if (msg->nduseropt_icmp_type != ND_ROUTER_ADVERT ||
440 msg->nduseropt_icmp_code != 0) {
441 SLOGE("RTM_NEWNDUSEROPT message for unknown ICMPv6 type/code %d/%d\n",
442 msg->nduseropt_icmp_type, msg->nduseropt_icmp_code);
443 return false;
444 }
445
446 // Find the interface name.
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900447 char ifname[IFNAMSIZ];
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900448 if (!if_indextoname(msg->nduseropt_ifindex, ifname)) {
449 SLOGE("RTM_NEWNDUSEROPT on unknown ifindex %d\n",
450 msg->nduseropt_ifindex);
451 return false;
452 }
453
454 // The kernel sends a separate netlink message for each ND option in the RA.
455 // So only parse the first ND option in the message.
456 struct nd_opt_hdr *opthdr = (struct nd_opt_hdr *) (msg + 1);
457
458 // The length is in multiples of 8 octets.
459 uint16_t optlen = opthdr->nd_opt_len;
460 if (optlen * 8 > len) {
461 SLOGE("Invalid option length %d > %d for ND option %d\n",
462 optlen * 8, len, opthdr->nd_opt_type);
463 return false;
464 }
465
466 if (opthdr->nd_opt_type == ND_OPT_RDNSS) {
467 // DNS Servers (RFC 6106).
468 // Each address takes up 2*8 octets, and the header takes up 8 octets.
469 // So for a valid option with one or more addresses, optlen must be
470 // odd and greater than 1.
471 if ((optlen < 3) || !(optlen & 0x1)) {
472 SLOGE("Invalid optlen %d for RDNSS option\n", optlen);
473 return false;
474 }
Erik Klineba48ff72015-06-17 15:53:29 +0900475 const int numaddrs = (optlen - 1) / 2;
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900476
477 // Find the lifetime.
478 struct nd_opt_rdnss *rndss_opt = (struct nd_opt_rdnss *) opthdr;
Erik Klineba48ff72015-06-17 15:53:29 +0900479 const uint32_t lifetime = ntohl(rndss_opt->nd_opt_rdnss_lifetime);
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900480
Lorenzo Colittid0e49382019-04-10 23:04:41 +0900481 // Construct a comma-separated string of DNS addresses.
Erik Klineba48ff72015-06-17 15:53:29 +0900482 // Reserve sufficient space for an IPv6 link-local address: all but the
483 // last address are followed by ','; the last is followed by '\0'.
Erik Klinecc451782015-07-28 17:31:19 +0900484 static const size_t kMaxSingleAddressLength =
Erik Klineba48ff72015-06-17 15:53:29 +0900485 INET6_ADDRSTRLEN + strlen("%") + IFNAMSIZ + strlen(",");
Lorenzo Colittid0e49382019-04-10 23:04:41 +0900486 const size_t bufsize = numaddrs * kMaxSingleAddressLength;
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900487 char *buf = (char *) malloc(bufsize);
488 if (!buf) {
489 SLOGE("RDNSS option: out of memory\n");
490 return false;
491 }
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900492
493 struct in6_addr *addrs = (struct in6_addr *) (rndss_opt + 1);
Lorenzo Colittid0e49382019-04-10 23:04:41 +0900494 size_t pos = 0;
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900495 for (int i = 0; i < numaddrs; i++) {
496 if (i > 0) {
497 buf[pos++] = ',';
498 }
499 inet_ntop(AF_INET6, addrs + i, buf + pos, bufsize - pos);
500 pos += strlen(buf + pos);
Erik Klineba48ff72015-06-17 15:53:29 +0900501 if (IN6_IS_ADDR_LINKLOCAL(addrs + i)) {
502 buf[pos++] = '%';
503 pos += strlcpy(buf + pos, ifname, bufsize - pos);
504 }
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900505 }
506 buf[pos] = '\0';
507
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700508 mAction = Action::kRdnss;
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900509 mSubsystem = strdup("net");
510 asprintf(&mParams[0], "INTERFACE=%s", ifname);
511 asprintf(&mParams[1], "LIFETIME=%u", lifetime);
Lorenzo Colittid0e49382019-04-10 23:04:41 +0900512 asprintf(&mParams[2], "SERVERS=%s", buf);
513 free(buf);
Lorenzo Colitticbfd65d2017-11-28 15:32:40 +0900514 } else if (opthdr->nd_opt_type == ND_OPT_DNSSL) {
515 // TODO: support DNSSL.
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900516 } else {
517 SLOGD("Unknown ND option type %d\n", opthdr->nd_opt_type);
518 return false;
519 }
520
521 return true;
522}
523
524/*
525 * Parse a binary message from a NETLINK_ROUTE netlink socket.
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900526 *
527 * Note that this function can only parse one message, because the message's
528 * content has to be stored in the class's member variables (mAction,
529 * mSubsystem, etc.). Invalid or unrecognized messages are skipped, but if
530 * there are multiple valid messages in the buffer, only the first one will be
531 * returned.
532 *
533 * TODO: consider only ever looking at the first message.
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700534 */
535bool NetlinkEvent::parseBinaryNetlinkMessage(char *buffer, int size) {
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700536 struct nlmsghdr *nh;
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700537
Lorenzo Colitti96834562013-08-17 03:40:31 +0900538 for (nh = (struct nlmsghdr *) buffer;
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900539 NLMSG_OK(nh, (unsigned) size) && (nh->nlmsg_type != NLMSG_DONE);
Lorenzo Colitti96834562013-08-17 03:40:31 +0900540 nh = NLMSG_NEXT(nh, size)) {
JP Abgralle6f80142011-07-14 16:46:32 -0700541
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900542 if (!rtMessageName(nh->nlmsg_type)) {
543 SLOGD("Unexpected netlink message type %d\n", nh->nlmsg_type);
544 continue;
545 }
546
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700547 if (nh->nlmsg_type == RTM_NEWLINK) {
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900548 if (parseIfInfoMessage(nh))
549 return true;
JP Abgralle6f80142011-07-14 16:46:32 -0700550
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700551 } else if (nh->nlmsg_type == LOCAL_QLOG_NL_EVENT) {
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900552 if (parseUlogPacketMessage(nh))
553 return true;
JP Abgralle6f80142011-07-14 16:46:32 -0700554
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900555 } else if (nh->nlmsg_type == RTM_NEWADDR ||
556 nh->nlmsg_type == RTM_DELADDR) {
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900557 if (parseIfAddrMessage(nh))
558 return true;
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900559
Lorenzo Colittid7ff7ea2014-06-11 17:37:12 +0900560 } else if (nh->nlmsg_type == RTM_NEWROUTE ||
561 nh->nlmsg_type == RTM_DELROUTE) {
562 if (parseRtMessage(nh))
563 return true;
564
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900565 } else if (nh->nlmsg_type == RTM_NEWNDUSEROPT) {
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900566 if (parseNdUserOptMessage(nh))
567 return true;
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900568
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700569 } else if (nh->nlmsg_type == LOCAL_NFLOG_PACKET) {
570 if (parseNfPacketMessage(nh))
571 return true;
572
JP Abgralle6f80142011-07-14 16:46:32 -0700573 }
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700574 }
575
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900576 return false;
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700577}
578
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100579/* If the string between 'str' and 'end' begins with 'prefixlen' characters
580 * from the 'prefix' array, then return 'str + prefixlen', otherwise return
581 * NULL.
582 */
583static const char*
584has_prefix(const char* str, const char* end, const char* prefix, size_t prefixlen)
585{
Yunlian Jiang33f67172017-02-07 15:39:25 -0800586 if ((end - str) >= (ptrdiff_t)prefixlen &&
587 (prefixlen == 0 || !memcmp(str, prefix, prefixlen))) {
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100588 return str + prefixlen;
Yunlian Jiang33f67172017-02-07 15:39:25 -0800589 } else {
Yi Kong48885252018-07-24 16:34:27 -0700590 return nullptr;
Yunlian Jiang33f67172017-02-07 15:39:25 -0800591 }
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100592}
593
594/* Same as strlen(x) for constant string literals ONLY */
595#define CONST_STRLEN(x) (sizeof(x)-1)
596
597/* Convenience macro to call has_prefix with a constant string literal */
598#define HAS_CONST_PREFIX(str,end,prefix) has_prefix((str),(end),prefix,CONST_STRLEN(prefix))
599
600
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700601/*
602 * Parse an ASCII-formatted message from a NETLINK_KOBJECT_UEVENT
603 * netlink socket.
604 */
605bool NetlinkEvent::parseAsciiNetlinkMessage(char *buffer, int size) {
Mike J. Chen17260b12011-06-23 15:00:30 -0700606 const char *s = buffer;
607 const char *end;
San Mehat168415b2009-05-06 11:14:21 -0700608 int param_idx = 0;
San Mehat168415b2009-05-06 11:14:21 -0700609 int first = 1;
610
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100611 if (size == 0)
612 return false;
613
614 /* Ensure the buffer is zero-terminated, the code below depends on this */
615 buffer[size-1] = '\0';
616
San Mehat168415b2009-05-06 11:14:21 -0700617 end = s + size;
618 while (s < end) {
619 if (first) {
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100620 const char *p;
621 /* buffer is 0-terminated, no need to check p < end */
622 for (p = s; *p != '@'; p++) {
623 if (!*p) { /* no '@', should not happen */
624 return false;
625 }
626 }
627 mPath = strdup(p+1);
San Mehat168415b2009-05-06 11:14:21 -0700628 first = 0;
629 } else {
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100630 const char* a;
Yi Kong48885252018-07-24 16:34:27 -0700631 if ((a = HAS_CONST_PREFIX(s, end, "ACTION=")) != nullptr) {
San Mehat168415b2009-05-06 11:14:21 -0700632 if (!strcmp(a, "add"))
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700633 mAction = Action::kAdd;
San Mehat168415b2009-05-06 11:14:21 -0700634 else if (!strcmp(a, "remove"))
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700635 mAction = Action::kRemove;
San Mehat168415b2009-05-06 11:14:21 -0700636 else if (!strcmp(a, "change"))
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700637 mAction = Action::kChange;
Yi Kong48885252018-07-24 16:34:27 -0700638 } else if ((a = HAS_CONST_PREFIX(s, end, "SEQNUM=")) != nullptr) {
Lorenzo Colittid0e49382019-04-10 23:04:41 +0900639 if (!ParseInt(a, &mSeq)) {
640 SLOGE("NetlinkEvent::parseAsciiNetlinkMessage: failed to parse SEQNUM=%s", a);
641 }
Yi Kong48885252018-07-24 16:34:27 -0700642 } else if ((a = HAS_CONST_PREFIX(s, end, "SUBSYSTEM=")) != nullptr) {
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100643 mSubsystem = strdup(a);
644 } else if (param_idx < NL_PARAMS_MAX) {
San Mehat168415b2009-05-06 11:14:21 -0700645 mParams[param_idx++] = strdup(s);
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100646 }
San Mehat168415b2009-05-06 11:14:21 -0700647 }
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100648 s += strlen(s) + 1;
San Mehat168415b2009-05-06 11:14:21 -0700649 }
650 return true;
651}
652
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700653bool NetlinkEvent::decode(char *buffer, int size, int format) {
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700654 if (format == NetlinkListener::NETLINK_FORMAT_BINARY
655 || format == NetlinkListener::NETLINK_FORMAT_BINARY_UNICAST) {
Mike J. Chen17260b12011-06-23 15:00:30 -0700656 return parseBinaryNetlinkMessage(buffer, size);
657 } else {
658 return parseAsciiNetlinkMessage(buffer, size);
659 }
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700660}
661
San Mehat168415b2009-05-06 11:14:21 -0700662const char *NetlinkEvent::findParam(const char *paramName) {
Chih-Wei Huang80ec37a2010-07-14 14:00:41 +0800663 size_t len = strlen(paramName);
Yi Kong48885252018-07-24 16:34:27 -0700664 for (int i = 0; i < NL_PARAMS_MAX && mParams[i] != nullptr; ++i) {
Chih-Wei Huang80ec37a2010-07-14 14:00:41 +0800665 const char *ptr = mParams[i] + len;
666 if (!strncmp(mParams[i], paramName, len) && *ptr == '=')
667 return ++ptr;
San Mehat168415b2009-05-06 11:14:21 -0700668 }
669
San Mehat7e8529a2010-03-25 09:31:42 -0700670 SLOGE("NetlinkEvent::FindParam(): Parameter '%s' not found", paramName);
Yi Kong48885252018-07-24 16:34:27 -0700671 return nullptr;
San Mehat168415b2009-05-06 11:14:21 -0700672}
Lorenzo Colittie439ffc2017-10-03 18:44:11 +0900673
674nlattr* NetlinkEvent::findNlAttr(const nlmsghdr* nh, size_t hdrlen, uint16_t attr) {
675 if (nh == nullptr || NLMSG_HDRLEN + NLMSG_ALIGN(hdrlen) > SSIZE_MAX) {
676 return nullptr;
677 }
678
679 // Skip header, padding, and family header.
680 const ssize_t NLA_START = NLMSG_HDRLEN + NLMSG_ALIGN(hdrlen);
681 ssize_t left = nh->nlmsg_len - NLA_START;
682 uint8_t* hdr = ((uint8_t*)nh) + NLA_START;
683
684 while (left >= NLA_HDRLEN) {
685 nlattr* nla = (nlattr*)hdr;
686 if (nla->nla_type == attr) {
687 return nla;
688 }
689
690 hdr += NLA_ALIGN(nla->nla_len);
691 left -= NLA_ALIGN(nla->nla_len);
692 }
693
694 return nullptr;
695}