]> git.proxmox.com Git - mirror_frr.git/blob - zebra/kernel_netlink.c
Merge pull request #2696 from sworleys/Netlink-Fuzz
[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 #endif /* HANDLE_NETLINK_FUZZING */
27
28 #ifdef HAVE_NETLINK
29
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"
48 #include "zebra/rt.h"
49 #include "zebra/debug.h"
50 #include "zebra/kernel_netlink.h"
51 #include "zebra/rt_netlink.h"
52 #include "zebra/if_netlink.h"
53 #include "zebra/rule_netlink.h"
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
65 #define NLMSG_TAIL(nmsg) \
66 ((struct rtattr *)(((uint8_t *)(nmsg)) \
67 + NLMSG_ALIGN((nmsg)->nlmsg_len)))
68 #endif
69
70 #ifndef RTA_TAIL
71 #define RTA_TAIL(rta) \
72 ((struct rtattr *)(((uint8_t *)(rta)) + RTA_ALIGN((rta)->rta_len)))
73 #endif
74
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
83 static 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"},
95 {RTM_NEWRULE, "RTM_NEWRULE"},
96 {RTM_DELRULE, "RTM_DELRULE"},
97 {RTM_GETRULE, "RTM_GETRULE"},
98 {0}};
99
100 static const struct message rtproto_str[] = {
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"},
109 #ifdef RTPROT_BIRD
110 {RTPROT_BIRD, "BIRD"},
111 #endif /* RTPROT_BIRD */
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"},
118 {RTPROT_ZSTATIC, "static"},
119 {0}};
120
121 static 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
128 static const struct message rttype_str[] = {{RTN_UNICAST, "unicast"},
129 {RTN_MULTICAST, "multicast"},
130 {0}};
131
132 extern struct thread_master *master;
133 extern uint32_t nl_rcvbufsize;
134
135 extern struct zebra_privs_t zserv_privs;
136
137 int netlink_talk_filter(struct nlmsghdr *h, ns_id_t ns_id, int startup)
138 {
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);
153 return 0;
154 }
155
156 static int netlink_recvbuf(struct nlsock *nl, uint32_t newsize)
157 {
158 uint32_t oldsize;
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;
196 }
197
198 /* Make socket for Linux netlink interface. */
199 static int netlink_socket(struct nlsock *nl, unsigned long groups,
200 ns_id_t ns_id)
201 {
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
213 sock = ns_socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE, ns_id);
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;
250 }
251
252 static int netlink_information_fetch(struct nlmsghdr *h, ns_id_t ns_id,
253 int startup)
254 {
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 */
264 switch (h->nlmsg_type) {
265 case RTM_NEWROUTE:
266 return netlink_route_change(h, ns_id, startup);
267 case RTM_DELROUTE:
268 return netlink_route_change(h, ns_id, startup);
269 case RTM_NEWLINK:
270 return netlink_link_change(h, ns_id, startup);
271 case RTM_DELLINK:
272 return netlink_link_change(h, ns_id, startup);
273 case RTM_NEWADDR:
274 return netlink_interface_addr(h, ns_id, startup);
275 case RTM_DELADDR:
276 return netlink_interface_addr(h, ns_id, startup);
277 case RTM_NEWNEIGH:
278 return netlink_neigh_change(h, ns_id);
279 case RTM_DELNEIGH:
280 return netlink_neigh_change(h, ns_id);
281 case RTM_NEWRULE:
282 return netlink_rule_change(h, ns_id, startup);
283 case RTM_DELRULE:
284 return netlink_rule_change(h, ns_id, startup);
285 default:
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);
296 break;
297 }
298 return 0;
299 }
300
301 #if defined(HANDLE_NETLINK_FUZZING)
302 /* Using globals here to avoid adding function parameters */
303
304 /* Keep distinct filenames for netlink fuzzy collection */
305 static unsigned int netlink_file_counter = 1;
306
307 /* File name to read fuzzed netlink from */
308 static char netlink_fuzz_file[MAXPATHLEN] = "";
309
310 /* Flag for whether to read from file or not */
311 bool netlink_read;
312
313 /**
314 * netlink_read_init() - Starts the message parser
315 * @fname: Filename to read.
316 */
317 void netlink_read_init(const char *fname)
318 {
319 snprintf(netlink_fuzz_file, MAXPATHLEN, "%s", fname);
320 /* Creating this fake socket for testing purposes */
321 struct zebra_ns *zns = zebra_ns_lookup(NS_DEFAULT);
322
323 netlink_parse_info(netlink_information_fetch, &zns->netlink, zns, 1, 0);
324 }
325
326 /**
327 * netlink_write_incoming() - Writes all data received from netlink to a file
328 * @buf: Data from netlink.
329 * @size: Size of data.
330 * @counter: Counter for keeping filenames distinct.
331 */
332 static void netlink_write_incoming(const char *buf, const unsigned int size,
333 unsigned int counter)
334 {
335 char fname[MAXPATHLEN];
336 FILE *f;
337
338 zserv_privs.change(ZPRIVS_RAISE);
339 snprintf(fname, MAXPATHLEN, "%s/%s_%u", DAEMON_VTY_DIR, "netlink",
340 counter);
341 f = fopen(fname, "w");
342 if (f) {
343 fwrite(buf, 1, size, f);
344 fclose(f);
345 }
346 zserv_privs.change(ZPRIVS_LOWER);
347 }
348
349 /**
350 * netlink_read_file() - Reads netlink data from file
351 * @buf: Netlink buffer being overwritten.
352 * @fname: File name to read from.
353 *
354 * Return: Size of file.
355 */
356 static long netlink_read_file(char *buf, const char *fname)
357 {
358 FILE *f;
359 long file_bytes = -1;
360
361 zserv_privs.change(ZPRIVS_RAISE);
362 f = fopen(fname, "r");
363 if (f) {
364 fseek(f, 0, SEEK_END);
365 file_bytes = ftell(f);
366 rewind(f);
367 fread(buf, NL_RCV_PKT_BUF_SIZE, 1, f);
368 fclose(f);
369 }
370 zserv_privs.change(ZPRIVS_LOWER);
371 return file_bytes;
372 }
373
374 #endif /* HANDLE_NETLINK_FUZZING */
375
376 static int kernel_read(struct thread *thread)
377 {
378 struct zebra_ns *zns = (struct zebra_ns *)THREAD_ARG(thread);
379 netlink_parse_info(netlink_information_fetch, &zns->netlink, zns, 5, 0);
380 zns->t_netlink = NULL;
381 thread_add_read(zebrad.master, kernel_read, zns, zns->netlink.sock,
382 &zns->t_netlink);
383
384 return 0;
385 }
386
387 /*
388 * Filter out messages from self that occur on listener socket,
389 * caused by our actions on the command socket
390 *
391 * When we add new Netlink message types we probably
392 * do not need to add them here as that we are filtering
393 * on the routes we actually care to receive( which is rarer
394 * then the normal course of operations). We are intentionally
395 * allowing some messages from ourselves through
396 * ( I'm looking at you Interface based netlink messages )
397 * so that we only had to write one way to handle incoming
398 * address add/delete changes.
399 */
400 static void netlink_install_filter(int sock, __u32 pid)
401 {
402 /*
403 * BPF_JUMP instructions and where you jump to are based upon
404 * 0 as being the next statement. So count from 0. Writing
405 * this down because every time I look at this I have to
406 * re-remember it.
407 */
408 struct sock_filter filter[] = {
409 /*
410 * Logic:
411 * if (nlmsg_pid == pid) {
412 * if (the incoming nlmsg_type ==
413 * RTM_NEWADDR | RTM_DELADDR)
414 * keep this message
415 * else
416 * skip this message
417 * } else
418 * keep this netlink message
419 */
420 /*
421 * 0: Load the nlmsg_pid into the BPF register
422 */
423 BPF_STMT(BPF_LD | BPF_ABS | BPF_W,
424 offsetof(struct nlmsghdr, nlmsg_pid)),
425 /*
426 * 1: Compare to pid
427 */
428 BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, htonl(pid), 0, 4),
429 /*
430 * 2: Load the nlmsg_type into BPF register
431 */
432 BPF_STMT(BPF_LD | BPF_ABS | BPF_H,
433 offsetof(struct nlmsghdr, nlmsg_type)),
434 /*
435 * 3: Compare to RTM_NEWADDR
436 */
437 BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, htons(RTM_NEWADDR), 2, 0),
438 /*
439 * 4: Compare to RTM_DELADDR
440 */
441 BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, htons(RTM_DELADDR), 1, 0),
442 /*
443 * 5: This is the end state of we want to skip the
444 * message
445 */
446 BPF_STMT(BPF_RET | BPF_K, 0),
447 /* 6: This is the end state of we want to keep
448 * the message
449 */
450 BPF_STMT(BPF_RET | BPF_K, 0xffff),
451 };
452
453 struct sock_fprog prog = {
454 .len = array_size(filter), .filter = filter,
455 };
456
457 if (setsockopt(sock, SOL_SOCKET, SO_ATTACH_FILTER, &prog, sizeof(prog))
458 < 0)
459 zlog_warn("Can't install socket filter: %s\n",
460 safe_strerror(errno));
461 }
462
463 void netlink_parse_rtattr(struct rtattr **tb, int max, struct rtattr *rta,
464 int len)
465 {
466 while (RTA_OK(rta, len)) {
467 if (rta->rta_type <= max)
468 tb[rta->rta_type] = rta;
469 rta = RTA_NEXT(rta, len);
470 }
471 }
472
473 int addattr_l(struct nlmsghdr *n, unsigned int maxlen, int type,
474 const void *data, unsigned int alen)
475 {
476 int len;
477 struct rtattr *rta;
478
479 len = RTA_LENGTH(alen);
480
481 if (NLMSG_ALIGN(n->nlmsg_len) + RTA_ALIGN(len) > maxlen)
482 return -1;
483
484 rta = (struct rtattr *)(((char *)n) + NLMSG_ALIGN(n->nlmsg_len));
485 rta->rta_type = type;
486 rta->rta_len = len;
487
488 if (data)
489 memcpy(RTA_DATA(rta), data, alen);
490 else
491 assert(alen == 0);
492
493 n->nlmsg_len = NLMSG_ALIGN(n->nlmsg_len) + RTA_ALIGN(len);
494
495 return 0;
496 }
497
498 int rta_addattr_l(struct rtattr *rta, unsigned int maxlen, int type,
499 const void *data, unsigned int alen)
500 {
501 unsigned int len;
502 struct rtattr *subrta;
503
504 len = RTA_LENGTH(alen);
505
506 if (RTA_ALIGN(rta->rta_len) + RTA_ALIGN(len) > maxlen)
507 return -1;
508
509 subrta = (struct rtattr *)(((char *)rta) + RTA_ALIGN(rta->rta_len));
510 subrta->rta_type = type;
511 subrta->rta_len = len;
512
513 if (data)
514 memcpy(RTA_DATA(subrta), data, alen);
515 else
516 assert(alen == 0);
517
518 rta->rta_len = NLMSG_ALIGN(rta->rta_len) + RTA_ALIGN(len);
519
520 return 0;
521 }
522
523 int addattr16(struct nlmsghdr *n, unsigned int maxlen, int type, uint16_t data)
524 {
525 return addattr_l(n, maxlen, type, &data, sizeof(uint16_t));
526 }
527
528 int addattr32(struct nlmsghdr *n, unsigned int maxlen, int type, int data)
529 {
530 return addattr_l(n, maxlen, type, &data, sizeof(uint32_t));
531 }
532
533 struct rtattr *addattr_nest(struct nlmsghdr *n, int maxlen, int type)
534 {
535 struct rtattr *nest = NLMSG_TAIL(n);
536
537 addattr_l(n, maxlen, type, NULL, 0);
538 return nest;
539 }
540
541 int addattr_nest_end(struct nlmsghdr *n, struct rtattr *nest)
542 {
543 nest->rta_len = (uint8_t *)NLMSG_TAIL(n) - (uint8_t *)nest;
544 return n->nlmsg_len;
545 }
546
547 struct rtattr *rta_nest(struct rtattr *rta, int maxlen, int type)
548 {
549 struct rtattr *nest = RTA_TAIL(rta);
550
551 rta_addattr_l(rta, maxlen, type, NULL, 0);
552 return nest;
553 }
554
555 int rta_nest_end(struct rtattr *rta, struct rtattr *nest)
556 {
557 nest->rta_len = (uint8_t *)RTA_TAIL(rta) - (uint8_t *)nest;
558 return rta->rta_len;
559 }
560
561 const char *nl_msg_type_to_str(uint16_t msg_type)
562 {
563 return lookup_msg(nlmsg_str, msg_type, "");
564 }
565
566 const char *nl_rtproto_to_str(uint8_t rtproto)
567 {
568 return lookup_msg(rtproto_str, rtproto, "");
569 }
570
571 const char *nl_family_to_str(uint8_t family)
572 {
573 return lookup_msg(family_str, family, "");
574 }
575
576 const char *nl_rttype_to_str(uint8_t rttype)
577 {
578 return lookup_msg(rttype_str, rttype, "");
579 }
580
581 #define NL_OK(nla, len) \
582 ((len) >= (int)sizeof(struct nlattr) \
583 && (nla)->nla_len >= sizeof(struct nlattr) \
584 && (nla)->nla_len <= (len))
585 #define NL_NEXT(nla, attrlen) \
586 ((attrlen) -= RTA_ALIGN((nla)->nla_len), \
587 (struct nlattr *)(((char *)(nla)) + RTA_ALIGN((nla)->nla_len)))
588 #define NL_RTA(r) \
589 ((struct nlattr *)(((char *)(r)) \
590 + NLMSG_ALIGN(sizeof(struct nlmsgerr))))
591
592 static void netlink_parse_nlattr(struct nlattr **tb, int max,
593 struct nlattr *nla, int len)
594 {
595 while (NL_OK(nla, len)) {
596 if (nla->nla_type <= max)
597 tb[nla->nla_type] = nla;
598 nla = NL_NEXT(nla, len);
599 }
600 }
601
602 static void netlink_parse_extended_ack(struct nlmsghdr *h)
603 {
604 struct nlattr *tb[NLMSGERR_ATTR_MAX + 1];
605 const struct nlmsgerr *err =
606 (const struct nlmsgerr *)((uint8_t *)h
607 + NLMSG_ALIGN(
608 sizeof(struct nlmsghdr)));
609 const struct nlmsghdr *err_nlh = NULL;
610 uint32_t hlen = sizeof(*err);
611 const char *msg = NULL;
612 uint32_t off = 0;
613
614 if (!(h->nlmsg_flags & NLM_F_CAPPED))
615 hlen += h->nlmsg_len - NLMSG_ALIGN(sizeof(struct nlmsghdr));
616
617 memset(tb, 0, sizeof(tb));
618 netlink_parse_nlattr(tb, NLMSGERR_ATTR_MAX, NL_RTA(h), hlen);
619
620 if (tb[NLMSGERR_ATTR_MSG])
621 msg = (const char *)RTA_DATA(tb[NLMSGERR_ATTR_MSG]);
622
623 if (tb[NLMSGERR_ATTR_OFFS]) {
624 off = *(uint32_t *)RTA_DATA(tb[NLMSGERR_ATTR_OFFS]);
625
626 if (off > h->nlmsg_len) {
627 zlog_err("Invalid offset for NLMSGERR_ATTR_OFFS\n");
628 } else if (!(h->nlmsg_flags & NLM_F_CAPPED)) {
629 /*
630 * Header of failed message
631 * we are not doing anything currently with it
632 * but noticing it for later.
633 */
634 err_nlh = &err->msg;
635 zlog_warn("%s: Received %d extended Ack",
636 __PRETTY_FUNCTION__, err_nlh->nlmsg_type);
637 }
638 }
639
640 if (msg && *msg != '\0') {
641 bool is_err = !!err->error;
642
643 if (is_err)
644 zlog_err("Extended Error: %s", msg);
645 else
646 zlog_warn("Extended Warning: %s", msg);
647 }
648 }
649
650 /*
651 * netlink_parse_info
652 *
653 * Receive message from netlink interface and pass those information
654 * to the given function.
655 *
656 * filter -> Function to call to read the results
657 * nl -> netlink socket information
658 * zns -> The zebra namespace data
659 * count -> How many we should read in, 0 means as much as possible
660 * startup -> Are we reading in under startup conditions? passed to
661 * the filter.
662 */
663 int netlink_parse_info(int (*filter)(struct nlmsghdr *, ns_id_t, int),
664 struct nlsock *nl, struct zebra_ns *zns, int count,
665 int startup)
666 {
667 int status;
668 int ret = 0;
669 int error;
670 int read_in = 0;
671
672 while (1) {
673 char buf[NL_RCV_PKT_BUF_SIZE];
674 struct iovec iov = {.iov_base = buf, .iov_len = sizeof buf};
675 struct sockaddr_nl snl;
676 struct msghdr msg = {.msg_name = (void *)&snl,
677 .msg_namelen = sizeof snl,
678 .msg_iov = &iov,
679 .msg_iovlen = 1};
680 struct nlmsghdr *h;
681
682 if (count && read_in >= count)
683 return 0;
684
685 #if defined(HANDLE_NETLINK_FUZZING)
686 /* Check if reading and filename is set */
687 if (netlink_read && '\0' != netlink_fuzz_file[0]) {
688 zlog_debug("Reading netlink fuzz file");
689 status = netlink_read_file(buf, netlink_fuzz_file);
690 snl.nl_pid = 0;
691 } else {
692 status = recvmsg(nl->sock, &msg, 0);
693 }
694 #else
695 status = recvmsg(nl->sock, &msg, 0);
696 #endif /* HANDLE_NETLINK_FUZZING */
697 if (status < 0) {
698 if (errno == EINTR)
699 continue;
700 if (errno == EWOULDBLOCK || errno == EAGAIN)
701 break;
702 zlog_err("%s recvmsg overrun: %s", nl->name,
703 safe_strerror(errno));
704 /*
705 * In this case we are screwed.
706 * There is no good way to
707 * recover zebra at this point.
708 */
709 exit(-1);
710 continue;
711 }
712
713 if (status == 0) {
714 zlog_err("%s EOF", nl->name);
715 return -1;
716 }
717
718 if (msg.msg_namelen != sizeof snl) {
719 zlog_err("%s sender address length error: length %d",
720 nl->name, msg.msg_namelen);
721 return -1;
722 }
723
724 if (IS_ZEBRA_DEBUG_KERNEL_MSGDUMP_RECV) {
725 zlog_debug("%s: << netlink message dump [recv]",
726 __func__);
727 zlog_hexdump(buf, status);
728 }
729
730 #if defined(HANDLE_NETLINK_FUZZING)
731 if (!netlink_read) {
732 zlog_debug("Writing incoming netlink message");
733 netlink_write_incoming(buf, status,
734 netlink_file_counter++);
735 }
736 #endif /* HANDLE_NETLINK_FUZZING */
737
738 read_in++;
739 for (h = (struct nlmsghdr *)buf;
740 (status >= 0 && NLMSG_OK(h, (unsigned int)status));
741 h = NLMSG_NEXT(h, status)) {
742 /* Finish of reading. */
743 if (h->nlmsg_type == NLMSG_DONE)
744 return ret;
745
746 /* Error handling. */
747 if (h->nlmsg_type == NLMSG_ERROR) {
748 struct nlmsgerr *err =
749 (struct nlmsgerr *)NLMSG_DATA(h);
750 int errnum = err->error;
751 int msg_type = err->msg.nlmsg_type;
752
753 if (h->nlmsg_len
754 < NLMSG_LENGTH(sizeof(struct nlmsgerr))) {
755 zlog_err("%s error: message truncated",
756 nl->name);
757 return -1;
758 }
759
760 /*
761 * Parse the extended information before
762 * we actually handle it.
763 * At this point in time we do not
764 * do anything other than report the
765 * issue.
766 */
767 if (h->nlmsg_flags & NLM_F_ACK_TLVS)
768 netlink_parse_extended_ack(h);
769
770 /* If the error field is zero, then this is an
771 * ACK */
772 if (err->error == 0) {
773 if (IS_ZEBRA_DEBUG_KERNEL) {
774 zlog_debug(
775 "%s: %s ACK: type=%s(%u), seq=%u, pid=%u",
776 __FUNCTION__, nl->name,
777 nl_msg_type_to_str(
778 err->msg.nlmsg_type),
779 err->msg.nlmsg_type,
780 err->msg.nlmsg_seq,
781 err->msg.nlmsg_pid);
782 }
783
784 /* return if not a multipart message,
785 * otherwise continue */
786 if (!(h->nlmsg_flags & NLM_F_MULTI))
787 return 0;
788 continue;
789 }
790
791 /* Deal with errors that occur because of races
792 * in link handling */
793 if (nl == &zns->netlink_cmd
794 && ((msg_type == RTM_DELROUTE
795 && (-errnum == ENODEV
796 || -errnum == ESRCH))
797 || (msg_type == RTM_NEWROUTE
798 && (-errnum == ENETDOWN
799 || -errnum == EEXIST)))) {
800 if (IS_ZEBRA_DEBUG_KERNEL)
801 zlog_debug(
802 "%s: error: %s type=%s(%u), seq=%u, pid=%u",
803 nl->name,
804 safe_strerror(-errnum),
805 nl_msg_type_to_str(
806 msg_type),
807 msg_type,
808 err->msg.nlmsg_seq,
809 err->msg.nlmsg_pid);
810 return 0;
811 }
812
813 /* We see RTM_DELNEIGH when shutting down an
814 * interface with an IPv4
815 * link-local. The kernel should have already
816 * deleted the neighbor
817 * so do not log these as an error.
818 */
819 if (msg_type == RTM_DELNEIGH
820 || (nl == &zns->netlink_cmd
821 && msg_type == RTM_NEWROUTE
822 && (-errnum == ESRCH
823 || -errnum == ENETUNREACH))) {
824 /* This is known to happen in some
825 * situations, don't log
826 * as error.
827 */
828 if (IS_ZEBRA_DEBUG_KERNEL)
829 zlog_debug(
830 "%s error: %s, type=%s(%u), seq=%u, pid=%u",
831 nl->name,
832 safe_strerror(-errnum),
833 nl_msg_type_to_str(
834 msg_type),
835 msg_type,
836 err->msg.nlmsg_seq,
837 err->msg.nlmsg_pid);
838 } else
839 zlog_err(
840 "%s error: %s, type=%s(%u), seq=%u, pid=%u",
841 nl->name,
842 safe_strerror(-errnum),
843 nl_msg_type_to_str(msg_type),
844 msg_type, err->msg.nlmsg_seq,
845 err->msg.nlmsg_pid);
846
847 return -1;
848 }
849
850 /* OK we got netlink message. */
851 if (IS_ZEBRA_DEBUG_KERNEL)
852 zlog_debug(
853 "netlink_parse_info: %s type %s(%u), len=%d, seq=%u, pid=%u",
854 nl->name,
855 nl_msg_type_to_str(h->nlmsg_type),
856 h->nlmsg_type, h->nlmsg_len,
857 h->nlmsg_seq, h->nlmsg_pid);
858
859
860 /*
861 * Ignore messages that maybe sent from
862 * other actors besides the kernel
863 */
864 if (snl.nl_pid != 0) {
865 zlog_err("Ignoring message from pid %u",
866 snl.nl_pid);
867 continue;
868 }
869
870 error = (*filter)(h, zns->ns_id, startup);
871 if (error < 0) {
872 zlog_err("%s filter function error", nl->name);
873 zlog_backtrace(LOG_ERR);
874 ret = error;
875 }
876 }
877
878 /* After error care. */
879 if (msg.msg_flags & MSG_TRUNC) {
880 zlog_err("%s error: message truncated", nl->name);
881 continue;
882 }
883 if (status) {
884 zlog_err("%s error: data remnant size %d", nl->name,
885 status);
886 return -1;
887 }
888 }
889 return ret;
890 }
891
892 /*
893 * netlink_talk
894 *
895 * sendmsg() to netlink socket then recvmsg().
896 * Calls netlink_parse_info to parse returned data
897 *
898 * filter -> The filter to read final results from kernel
899 * nlmsghdr -> The data to send to the kernel
900 * nl -> The netlink socket information
901 * zns -> The zebra namespace information
902 * startup -> Are we reading in under startup conditions
903 * This is passed through eventually to filter.
904 */
905 int netlink_talk(int (*filter)(struct nlmsghdr *, ns_id_t, int startup),
906 struct nlmsghdr *n, struct nlsock *nl, struct zebra_ns *zns,
907 int startup)
908 {
909 int status;
910 struct sockaddr_nl snl;
911 struct iovec iov;
912 struct msghdr msg;
913 int save_errno;
914
915 memset(&snl, 0, sizeof snl);
916 memset(&iov, 0, sizeof iov);
917 memset(&msg, 0, sizeof msg);
918
919 iov.iov_base = n;
920 iov.iov_len = n->nlmsg_len;
921 msg.msg_name = (void *)&snl;
922 msg.msg_namelen = sizeof snl;
923 msg.msg_iov = &iov;
924 msg.msg_iovlen = 1;
925
926 snl.nl_family = AF_NETLINK;
927
928 n->nlmsg_seq = ++nl->seq;
929 n->nlmsg_pid = nl->snl.nl_pid;
930
931 if (IS_ZEBRA_DEBUG_KERNEL)
932 zlog_debug(
933 "netlink_talk: %s type %s(%u), len=%d seq=%u flags 0x%x",
934 nl->name, nl_msg_type_to_str(n->nlmsg_type),
935 n->nlmsg_type, n->nlmsg_len, n->nlmsg_seq,
936 n->nlmsg_flags);
937
938 /* Send message to netlink interface. */
939 if (zserv_privs.change(ZPRIVS_RAISE))
940 zlog_err("Can't raise privileges");
941 status = sendmsg(nl->sock, &msg, 0);
942 save_errno = errno;
943 if (zserv_privs.change(ZPRIVS_LOWER))
944 zlog_err("Can't lower privileges");
945
946 if (IS_ZEBRA_DEBUG_KERNEL_MSGDUMP_SEND) {
947 zlog_debug("%s: >> netlink message dump [sent]", __func__);
948 zlog_hexdump(n, n->nlmsg_len);
949 }
950
951 if (status < 0) {
952 zlog_err("netlink_talk sendmsg() error: %s",
953 safe_strerror(save_errno));
954 return -1;
955 }
956
957
958 /*
959 * Get reply from netlink socket.
960 * The reply should either be an acknowlegement or an error.
961 */
962 return netlink_parse_info(filter, nl, zns, 0, startup);
963 }
964
965 /* Issue request message to kernel via netlink socket. GET messages
966 * are issued through this interface.
967 */
968 int netlink_request(struct nlsock *nl, struct nlmsghdr *n)
969 {
970 int ret;
971 struct sockaddr_nl snl;
972 int save_errno;
973
974 /* Check netlink socket. */
975 if (nl->sock < 0) {
976 zlog_err("%s socket isn't active.", nl->name);
977 return -1;
978 }
979
980 /* Fill common fields for all requests. */
981 n->nlmsg_flags = NLM_F_ROOT | NLM_F_MATCH | NLM_F_REQUEST;
982 n->nlmsg_pid = nl->snl.nl_pid;
983 n->nlmsg_seq = ++nl->seq;
984
985 memset(&snl, 0, sizeof snl);
986 snl.nl_family = AF_NETLINK;
987
988 /* Raise capabilities and send message, then lower capabilities. */
989 if (zserv_privs.change(ZPRIVS_RAISE)) {
990 zlog_err("Can't raise privileges");
991 return -1;
992 }
993
994 ret = sendto(nl->sock, (void *)n, n->nlmsg_len, 0,
995 (struct sockaddr *)&snl, sizeof snl);
996 save_errno = errno;
997
998 if (zserv_privs.change(ZPRIVS_LOWER))
999 zlog_err("Can't lower privileges");
1000
1001 if (ret < 0) {
1002 zlog_err("%s sendto failed: %s", nl->name,
1003 safe_strerror(save_errno));
1004 return -1;
1005 }
1006
1007 return 0;
1008 }
1009
1010 /* Exported interface function. This function simply calls
1011 netlink_socket (). */
1012 void kernel_init(struct zebra_ns *zns)
1013 {
1014 unsigned long groups;
1015 #if defined SOL_NETLINK
1016 int one, ret;
1017 #endif
1018
1019 /*
1020 * Initialize netlink sockets
1021 *
1022 * If RTMGRP_XXX exists use that, but at some point
1023 * I think the kernel developers realized that
1024 * keeping track of all the different values would
1025 * lead to confusion, so we need to convert the
1026 * RTNLGRP_XXX to a bit position for ourself
1027 */
1028 groups = RTMGRP_LINK |
1029 RTMGRP_IPV4_ROUTE |
1030 RTMGRP_IPV4_IFADDR |
1031 RTMGRP_IPV6_ROUTE |
1032 RTMGRP_IPV6_IFADDR |
1033 RTMGRP_IPV4_MROUTE |
1034 RTMGRP_NEIGH |
1035 (1 << (RTNLGRP_IPV4_RULE - 1)) |
1036 (1 << (RTNLGRP_IPV6_RULE - 1));
1037
1038 snprintf(zns->netlink.name, sizeof(zns->netlink.name),
1039 "netlink-listen (NS %u)", zns->ns_id);
1040 zns->netlink.sock = -1;
1041 if (netlink_socket(&zns->netlink, groups, zns->ns_id) < 0) {
1042 zlog_err("Failure to create %s socket",
1043 zns->netlink.name);
1044 exit(-1);
1045 }
1046
1047 snprintf(zns->netlink_cmd.name, sizeof(zns->netlink_cmd.name),
1048 "netlink-cmd (NS %u)", zns->ns_id);
1049 zns->netlink_cmd.sock = -1;
1050 if (netlink_socket(&zns->netlink_cmd, 0, zns->ns_id) < 0) {
1051 zlog_err("Failure to create %s socket",
1052 zns->netlink_cmd.name);
1053 exit(-1);
1054 }
1055
1056 /*
1057 * SOL_NETLINK is not available on all platforms yet
1058 * apparently. It's in bits/socket.h which I am not
1059 * sure that we want to pull into our build system.
1060 */
1061 #if defined SOL_NETLINK
1062 /*
1063 * Let's tell the kernel that we want to receive extended
1064 * ACKS over our command socket
1065 */
1066 one = 1;
1067 ret = setsockopt(zns->netlink_cmd.sock, SOL_NETLINK, NETLINK_EXT_ACK,
1068 &one, sizeof(one));
1069
1070 if (ret < 0)
1071 zlog_notice("Registration for extended ACK failed : %d %s",
1072 errno, safe_strerror(errno));
1073 #endif
1074
1075 /* Register kernel socket. */
1076 if (fcntl(zns->netlink.sock, F_SETFL, O_NONBLOCK) < 0)
1077 zlog_err("Can't set %s socket error: %s(%d)",
1078 zns->netlink.name, safe_strerror(errno), errno);
1079
1080 if (fcntl(zns->netlink_cmd.sock, F_SETFL, O_NONBLOCK) < 0)
1081 zlog_err("Can't set %s socket error: %s(%d)",
1082 zns->netlink_cmd.name, safe_strerror(errno), errno);
1083
1084 /* Set receive buffer size if it's set from command line */
1085 if (nl_rcvbufsize)
1086 netlink_recvbuf(&zns->netlink, nl_rcvbufsize);
1087
1088 netlink_install_filter(zns->netlink.sock,
1089 zns->netlink_cmd.snl.nl_pid);
1090 zns->t_netlink = NULL;
1091
1092 thread_add_read(zebrad.master, kernel_read, zns,
1093 zns->netlink.sock, &zns->t_netlink);
1094
1095 rt_netlink_init();
1096 }
1097
1098 void kernel_terminate(struct zebra_ns *zns)
1099 {
1100 THREAD_READ_OFF(zns->t_netlink);
1101
1102 if (zns->netlink.sock >= 0) {
1103 close(zns->netlink.sock);
1104 zns->netlink.sock = -1;
1105 }
1106
1107 if (zns->netlink_cmd.sock >= 0) {
1108 close(zns->netlink_cmd.sock);
1109 zns->netlink_cmd.sock = -1;
1110 }
1111 }
1112
1113 #endif /* HAVE_NETLINK */