1 /*
2  * Copyright (C) 2017 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 #include <errno.h>
18 #include <linux/netlink.h>
19 #include <linux/rtnetlink.h>
20 #include <sys/socket.h>
21 #include <sys/types.h>
22 #include <sys/uio.h>
23 #include <unistd.h>
24 
25 #define LOG_TAG "Netd"
26 #include <log/log.h>
27 
28 #include "NetdConstants.h"
29 #include "NetlinkCommands.h"
30 
31 namespace android {
32 namespace net {
33 
openNetlinkSocket(int protocol)34 int openNetlinkSocket(int protocol) {
35     int sock = socket(AF_NETLINK, SOCK_DGRAM | SOCK_CLOEXEC, protocol);
36     if (sock == -1) {
37         return -errno;
38     }
39     if (connect(sock, reinterpret_cast<const sockaddr*>(&KERNEL_NLADDR),
40                 sizeof(KERNEL_NLADDR)) == -1) {
41         close(sock);
42         return -errno;
43     }
44     return sock;
45 }
46 
recvNetlinkAck(int sock)47 int recvNetlinkAck(int sock) {
48     struct {
49         nlmsghdr msg;
50         nlmsgerr err;
51     } response;
52 
53     int ret = recv(sock, &response, sizeof(response), 0);
54 
55     if (ret == -1) {
56         ret = -errno;
57         ALOGE("netlink recv failed (%s)", strerror(-ret));
58         return ret;
59     }
60 
61     if (ret != sizeof(response)) {
62         ALOGE("bad netlink response message size (%d != %zu)", ret, sizeof(response));
63         return -EBADMSG;
64     }
65 
66     return response.err.error;  // Netlink errors are negative errno.
67 }
68 
69 // Disable optimizations in ASan build.
70 // ASan reports an out-of-bounds 32-bit(!) access in the first loop of the function (over iov[]).
71 // TODO: verify if this bug is still present.
72 #ifdef __clang__
73 #if __has_feature(address_sanitizer)
74 #define OPTNONE [[clang::optnone]]
75 #endif
76 #endif
77 
78 #ifndef OPTNONE
79 #define OPTNONE /* nop */
80 #endif
81 
82 // Sends a netlink request and possibly expects an ack.
83 // |iov| is an array of struct iovec that contains the netlink message payload.
84 // The netlink header is generated by this function based on |action| and |flags|.
85 // Returns -errno if there was an error or if the kernel reported an error.
sendNetlinkRequest(uint16_t action,uint16_t flags,iovec * iov,int iovlen,const NetlinkDumpCallback * callback)86 OPTNONE int sendNetlinkRequest(uint16_t action, uint16_t flags, iovec* iov, int iovlen,
87                                const NetlinkDumpCallback* callback) {
88     int sock = openNetlinkSocket(NETLINK_ROUTE);
89     if (sock < 0) {
90         return sock;
91     }
92 
93     nlmsghdr nlmsg = {
94         .nlmsg_type = action,
95         .nlmsg_flags = flags,
96     };
97     iov[0].iov_base = &nlmsg;
98     iov[0].iov_len = sizeof(nlmsg);
99     for (int i = 0; i < iovlen; ++i) {
100         nlmsg.nlmsg_len += iov[i].iov_len;
101     }
102 
103     ssize_t writevRet = writev(sock, iov, iovlen);
104     // Don't let pointers to the stack escape.
105     iov[0] = {nullptr, 0};
106     int ret = 0;
107     if (writevRet == -1) {
108         ret = -errno;
109         ALOGE("netlink socket connect/writev failed (%s)", strerror(-ret));
110         close(sock);
111         return ret;
112     }
113 
114     if (flags & NLM_F_ACK) {
115         ret = recvNetlinkAck(sock);
116     } else if ((flags & NLM_F_DUMP) && callback != nullptr) {
117         ret = processNetlinkDump(sock, *callback);
118     }
119 
120     close(sock);
121 
122     return ret;
123 }
124 
sendNetlinkRequest(uint16_t action,uint16_t flags,iovec * iov,int iovlen)125 int sendNetlinkRequest(uint16_t action, uint16_t flags, iovec* iov, int iovlen) {
126     return sendNetlinkRequest(action, flags, iov, iovlen, nullptr);
127 }
128 
processNetlinkDump(int sock,const NetlinkDumpCallback & callback)129 int processNetlinkDump(int sock, const NetlinkDumpCallback& callback) {
130     char buf[kNetlinkDumpBufferSize];
131 
132     ssize_t bytesread;
133     do {
134         bytesread = read(sock, buf, sizeof(buf));
135 
136         if (bytesread < 0) {
137             return -errno;
138         }
139 
140         uint32_t len = bytesread;
141         for (nlmsghdr *nlh = reinterpret_cast<nlmsghdr *>(buf);
142              NLMSG_OK(nlh, len);
143              nlh = NLMSG_NEXT(nlh, len)) {
144             switch (nlh->nlmsg_type) {
145               case NLMSG_DONE:
146                 return 0;
147               case NLMSG_ERROR: {
148                 nlmsgerr *err = reinterpret_cast<nlmsgerr *>(NLMSG_DATA(nlh));
149                 return err->error;
150               }
151               default:
152                 callback(nlh);
153             }
154         }
155     } while (bytesread > 0);
156 
157     return 0;
158 }
159 
rtNetlinkFlush(uint16_t getAction,uint16_t deleteAction,const char * what,const NetlinkDumpFilter & shouldDelete)160 int rtNetlinkFlush(uint16_t getAction, uint16_t deleteAction, const char* what,
161                    const NetlinkDumpFilter& shouldDelete) {
162     // RTM_GETxxx is always RTM_DELxxx + 1, see <linux/rtnetlink.h>.
163     if (getAction != deleteAction + 1) {
164         ALOGE("Unknown flush type getAction=%d deleteAction=%d", getAction, deleteAction);
165         return -EINVAL;
166     }
167 
168     int writeSock = openNetlinkSocket(NETLINK_ROUTE);
169     if (writeSock < 0) {
170         return writeSock;
171     }
172 
173     NetlinkDumpCallback callback = [writeSock, deleteAction, shouldDelete, what] (nlmsghdr *nlh) {
174         if (!shouldDelete(nlh)) return;
175 
176         nlh->nlmsg_type = deleteAction;
177         nlh->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
178         if (write(writeSock, nlh, nlh->nlmsg_len) == -1) {
179             ALOGE("Error writing flush request: %s", strerror(errno));
180             return;
181         }
182 
183         int ret = recvNetlinkAck(writeSock);
184         // A flush works by dumping routes and deleting each route as it's returned, and it can
185         // fail if something else deletes the route between the dump and the delete. This can
186         // happen, for example, if an interface goes down while we're trying to flush its routes.
187         // So ignore ENOENT.
188         if (ret != 0 && ret != -ENOENT) {
189             ALOGW("Flushing %s: %s", what, strerror(-ret));
190         }
191     };
192 
193     int ret = 0;
194     for (const int family : { AF_INET, AF_INET6 }) {
195         // struct fib_rule_hdr and struct rtmsg are functionally identical.
196         rtmsg rule = {
197             .rtm_family = static_cast<uint8_t>(family),
198         };
199         iovec iov[] = {
200             { nullptr,  0 },
201             { &rule, sizeof(rule) },
202         };
203         uint16_t flags = NETLINK_DUMP_FLAGS;
204 
205         if ((ret = sendNetlinkRequest(getAction, flags, iov, ARRAY_SIZE(iov), &callback)) != 0) {
206             break;
207         }
208     }
209 
210     close(writeSock);
211 
212     return ret;
213 }
214 
getRtmU32Attribute(const nlmsghdr * nlh,int attribute)215 uint32_t getRtmU32Attribute(const nlmsghdr* nlh, int attribute) {
216     uint32_t rta_len = RTM_PAYLOAD(nlh);
217     rtmsg *msg = reinterpret_cast<rtmsg *>(NLMSG_DATA(nlh));
218     rtattr *rta = reinterpret_cast<rtattr *> RTM_RTA(msg);
219     for (; RTA_OK(rta, rta_len); rta = RTA_NEXT(rta, rta_len)) {
220         if (rta->rta_type == attribute) {
221             return *(static_cast<uint32_t *>(RTA_DATA(rta)));
222         }
223     }
224     return 0;
225 }
226 
227 }  // namespace net
228 }  // namespace android
229