]> git.proxmox.com Git - mirror_frr.git/blame - zebra/kernel_netlink.c
zebra: Add code for fuzzing netlink
[mirror_frr.git] / zebra / kernel_netlink.c
CommitLineData
718e3744 1/* Kernel communication using netlink interface.
2 * Copyright (C) 1999 Kunihiro Ishiguro
3 *
4 * This file is part of GNU Zebra.
5 *
6 * GNU Zebra is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License as published by the
8 * Free Software Foundation; either version 2, or (at your option) any
9 * later version.
10 *
11 * GNU Zebra is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * General Public License for more details.
15 *
896014f4
DL
16 * You should have received a copy of the GNU General Public License along
17 * with this program; see the file COPYING; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
718e3744 19 */
1fdc9eae 20
21#include <zebra.h>
22
81a2f870
SW
23#if defined(HANDLE_ZAPI_FUZZING)
24#include <stdio.h>
25#include <string.h>
26#endif
27
ddfeb486
DL
28#ifdef HAVE_NETLINK
29
1fdc9eae 30#include "linklist.h"
31#include "if.h"
32#include "log.h"
33#include "prefix.h"
34#include "connected.h"
35#include "table.h"
36#include "memory.h"
37#include "zebra_memory.h"
38#include "rib.h"
39#include "thread.h"
40#include "privs.h"
41#include "nexthop.h"
42#include "vrf.h"
43#include "mpls.h"
44
45#include "zebra/zserv.h"
46#include "zebra/zebra_ns.h"
47#include "zebra/zebra_vrf.h"
05f7f5db 48#include "zebra/rt.h"
1fdc9eae 49#include "zebra/debug.h"
50#include "zebra/kernel_netlink.h"
51#include "zebra/rt_netlink.h"
52#include "zebra/if_netlink.h"
942bf97b 53#include "zebra/rule_netlink.h"
1fdc9eae 54
55#ifndef SO_RCVBUFFORCE
56#define SO_RCVBUFFORCE (33)
57#endif
58
59/* Hack for GNU libc version 2. */
60#ifndef MSG_TRUNC
61#define MSG_TRUNC 0x20
62#endif /* MSG_TRUNC */
63
64#ifndef NLMSG_TAIL
d62a17ae 65#define NLMSG_TAIL(nmsg) \
d7c0a89a
QY
66 ((struct rtattr *)(((uint8_t *)(nmsg)) \
67 + NLMSG_ALIGN((nmsg)->nlmsg_len)))
1fdc9eae 68#endif
69
70#ifndef RTA_TAIL
d62a17ae 71#define RTA_TAIL(rta) \
d7c0a89a 72 ((struct rtattr *)(((uint8_t *)(rta)) + RTA_ALIGN((rta)->rta_len)))
1fdc9eae 73#endif
74
f909c673
DS
75#ifndef RTNL_FAMILY_IP6MR
76#define RTNL_FAMILY_IP6MR 129
77#endif
78
79#ifndef RTPROT_MROUTED
80#define RTPROT_MROUTED 17
81#endif
82
d62a17ae 83static const struct message nlmsg_str[] = {{RTM_NEWROUTE, "RTM_NEWROUTE"},
84 {RTM_DELROUTE, "RTM_DELROUTE"},
85 {RTM_GETROUTE, "RTM_GETROUTE"},
86 {RTM_NEWLINK, "RTM_NEWLINK"},
87 {RTM_DELLINK, "RTM_DELLINK"},
88 {RTM_GETLINK, "RTM_GETLINK"},
89 {RTM_NEWADDR, "RTM_NEWADDR"},
90 {RTM_DELADDR, "RTM_DELADDR"},
91 {RTM_GETADDR, "RTM_GETADDR"},
92 {RTM_NEWNEIGH, "RTM_NEWNEIGH"},
93 {RTM_DELNEIGH, "RTM_DELNEIGH"},
94 {RTM_GETNEIGH, "RTM_GETNEIGH"},
942bf97b 95 {RTM_NEWRULE, "RTM_NEWRULE"},
96 {RTM_DELRULE, "RTM_DELRULE"},
97 {RTM_GETRULE, "RTM_GETRULE"},
d62a17ae 98 {0}};
1fdc9eae 99
100static const struct message rtproto_str[] = {
d62a17ae 101 {RTPROT_REDIRECT, "redirect"},
102 {RTPROT_KERNEL, "kernel"},
103 {RTPROT_BOOT, "boot"},
104 {RTPROT_STATIC, "static"},
105 {RTPROT_GATED, "GateD"},
106 {RTPROT_RA, "router advertisement"},
107 {RTPROT_MRT, "MRT"},
108 {RTPROT_ZEBRA, "Zebra"},
1fdc9eae 109#ifdef RTPROT_BIRD
d62a17ae 110 {RTPROT_BIRD, "BIRD"},
1fdc9eae 111#endif /* RTPROT_BIRD */
d62a17ae 112 {RTPROT_MROUTED, "mroute"},
113 {RTPROT_BGP, "BGP"},
114 {RTPROT_OSPF, "OSPF"},
115 {RTPROT_ISIS, "IS-IS"},
116 {RTPROT_RIP, "RIP"},
117 {RTPROT_RIPNG, "RIPNG"},
d4d71f11 118 {RTPROT_ZSTATIC, "static"},
d62a17ae 119 {0}};
120
121static const struct message family_str[] = {{AF_INET, "ipv4"},
122 {AF_INET6, "ipv6"},
123 {AF_BRIDGE, "bridge"},
124 {RTNL_FAMILY_IPMR, "ipv4MR"},
125 {RTNL_FAMILY_IP6MR, "ipv6MR"},
126 {0}};
127
128static const struct message rttype_str[] = {{RTN_UNICAST, "unicast"},
129 {RTN_MULTICAST, "multicast"},
130 {0}};
b339bde7 131
1fdc9eae 132extern struct thread_master *master;
d7c0a89a 133extern uint32_t nl_rcvbufsize;
1fdc9eae 134
135extern struct zebra_privs_t zserv_privs;
136
2414abd3 137int netlink_talk_filter(struct nlmsghdr *h, ns_id_t ns_id, int startup)
1fdc9eae 138{
3575d9e8
DS
139 /*
140 * This is an error condition that must be handled during
141 * development.
142 *
143 * The netlink_talk_filter function is used for communication
144 * down the netlink_cmd pipe and we are expecting
145 * an ack being received. So if we get here
146 * then we did not receive the ack and instead
147 * received some other message in an unexpected
148 * way.
149 */
150 zlog_err("%s: ignoring message type 0x%04x(%s) NS %u",
151 __PRETTY_FUNCTION__, h->nlmsg_type,
152 nl_msg_type_to_str(h->nlmsg_type), ns_id);
d62a17ae 153 return 0;
1fdc9eae 154}
155
d62a17ae 156static int netlink_recvbuf(struct nlsock *nl, uint32_t newsize)
1fdc9eae 157{
d7c0a89a 158 uint32_t oldsize;
d62a17ae 159 socklen_t newlen = sizeof(newsize);
160 socklen_t oldlen = sizeof(oldsize);
161 int ret;
162
163 ret = getsockopt(nl->sock, SOL_SOCKET, SO_RCVBUF, &oldsize, &oldlen);
164 if (ret < 0) {
165 zlog_err("Can't get %s receive buffer size: %s", nl->name,
166 safe_strerror(errno));
167 return -1;
168 }
169
170 /* Try force option (linux >= 2.6.14) and fall back to normal set */
171 if (zserv_privs.change(ZPRIVS_RAISE))
172 zlog_err("routing_socket: Can't raise privileges");
173 ret = setsockopt(nl->sock, SOL_SOCKET, SO_RCVBUFFORCE, &nl_rcvbufsize,
174 sizeof(nl_rcvbufsize));
175 if (zserv_privs.change(ZPRIVS_LOWER))
176 zlog_err("routing_socket: Can't lower privileges");
177 if (ret < 0)
178 ret = setsockopt(nl->sock, SOL_SOCKET, SO_RCVBUF,
179 &nl_rcvbufsize, sizeof(nl_rcvbufsize));
180 if (ret < 0) {
181 zlog_err("Can't set %s receive buffer size: %s", nl->name,
182 safe_strerror(errno));
183 return -1;
184 }
185
186 ret = getsockopt(nl->sock, SOL_SOCKET, SO_RCVBUF, &newsize, &newlen);
187 if (ret < 0) {
188 zlog_err("Can't get %s receive buffer size: %s", nl->name,
189 safe_strerror(errno));
190 return -1;
191 }
192
193 zlog_info("Setting netlink socket receive buffer size: %u -> %u",
194 oldsize, newsize);
195 return 0;
1fdc9eae 196}
197
198/* Make socket for Linux netlink interface. */
d62a17ae 199static int netlink_socket(struct nlsock *nl, unsigned long groups,
200 ns_id_t ns_id)
1fdc9eae 201{
d62a17ae 202 int ret;
203 struct sockaddr_nl snl;
204 int sock;
205 int namelen;
206 int save_errno;
207
208 if (zserv_privs.change(ZPRIVS_RAISE)) {
209 zlog_err("Can't raise privileges");
210 return -1;
211 }
212
fe533c56 213 sock = ns_socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE, ns_id);
d62a17ae 214 if (sock < 0) {
215 zlog_err("Can't open %s socket: %s", nl->name,
216 safe_strerror(errno));
217 return -1;
218 }
219
220 memset(&snl, 0, sizeof snl);
221 snl.nl_family = AF_NETLINK;
222 snl.nl_groups = groups;
223
224 /* Bind the socket to the netlink structure for anything. */
225 ret = bind(sock, (struct sockaddr *)&snl, sizeof snl);
226 save_errno = errno;
227 if (zserv_privs.change(ZPRIVS_LOWER))
228 zlog_err("Can't lower privileges");
229
230 if (ret < 0) {
231 zlog_err("Can't bind %s socket to group 0x%x: %s", nl->name,
232 snl.nl_groups, safe_strerror(save_errno));
233 close(sock);
234 return -1;
235 }
236
237 /* multiple netlink sockets will have different nl_pid */
238 namelen = sizeof snl;
239 ret = getsockname(sock, (struct sockaddr *)&snl, (socklen_t *)&namelen);
240 if (ret < 0 || namelen != sizeof snl) {
241 zlog_err("Can't get %s socket name: %s", nl->name,
242 safe_strerror(errno));
243 close(sock);
244 return -1;
245 }
246
247 nl->snl = snl;
248 nl->sock = sock;
249 return ret;
1fdc9eae 250}
251
2414abd3 252static int netlink_information_fetch(struct nlmsghdr *h, ns_id_t ns_id,
d62a17ae 253 int startup)
1fdc9eae 254{
3575d9e8
DS
255 /*
256 * When we handle new message types here
257 * because we are starting to install them
258 * then lets check the netlink_install_filter
259 * and see if we should add the corresponding
260 * allow through entry there.
261 * Probably not needed to do but please
262 * think about it.
263 */
d62a17ae 264 switch (h->nlmsg_type) {
265 case RTM_NEWROUTE:
2414abd3 266 return netlink_route_change(h, ns_id, startup);
d62a17ae 267 case RTM_DELROUTE:
2414abd3 268 return netlink_route_change(h, ns_id, startup);
d62a17ae 269 case RTM_NEWLINK:
2414abd3 270 return netlink_link_change(h, ns_id, startup);
d62a17ae 271 case RTM_DELLINK:
2414abd3 272 return netlink_link_change(h, ns_id, startup);
d62a17ae 273 case RTM_NEWADDR:
2414abd3 274 return netlink_interface_addr(h, ns_id, startup);
d62a17ae 275 case RTM_DELADDR:
2414abd3 276 return netlink_interface_addr(h, ns_id, startup);
d62a17ae 277 case RTM_NEWNEIGH:
2414abd3 278 return netlink_neigh_change(h, ns_id);
d62a17ae 279 case RTM_DELNEIGH:
2414abd3 280 return netlink_neigh_change(h, ns_id);
942bf97b 281 case RTM_NEWRULE:
2414abd3 282 return netlink_rule_change(h, ns_id, startup);
942bf97b 283 case RTM_DELRULE:
2414abd3 284 return netlink_rule_change(h, ns_id, startup);
d62a17ae 285 default:
3575d9e8
DS
286 /*
287 * If we have received this message then
288 * we have made a mistake during development
289 * and we need to write some code to handle
290 * this message type or not ask for
291 * it to be sent up to us
292 */
293 zlog_err("Unknown netlink nlmsg_type %s(%d) vrf %u\n",
294 nl_msg_type_to_str(h->nlmsg_type), h->nlmsg_type,
295 ns_id);
d62a17ae 296 break;
297 }
298 return 0;
1fdc9eae 299}
300
81a2f870
SW
301#if defined(HANDLE_ZAPI_FUZZING)
302/* Using globals here to avoid adding function parameters */
303
304/* Keep distinct filenames for netlink fuzzy collection */
305static unsigned int netlink_file_counter = 1;
306
307/* File name to read fuzzed netlink from */
308static char netlink_fuzz_file[MAXPATHLEN] = "";
309
310/* Flag for whether to read from file or not */
311static int netlink_read = 0;
312
313/**
314 * netlink_set_read() - Sets the read flag
315 * @flag: Flag value.
316 *
317 */
318void set_netlink_read(int flag)
319{
320 netlink_read = flag;
321}
322
323/**
324 * netlink_read_init() - Starts the message parser
325 * @fname: Filename to read.
326 */
327void netlink_read_init(const char *fname)
328{
329 snprintf(netlink_fuzz_file, MAXPATHLEN, "%s", fname);
330 /* Creating this fake socket for testing purposes */
331 struct zebra_ns zns = {
332 .ns_id = 0,
333 .netlink_cmd = {.sock = -1,
334 .seq = -1,
335 .name = "fuzzer_command_channel"},
336 .netlink = {.sock = -1,
337 .seq = -1,
338 .name = "fuzzer_kernel_message"}
339 };
340 netlink_parse_info(netlink_information_fetch, &zns.netlink, &zns, 1, 0);
341}
342
343/**
344 * netlink_write_incoming() - Writes all data received from netlink to a file
345 * @buf: Data from netlink.
346 * @size: Size of data.
347 * @counter: Counter for keeping filenames distinct.
348 */
349static void netlink_write_incoming(const char *buf, const unsigned int size,
350 unsigned int counter)
351{
352 char fname[MAXPATHLEN];
353 FILE *f;
354
355 zserv_privs.change(ZPRIVS_RAISE);
356 snprintf(fname, MAXPATHLEN, "%s/%s_%u", DAEMON_VTY_DIR, "netlink",
357 counter);
358 f = fopen(fname, "w");
359 if (f) {
360 fwrite(buf, 1, size, f);
361 fclose(f);
362 }
363 zserv_privs.change(ZPRIVS_LOWER);
364}
365
366/**
367 * netlink_read_file() - Reads netlink data from file
368 * @buf: Netlink buffer being overwritten.
369 * @fname: File name to read from.
370 *
371 * Return: Size of file.
372 */
373static long netlink_read_file(char *buf, const char *fname)
374{
375 FILE *f;
376 long file_bytes = -1;
377 zserv_privs.change(ZPRIVS_RAISE);
378 f = fopen(fname, "r");
379 if (f) {
380 fseek(f, 0, SEEK_END);
381 file_bytes = ftell(f);
382 rewind(f);
383 fread(buf, file_bytes, 1, f);
384 fclose(f);
385 }
386 zserv_privs.change(ZPRIVS_LOWER);
387 return file_bytes;
388}
389
390#endif
391
d62a17ae 392static int kernel_read(struct thread *thread)
1fdc9eae 393{
d62a17ae 394 struct zebra_ns *zns = (struct zebra_ns *)THREAD_ARG(thread);
395 netlink_parse_info(netlink_information_fetch, &zns->netlink, zns, 5, 0);
396 zns->t_netlink = NULL;
397 thread_add_read(zebrad.master, kernel_read, zns, zns->netlink.sock,
398 &zns->t_netlink);
1fdc9eae 399
d62a17ae 400 return 0;
1fdc9eae 401}
402
3575d9e8
DS
403/*
404 * Filter out messages from self that occur on listener socket,
1fdc9eae 405 * caused by our actions on the command socket
3575d9e8
DS
406 *
407 * When we add new Netlink message types we probably
408 * do not need to add them here as that we are filtering
409 * on the routes we actually care to receive( which is rarer
410 * then the normal course of operations). We are intentionally
411 * allowing some messages from ourselves through
412 * ( I'm looking at you Interface based netlink messages )
413 * so that we only had to write one way to handle incoming
414 * address add/delete changes.
1fdc9eae 415 */
d62a17ae 416static void netlink_install_filter(int sock, __u32 pid)
1fdc9eae 417{
3575d9e8
DS
418 /*
419 * BPF_JUMP instructions and where you jump to are based upon
420 * 0 as being the next statement. So count from 0. Writing
421 * this down because every time I look at this I have to
422 * re-remember it.
423 */
d62a17ae 424 struct sock_filter filter[] = {
3575d9e8
DS
425 /*
426 * Logic:
427 * if (nlmsg_pid == pid) {
428 * if (the incoming nlmsg_type ==
429 * RTM_NEWADDR | RTM_DELADDR)
430 * keep this message
431 * else
432 * skip this message
433 * } else
434 * keep this netlink message
435 */
436 /*
437 * 0: Load the nlmsg_pid into the BPF register
438 */
d62a17ae 439 BPF_STMT(BPF_LD | BPF_ABS | BPF_W,
440 offsetof(struct nlmsghdr, nlmsg_pid)),
3575d9e8
DS
441 /*
442 * 1: Compare to pid
443 */
444 BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, htonl(pid), 0, 4),
445 /*
446 * 2: Load the nlmsg_type into BPF register
447 */
448 BPF_STMT(BPF_LD | BPF_ABS | BPF_H,
449 offsetof(struct nlmsghdr, nlmsg_type)),
450 /*
451 * 3: Compare to RTM_NEWADDR
452 */
453 BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, htons(RTM_NEWADDR), 2, 0),
454 /*
455 * 4: Compare to RTM_DELADDR
456 */
457 BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, htons(RTM_DELADDR), 1, 0),
458 /*
459 * 5: This is the end state of we want to skip the
460 * message
461 */
d62a17ae 462 BPF_STMT(BPF_RET | BPF_K, 0),
3575d9e8
DS
463 /* 6: This is the end state of we want to keep
464 * the message
465 */
d62a17ae 466 BPF_STMT(BPF_RET | BPF_K, 0xffff),
467 };
468
469 struct sock_fprog prog = {
9d303b37 470 .len = array_size(filter), .filter = filter,
d62a17ae 471 };
472
473 if (setsockopt(sock, SOL_SOCKET, SO_ATTACH_FILTER, &prog, sizeof(prog))
474 < 0)
475 zlog_warn("Can't install socket filter: %s\n",
476 safe_strerror(errno));
1fdc9eae 477}
478
d62a17ae 479void netlink_parse_rtattr(struct rtattr **tb, int max, struct rtattr *rta,
480 int len)
1fdc9eae 481{
d62a17ae 482 while (RTA_OK(rta, len)) {
483 if (rta->rta_type <= max)
484 tb[rta->rta_type] = rta;
485 rta = RTA_NEXT(rta, len);
486 }
1fdc9eae 487}
488
86391e56
MS
489int addattr_l(struct nlmsghdr *n, unsigned int maxlen, int type,
490 const void *data, unsigned int alen)
1fdc9eae 491{
d62a17ae 492 int len;
493 struct rtattr *rta;
1fdc9eae 494
d62a17ae 495 len = RTA_LENGTH(alen);
1fdc9eae 496
d62a17ae 497 if (NLMSG_ALIGN(n->nlmsg_len) + RTA_ALIGN(len) > maxlen)
498 return -1;
1fdc9eae 499
d62a17ae 500 rta = (struct rtattr *)(((char *)n) + NLMSG_ALIGN(n->nlmsg_len));
501 rta->rta_type = type;
502 rta->rta_len = len;
4b2792b5 503
d62a17ae 504 if (data)
505 memcpy(RTA_DATA(rta), data, alen);
506 else
507 assert(alen == 0);
4b2792b5 508
d62a17ae 509 n->nlmsg_len = NLMSG_ALIGN(n->nlmsg_len) + RTA_ALIGN(len);
1fdc9eae 510
d62a17ae 511 return 0;
1fdc9eae 512}
513
86391e56
MS
514int rta_addattr_l(struct rtattr *rta, unsigned int maxlen, int type,
515 const void *data, unsigned int alen)
1fdc9eae 516{
d62a17ae 517 unsigned int len;
518 struct rtattr *subrta;
1fdc9eae 519
d62a17ae 520 len = RTA_LENGTH(alen);
1fdc9eae 521
d62a17ae 522 if (RTA_ALIGN(rta->rta_len) + RTA_ALIGN(len) > maxlen)
523 return -1;
1fdc9eae 524
d62a17ae 525 subrta = (struct rtattr *)(((char *)rta) + RTA_ALIGN(rta->rta_len));
526 subrta->rta_type = type;
527 subrta->rta_len = len;
4b2792b5 528
d62a17ae 529 if (data)
530 memcpy(RTA_DATA(subrta), data, alen);
531 else
532 assert(alen == 0);
4b2792b5 533
d62a17ae 534 rta->rta_len = NLMSG_ALIGN(rta->rta_len) + RTA_ALIGN(len);
1fdc9eae 535
d62a17ae 536 return 0;
1fdc9eae 537}
538
d7c0a89a 539int addattr16(struct nlmsghdr *n, unsigned int maxlen, int type, uint16_t data)
bbc16902 540{
d7c0a89a 541 return addattr_l(n, maxlen, type, &data, sizeof(uint16_t));
bbc16902 542}
543
d62a17ae 544int addattr32(struct nlmsghdr *n, unsigned int maxlen, int type, int data)
1fdc9eae 545{
d7c0a89a 546 return addattr_l(n, maxlen, type, &data, sizeof(uint32_t));
1fdc9eae 547}
548
d62a17ae 549struct rtattr *addattr_nest(struct nlmsghdr *n, int maxlen, int type)
1fdc9eae 550{
d62a17ae 551 struct rtattr *nest = NLMSG_TAIL(n);
1fdc9eae 552
d62a17ae 553 addattr_l(n, maxlen, type, NULL, 0);
554 return nest;
1fdc9eae 555}
556
d62a17ae 557int addattr_nest_end(struct nlmsghdr *n, struct rtattr *nest)
1fdc9eae 558{
d7c0a89a 559 nest->rta_len = (uint8_t *)NLMSG_TAIL(n) - (uint8_t *)nest;
d62a17ae 560 return n->nlmsg_len;
1fdc9eae 561}
562
d62a17ae 563struct rtattr *rta_nest(struct rtattr *rta, int maxlen, int type)
1fdc9eae 564{
d62a17ae 565 struct rtattr *nest = RTA_TAIL(rta);
1fdc9eae 566
d62a17ae 567 rta_addattr_l(rta, maxlen, type, NULL, 0);
568 return nest;
1fdc9eae 569}
570
d62a17ae 571int rta_nest_end(struct rtattr *rta, struct rtattr *nest)
1fdc9eae 572{
d7c0a89a 573 nest->rta_len = (uint8_t *)RTA_TAIL(rta) - (uint8_t *)nest;
d62a17ae 574 return rta->rta_len;
1fdc9eae 575}
576
d62a17ae 577const char *nl_msg_type_to_str(uint16_t msg_type)
1fdc9eae 578{
d62a17ae 579 return lookup_msg(nlmsg_str, msg_type, "");
1fdc9eae 580}
581
d7c0a89a 582const char *nl_rtproto_to_str(uint8_t rtproto)
1fdc9eae 583{
d62a17ae 584 return lookup_msg(rtproto_str, rtproto, "");
1fdc9eae 585}
b339bde7 586
d7c0a89a 587const char *nl_family_to_str(uint8_t family)
b339bde7 588{
d62a17ae 589 return lookup_msg(family_str, family, "");
b339bde7
DS
590}
591
d7c0a89a 592const char *nl_rttype_to_str(uint8_t rttype)
b339bde7 593{
d62a17ae 594 return lookup_msg(rttype_str, rttype, "");
b339bde7
DS
595}
596
5d307d5d
DS
597#define NL_OK(nla, len) \
598 ((len) >= (int)sizeof(struct nlattr) \
599 && (nla)->nla_len >= sizeof(struct nlattr) \
600 && (nla)->nla_len <= (len))
601#define NL_NEXT(nla, attrlen) \
602 ((attrlen) -= RTA_ALIGN((nla)->nla_len), \
603 (struct nlattr *)(((char *)(nla)) + RTA_ALIGN((nla)->nla_len)))
604#define NL_RTA(r) \
605 ((struct nlattr *)(((char *)(r)) \
606 + NLMSG_ALIGN(sizeof(struct nlmsgerr))))
607
608static void netlink_parse_nlattr(struct nlattr **tb, int max,
609 struct nlattr *nla, int len)
610{
611 while (NL_OK(nla, len)) {
612 if (nla->nla_type <= max)
613 tb[nla->nla_type] = nla;
614 nla = NL_NEXT(nla, len);
615 }
616}
617
618static void netlink_parse_extended_ack(struct nlmsghdr *h)
619{
620 struct nlattr *tb[NLMSGERR_ATTR_MAX + 1];
621 const struct nlmsgerr *err =
622 (const struct nlmsgerr *)((uint8_t *)h
623 + NLMSG_ALIGN(
624 sizeof(struct nlmsghdr)));
625 const struct nlmsghdr *err_nlh = NULL;
626 uint32_t hlen = sizeof(*err);
627 const char *msg = NULL;
628 uint32_t off = 0;
629
630 if (!(h->nlmsg_flags & NLM_F_CAPPED))
631 hlen += h->nlmsg_len - NLMSG_ALIGN(sizeof(struct nlmsghdr));
632
633 memset(tb, 0, sizeof(tb));
634 netlink_parse_nlattr(tb, NLMSGERR_ATTR_MAX, NL_RTA(h), hlen);
635
636 if (tb[NLMSGERR_ATTR_MSG])
637 msg = (const char *)RTA_DATA(tb[NLMSGERR_ATTR_MSG]);
638
639 if (tb[NLMSGERR_ATTR_OFFS]) {
640 off = *(uint32_t *)RTA_DATA(tb[NLMSGERR_ATTR_OFFS]);
641
642 if (off > h->nlmsg_len) {
643 zlog_err("Invalid offset for NLMSGERR_ATTR_OFFS\n");
5d307d5d
DS
644 } else if (!(h->nlmsg_flags & NLM_F_CAPPED)) {
645 /*
646 * Header of failed message
647 * we are not doing anything currently with it
648 * but noticing it for later.
649 */
650 err_nlh = &err->msg;
651 zlog_warn("%s: Received %d extended Ack",
652 __PRETTY_FUNCTION__, err_nlh->nlmsg_type);
653 }
654 }
655
656 if (msg && *msg != '\0') {
657 bool is_err = !!err->error;
658
659 if (is_err)
660 zlog_err("Extended Error: %s", msg);
661 else
662 zlog_warn("Extended Warning: %s", msg);
663 }
664}
665
936ebf0a
DS
666/*
667 * netlink_parse_info
668 *
669 * Receive message from netlink interface and pass those information
670 * to the given function.
671 *
672 * filter -> Function to call to read the results
673 * nl -> netlink socket information
674 * zns -> The zebra namespace data
675 * count -> How many we should read in, 0 means as much as possible
676 * startup -> Are we reading in under startup conditions? passed to
677 * the filter.
678 */
2414abd3 679int netlink_parse_info(int (*filter)(struct nlmsghdr *, ns_id_t, int),
d62a17ae 680 struct nlsock *nl, struct zebra_ns *zns, int count,
681 int startup)
1fdc9eae 682{
d62a17ae 683 int status;
684 int ret = 0;
685 int error;
686 int read_in = 0;
687
688 while (1) {
9ed7517b 689 char buf[NL_RCV_PKT_BUF_SIZE];
d62a17ae 690 struct iovec iov = {.iov_base = buf, .iov_len = sizeof buf};
691 struct sockaddr_nl snl;
692 struct msghdr msg = {.msg_name = (void *)&snl,
693 .msg_namelen = sizeof snl,
694 .msg_iov = &iov,
695 .msg_iovlen = 1};
696 struct nlmsghdr *h;
697
698 if (count && read_in >= count)
699 return 0;
700
81a2f870
SW
701#if defined(HANDLE_ZAPI_FUZZING)
702 /* Check if reading and filename is set */
703 if (netlink_read && '\0' != netlink_fuzz_file[0]) {
704 zlog_debug("Reading netlink fuzz file");
705 status = netlink_read_file(buf, netlink_fuzz_file);
706 snl.nl_pid = 0;
707 } else {
708 status = recvmsg(nl->sock, &msg, 0);
709 }
710#else
d62a17ae 711 status = recvmsg(nl->sock, &msg, 0);
81a2f870 712#endif
d62a17ae 713 if (status < 0) {
714 if (errno == EINTR)
715 continue;
716 if (errno == EWOULDBLOCK || errno == EAGAIN)
717 break;
718 zlog_err("%s recvmsg overrun: %s", nl->name,
719 safe_strerror(errno));
720 /*
721 * In this case we are screwed.
722 * There is no good way to
723 * recover zebra at this point.
724 */
725 exit(-1);
726 continue;
1fdc9eae 727 }
728
d62a17ae 729 if (status == 0) {
730 zlog_err("%s EOF", nl->name);
731 return -1;
732 }
733
734 if (msg.msg_namelen != sizeof snl) {
735 zlog_err("%s sender address length error: length %d",
736 nl->name, msg.msg_namelen);
737 return -1;
738 }
739
740 if (IS_ZEBRA_DEBUG_KERNEL_MSGDUMP_RECV) {
741 zlog_debug("%s: << netlink message dump [recv]",
742 __func__);
743 zlog_hexdump(buf, status);
744 }
745
81a2f870
SW
746#if defined(HANDLE_ZAPI_FUZZING)
747 if (!netlink_read) {
748 zlog_debug("Writing incoming netlink message");
749 netlink_write_incoming(buf, status,
750 netlink_file_counter++);
751 }
752#endif
753
d62a17ae 754 read_in++;
755 for (h = (struct nlmsghdr *)buf;
756 NLMSG_OK(h, (unsigned int)status);
757 h = NLMSG_NEXT(h, status)) {
758 /* Finish of reading. */
759 if (h->nlmsg_type == NLMSG_DONE)
760 return ret;
761
762 /* Error handling. */
763 if (h->nlmsg_type == NLMSG_ERROR) {
764 struct nlmsgerr *err =
765 (struct nlmsgerr *)NLMSG_DATA(h);
766 int errnum = err->error;
767 int msg_type = err->msg.nlmsg_type;
768
5d307d5d
DS
769 if (h->nlmsg_len
770 < NLMSG_LENGTH(sizeof(struct nlmsgerr))) {
771 zlog_err("%s error: message truncated",
772 nl->name);
773 return -1;
774 }
775
776 /*
777 * Parse the extended information before
778 * we actually handle it.
779 * At this point in time we do not
780 * do anything other than report the
781 * issue.
782 */
783 if (h->nlmsg_flags & NLM_F_ACK_TLVS)
784 netlink_parse_extended_ack(h);
785
d62a17ae 786 /* If the error field is zero, then this is an
787 * ACK */
788 if (err->error == 0) {
789 if (IS_ZEBRA_DEBUG_KERNEL) {
790 zlog_debug(
791 "%s: %s ACK: type=%s(%u), seq=%u, pid=%u",
792 __FUNCTION__, nl->name,
793 nl_msg_type_to_str(
794 err->msg.nlmsg_type),
795 err->msg.nlmsg_type,
796 err->msg.nlmsg_seq,
797 err->msg.nlmsg_pid);
798 }
799
800 /* return if not a multipart message,
801 * otherwise continue */
802 if (!(h->nlmsg_flags & NLM_F_MULTI))
803 return 0;
804 continue;
805 }
806
d62a17ae 807 /* Deal with errors that occur because of races
808 * in link handling */
809 if (nl == &zns->netlink_cmd
810 && ((msg_type == RTM_DELROUTE
811 && (-errnum == ENODEV
812 || -errnum == ESRCH))
813 || (msg_type == RTM_NEWROUTE
814 && (-errnum == ENETDOWN
815 || -errnum == EEXIST)))) {
816 if (IS_ZEBRA_DEBUG_KERNEL)
817 zlog_debug(
818 "%s: error: %s type=%s(%u), seq=%u, pid=%u",
819 nl->name,
820 safe_strerror(-errnum),
821 nl_msg_type_to_str(
822 msg_type),
823 msg_type,
824 err->msg.nlmsg_seq,
825 err->msg.nlmsg_pid);
826 return 0;
827 }
828
829 /* We see RTM_DELNEIGH when shutting down an
830 * interface with an IPv4
831 * link-local. The kernel should have already
832 * deleted the neighbor
833 * so do not log these as an error.
834 */
835 if (msg_type == RTM_DELNEIGH
836 || (nl == &zns->netlink_cmd
837 && msg_type == RTM_NEWROUTE
838 && (-errnum == ESRCH
839 || -errnum == ENETUNREACH))) {
840 /* This is known to happen in some
841 * situations, don't log
842 * as error.
843 */
844 if (IS_ZEBRA_DEBUG_KERNEL)
845 zlog_debug(
846 "%s error: %s, type=%s(%u), seq=%u, pid=%u",
847 nl->name,
848 safe_strerror(-errnum),
849 nl_msg_type_to_str(
850 msg_type),
851 msg_type,
852 err->msg.nlmsg_seq,
853 err->msg.nlmsg_pid);
854 } else
855 zlog_err(
856 "%s error: %s, type=%s(%u), seq=%u, pid=%u",
857 nl->name,
858 safe_strerror(-errnum),
859 nl_msg_type_to_str(msg_type),
860 msg_type, err->msg.nlmsg_seq,
861 err->msg.nlmsg_pid);
862
863 return -1;
864 }
865
866 /* OK we got netlink message. */
867 if (IS_ZEBRA_DEBUG_KERNEL)
868 zlog_debug(
869 "netlink_parse_info: %s type %s(%u), len=%d, seq=%u, pid=%u",
870 nl->name,
871 nl_msg_type_to_str(h->nlmsg_type),
872 h->nlmsg_type, h->nlmsg_len,
873 h->nlmsg_seq, h->nlmsg_pid);
874
783827ae
DS
875
876 /*
877 * Ignore messages that maybe sent from
878 * other actors besides the kernel
879 */
880 if (snl.nl_pid != 0) {
881 zlog_err("Ignoring message from pid %u",
882 snl.nl_pid);
d62a17ae 883 continue;
884 }
885
2414abd3 886 error = (*filter)(h, zns->ns_id, startup);
d62a17ae 887 if (error < 0) {
888 zlog_err("%s filter function error", nl->name);
6ca7b664 889 zlog_backtrace(LOG_ERR);
d62a17ae 890 ret = error;
891 }
892 }
893
894 /* After error care. */
895 if (msg.msg_flags & MSG_TRUNC) {
896 zlog_err("%s error: message truncated", nl->name);
897 continue;
898 }
899 if (status) {
900 zlog_err("%s error: data remnant size %d", nl->name,
901 status);
902 return -1;
903 }
904 }
905 return ret;
1fdc9eae 906}
907
936ebf0a
DS
908/*
909 * netlink_talk
910 *
911 * sendmsg() to netlink socket then recvmsg().
912 * Calls netlink_parse_info to parse returned data
913 *
914 * filter -> The filter to read final results from kernel
915 * nlmsghdr -> The data to send to the kernel
916 * nl -> The netlink socket information
917 * zns -> The zebra namespace information
918 * startup -> Are we reading in under startup conditions
919 * This is passed through eventually to filter.
920 */
2414abd3 921int netlink_talk(int (*filter)(struct nlmsghdr *, ns_id_t, int startup),
d62a17ae 922 struct nlmsghdr *n, struct nlsock *nl, struct zebra_ns *zns,
923 int startup)
1fdc9eae 924{
d62a17ae 925 int status;
926 struct sockaddr_nl snl;
cbaca6a1
DS
927 struct iovec iov;
928 struct msghdr msg;
d62a17ae 929 int save_errno;
930
931 memset(&snl, 0, sizeof snl);
cbaca6a1
DS
932 memset(&iov, 0, sizeof iov);
933 memset(&msg, 0, sizeof msg);
934
935 iov.iov_base = n;
936 iov.iov_len = n->nlmsg_len;
937 msg.msg_name = (void *)&snl;
938 msg.msg_namelen = sizeof snl;
939 msg.msg_iov = &iov;
940 msg.msg_iovlen = 1;
941
d62a17ae 942 snl.nl_family = AF_NETLINK;
943
944 n->nlmsg_seq = ++nl->seq;
945 n->nlmsg_pid = nl->snl.nl_pid;
946
d62a17ae 947 if (IS_ZEBRA_DEBUG_KERNEL)
948 zlog_debug(
949 "netlink_talk: %s type %s(%u), len=%d seq=%u flags 0x%x",
950 nl->name, nl_msg_type_to_str(n->nlmsg_type),
951 n->nlmsg_type, n->nlmsg_len, n->nlmsg_seq,
952 n->nlmsg_flags);
953
954 /* Send message to netlink interface. */
955 if (zserv_privs.change(ZPRIVS_RAISE))
956 zlog_err("Can't raise privileges");
957 status = sendmsg(nl->sock, &msg, 0);
958 save_errno = errno;
959 if (zserv_privs.change(ZPRIVS_LOWER))
960 zlog_err("Can't lower privileges");
961
962 if (IS_ZEBRA_DEBUG_KERNEL_MSGDUMP_SEND) {
963 zlog_debug("%s: >> netlink message dump [sent]", __func__);
964 zlog_hexdump(n, n->nlmsg_len);
965 }
966
967 if (status < 0) {
968 zlog_err("netlink_talk sendmsg() error: %s",
969 safe_strerror(save_errno));
970 return -1;
971 }
972
973
974 /*
975 * Get reply from netlink socket.
976 * The reply should either be an acknowlegement or an error.
977 */
978 return netlink_parse_info(filter, nl, zns, 0, startup);
1fdc9eae 979}
980
289602d7 981/* Issue request message to kernel via netlink socket. GET messages
982 * are issued through this interface.
983 */
d62a17ae 984int netlink_request(struct nlsock *nl, struct nlmsghdr *n)
1fdc9eae 985{
d62a17ae 986 int ret;
987 struct sockaddr_nl snl;
988 int save_errno;
989
990 /* Check netlink socket. */
991 if (nl->sock < 0) {
992 zlog_err("%s socket isn't active.", nl->name);
993 return -1;
994 }
995
996 /* Fill common fields for all requests. */
997 n->nlmsg_flags = NLM_F_ROOT | NLM_F_MATCH | NLM_F_REQUEST;
998 n->nlmsg_pid = nl->snl.nl_pid;
999 n->nlmsg_seq = ++nl->seq;
1000
1001 memset(&snl, 0, sizeof snl);
1002 snl.nl_family = AF_NETLINK;
1003
1004 /* Raise capabilities and send message, then lower capabilities. */
1005 if (zserv_privs.change(ZPRIVS_RAISE)) {
1006 zlog_err("Can't raise privileges");
1007 return -1;
1008 }
1009
1010 ret = sendto(nl->sock, (void *)n, n->nlmsg_len, 0,
1011 (struct sockaddr *)&snl, sizeof snl);
1012 save_errno = errno;
1013
1014 if (zserv_privs.change(ZPRIVS_LOWER))
1015 zlog_err("Can't lower privileges");
1016
1017 if (ret < 0) {
1018 zlog_err("%s sendto failed: %s", nl->name,
1019 safe_strerror(save_errno));
1020 return -1;
1021 }
1022
1023 return 0;
1fdc9eae 1024}
1025
1026/* Exported interface function. This function simply calls
1027 netlink_socket (). */
d62a17ae 1028void kernel_init(struct zebra_ns *zns)
1fdc9eae 1029{
d62a17ae 1030 unsigned long groups;
5d307d5d
DS
1031#if defined SOL_NETLINK
1032 int one, ret;
1033#endif
d62a17ae 1034
026a316f
DS
1035 /*
1036 * Initialize netlink sockets
1037 *
1038 * If RTMGRP_XXX exists use that, but at some point
1039 * I think the kernel developers realized that
1040 * keeping track of all the different values would
1041 * lead to confusion, so we need to convert the
1042 * RTNLGRP_XXX to a bit position for ourself
1043 */
1044 groups = RTMGRP_LINK |
1045 RTMGRP_IPV4_ROUTE |
1046 RTMGRP_IPV4_IFADDR |
1047 RTMGRP_IPV6_ROUTE |
1048 RTMGRP_IPV6_IFADDR |
1049 RTMGRP_IPV4_MROUTE |
1050 RTMGRP_NEIGH |
1051 (1 << (RTNLGRP_IPV4_RULE - 1)) |
1052 (1 << (RTNLGRP_IPV6_RULE - 1));
d62a17ae 1053
1054 snprintf(zns->netlink.name, sizeof(zns->netlink.name),
1055 "netlink-listen (NS %u)", zns->ns_id);
1056 zns->netlink.sock = -1;
19d5a4fe
DS
1057 if (netlink_socket(&zns->netlink, groups, zns->ns_id) < 0) {
1058 zlog_err("Failure to create %s socket",
1059 zns->netlink.name);
1060 exit(-1);
1061 }
d62a17ae 1062
1063 snprintf(zns->netlink_cmd.name, sizeof(zns->netlink_cmd.name),
1064 "netlink-cmd (NS %u)", zns->ns_id);
1065 zns->netlink_cmd.sock = -1;
19d5a4fe
DS
1066 if (netlink_socket(&zns->netlink_cmd, 0, zns->ns_id) < 0) {
1067 zlog_err("Failure to create %s socket",
1068 zns->netlink_cmd.name);
1069 exit(-1);
1070 }
d62a17ae 1071
5d307d5d
DS
1072 /*
1073 * SOL_NETLINK is not available on all platforms yet
1074 * apparently. It's in bits/socket.h which I am not
1075 * sure that we want to pull into our build system.
1076 */
1077#if defined SOL_NETLINK
1078 /*
1079 * Let's tell the kernel that we want to receive extended
1080 * ACKS over our command socket
1081 */
1082 one = 1;
1083 ret = setsockopt(zns->netlink_cmd.sock, SOL_NETLINK, NETLINK_EXT_ACK,
1084 &one, sizeof(one));
1085
1086 if (ret < 0)
1087 zlog_notice("Registration for extended ACK failed : %d %s",
1088 errno, safe_strerror(errno));
1089#endif
1090
d62a17ae 1091 /* Register kernel socket. */
19d5a4fe 1092 if (fcntl(zns->netlink.sock, F_SETFL, O_NONBLOCK) < 0)
8c85e8ea
DS
1093 zlog_err("Can't set %s socket error: %s(%d)",
1094 zns->netlink.name, safe_strerror(errno), errno);
1095
1096 if (fcntl(zns->netlink_cmd.sock, F_SETFL, O_NONBLOCK) < 0)
1097 zlog_err("Can't set %s socket error: %s(%d)",
1098 zns->netlink_cmd.name, safe_strerror(errno), errno);
19d5a4fe
DS
1099
1100 /* Set receive buffer size if it's set from command line */
1101 if (nl_rcvbufsize)
1102 netlink_recvbuf(&zns->netlink, nl_rcvbufsize);
1103
1104 netlink_install_filter(zns->netlink.sock,
1105 zns->netlink_cmd.snl.nl_pid);
1106 zns->t_netlink = NULL;
1107
1108 thread_add_read(zebrad.master, kernel_read, zns,
1109 zns->netlink.sock, &zns->t_netlink);
d62a17ae 1110
1111 rt_netlink_init();
1fdc9eae 1112}
1113
d62a17ae 1114void kernel_terminate(struct zebra_ns *zns)
1fdc9eae 1115{
d62a17ae 1116 THREAD_READ_OFF(zns->t_netlink);
1117
1118 if (zns->netlink.sock >= 0) {
1119 close(zns->netlink.sock);
1120 zns->netlink.sock = -1;
1121 }
1122
1123 if (zns->netlink_cmd.sock >= 0) {
1124 close(zns->netlink_cmd.sock);
1125 zns->netlink_cmd.sock = -1;
1126 }
1fdc9eae 1127}
ddfeb486
DL
1128
1129#endif /* HAVE_NETLINK */