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