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