1 /* Copyright (C) 2020-2021 Greenbone Networks GmbH
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later
4 *
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "util.h"
21
22 #include "../base/networking.h" /* for range_t */
23
24 #include <stdio.h>
25 #include <sys/types.h>
26 #include <sys/socket.h>
27 #include <errno.h>
28 #include <glib.h>
29 #include <ifaddrs.h> /* for getifaddrs() */
30 #include <net/ethernet.h>
31 #include <net/if.h> /* for if_nametoindex() */
32 #ifdef AF_LINK
33 # include <net/if_dl.h>
34 #endif
35 #ifdef AF_PACKET
36 # include <netpacket/packet.h>
37 #endif
38 #include <stdlib.h>
39 #include <string.h>
40 #include <sys/ioctl.h>
41 #include <sys/socket.h>
42 #include <unistd.h>
43
44 #undef G_LOG_DOMAIN
45 /**
46 * @brief GLib log domain.
47 */
48 #define G_LOG_DOMAIN "libgvm boreas"
49
50 static boreas_error_t
51 set_socket (socket_type_t, int *);
52
53 /**
54 * @brief Checksum calculation.
55 *
56 * From W.Richard Stevens "UNIX NETWORK PROGRAMMING" book. libfree/in_cksum.c
57 * TODO: Section 8.7 of TCPv2 has more efficient implementation
58 **/
59 uint16_t
in_cksum(uint16_t * addr,int len)60 in_cksum (uint16_t *addr, int len)
61 {
62 int nleft = len;
63 uint32_t sum = 0;
64 uint16_t *w = addr;
65 uint16_t answer = 0;
66
67 /*
68 * Our algorithm is simple, using a 32 bit accumulator (sum), we add
69 * sequential 16 bit words to it, and at the end, fold back all the
70 * carry bits from the top 16 bits into the lower 16 bits.
71 */
72 while (nleft > 1)
73 {
74 sum += *w++;
75 nleft -= 2;
76 }
77
78 /* mop up an odd byte, if necessary */
79 if (nleft == 1)
80 {
81 *(unsigned char *) (&answer) = *(unsigned char *) w;
82 sum += answer;
83 }
84
85 /* add back carry outs from top 16 bits to low 16 bits */
86 sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */
87 sum += (sum >> 16); /* add carry */
88 answer = ~sum; /* truncate to 16 bits */
89 return (answer);
90 }
91
92 /**
93 * @brief Get the source mac address of the given interface
94 * or of the first non lo interface.
95 *
96 * @param interface Interface to get mac address from or NULL if first non lo
97 * interface should be used.
98 * @param[out] mac Location where to store mac address.
99 *
100 * @return 0 on success, -1 on error.
101 */
102 int
get_source_mac_addr(char * interface,uint8_t * mac)103 get_source_mac_addr (char *interface, uint8_t *mac)
104 {
105 struct ifaddrs *ifaddr = NULL;
106 struct ifaddrs *ifa = NULL;
107 int interface_provided = 0;
108
109 if (interface)
110 interface_provided = 1;
111
112 if (getifaddrs (&ifaddr) == -1)
113 {
114 g_debug ("%s: getifaddr failed: %s", __func__, strerror (errno));
115 return -1;
116 }
117 else
118 {
119 for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next)
120 {
121 if ((ifa->ifa_addr) && (ifa->ifa_addr->sa_family == AF_LINK)
122 && !(ifa->ifa_flags & (IFF_LOOPBACK)))
123 {
124 if (interface_provided)
125 {
126 if (g_strcmp0 (interface, ifa->ifa_name) == 0)
127 {
128 struct sockaddr_dl *s =
129 (struct sockaddr_dl *) ifa->ifa_addr;
130 memcpy (mac, s->sdl_data, 6 * sizeof (uint8_t));
131 }
132 }
133 else
134 {
135 struct sockaddr_dl *s = (struct sockaddr_dl *) ifa->ifa_addr;
136 memcpy (mac, s->sdl_data, 6 * sizeof (uint8_t));
137 }
138 }
139 }
140 freeifaddrs (ifaddr);
141 }
142 return 0;
143 }
144
145 /**
146 * @brief Figure out source address for given destination.
147 *
148 * This function uses a well known trick for getting the source address used
149 * for a given destination by calling connect() and getsockname() on an udp
150 * socket.
151 *
152 * @param[in] udpv6soc Location of the socket to use.
153 * @param[in] dst Destination address.
154 * @param[out] src Source address.
155 *
156 * @return 0 on success, boreas_error_t on failure.
157 */
158 boreas_error_t
get_source_addr_v6(int * udpv6soc,struct in6_addr * dst,struct in6_addr * src)159 get_source_addr_v6 (int *udpv6soc, struct in6_addr *dst, struct in6_addr *src)
160 {
161 struct sockaddr_storage storage;
162 struct sockaddr_in6 sin;
163 socklen_t sock_len;
164 boreas_error_t error;
165
166 memset (&sin, 0, sizeof (struct sockaddr_in6));
167 sin.sin6_family = AF_INET6;
168 sin.sin6_addr = *dst;
169 sin.sin6_port = htons (9); /* discard port (see RFC 863) */
170 memcpy (&storage, &sin, sizeof (sin));
171
172 error = NO_ERROR;
173 sock_len = sizeof (storage);
174 if (connect (*udpv6soc, (const struct sockaddr *) &storage, sock_len) < 0)
175 {
176 g_warning ("%s: connect() on udpv6soc failed: %s %d", __func__,
177 strerror (errno), errno);
178 /* State of the socket is unspecified. Close the socket and create a new
179 * one. */
180 if ((close (*udpv6soc)) != 0)
181 {
182 g_debug ("%s: Error in close(): %s", __func__, strerror (errno));
183 }
184 set_socket (UDPV6, udpv6soc);
185 error = BOREAS_NO_SRC_ADDR_FOUND;
186 }
187 else
188 {
189 if (getsockname (*udpv6soc, (struct sockaddr *) &storage, &sock_len) < 0)
190 {
191 g_debug ("%s: getsockname() on updv6soc failed: %s", __func__,
192 strerror (errno));
193 error = BOREAS_NO_SRC_ADDR_FOUND;
194 }
195 }
196
197 if (!error)
198 {
199 /* Set source address. */
200 memcpy (src, &((struct sockaddr_in6 *) (&storage))->sin6_addr,
201 sizeof (struct in6_addr));
202
203 /* Dissolve association so we can connect() on same socket again in later
204 * call to get_source_addr_v4(). */
205 sin.sin6_family = AF_UNSPEC;
206 sock_len = sizeof (storage);
207 memcpy (&storage, &sin, sizeof (sin));
208 if (connect (*udpv6soc, (const struct sockaddr *) &storage, sock_len) < 0)
209 g_debug ("%s: connect() on udpv6soc to dissolve association failed: %s",
210 __func__, strerror (errno));
211 }
212
213 return error;
214 }
215
216 /**
217 * @brief Figure out source address for given destination.
218 *
219 * This function uses a well known trick for getting the source address used
220 * for a given destination by calling connect() and getsockname() on an udp
221 * socket.
222 *
223 * @param[in] udpv4soc Location of the socket to use.
224 * @param[in] dst Destination address.
225 * @param[out] src Source address.
226 *
227 * @return 0 on success, boreas_error_t on failure.
228 */
229 boreas_error_t
get_source_addr_v4(int * udpv4soc,struct in_addr * dst,struct in_addr * src)230 get_source_addr_v4 (int *udpv4soc, struct in_addr *dst, struct in_addr *src)
231 {
232 struct sockaddr_storage storage;
233 struct sockaddr_in sin;
234 socklen_t sock_len;
235 boreas_error_t error;
236
237 memset (&sin, 0, sizeof (struct sockaddr_in));
238 sin.sin_family = AF_INET;
239 sin.sin_addr.s_addr = dst->s_addr;
240 sin.sin_port = htons (9); /* discard port (see RFC 863) */
241 memcpy (&storage, &sin, sizeof (sin));
242
243 error = NO_ERROR;
244 sock_len = sizeof (storage);
245 if (connect (*udpv4soc, (const struct sockaddr *) &storage, sock_len) < 0)
246 {
247 g_warning ("%s: connect() on udpv4soc failed: %s", __func__,
248 strerror (errno));
249 /* State of the socket is unspecified. Close the socket and create a new
250 * one. */
251 if ((close (*udpv4soc)) != 0)
252 {
253 g_debug ("%s: Error in close(): %s", __func__, strerror (errno));
254 }
255 set_socket (UDPV4, udpv4soc);
256 error = BOREAS_NO_SRC_ADDR_FOUND;
257 }
258 else
259 {
260 if (getsockname (*udpv4soc, (struct sockaddr *) &storage, &sock_len) < 0)
261 {
262 g_debug ("%s: getsockname() on updv4soc failed: %s", __func__,
263 strerror (errno));
264 error = BOREAS_NO_SRC_ADDR_FOUND;
265 }
266 }
267
268 if (!error)
269 {
270 /* Set source address. */
271 memcpy (src, &((struct sockaddr_in *) (&storage))->sin_addr,
272 sizeof (struct in_addr));
273
274 /* Dissolve association so we can connect() on same socket again in later
275 * call to get_source_addr_v4(). */
276 sin.sin_family = AF_UNSPEC;
277 sock_len = sizeof (storage);
278 memcpy (&storage, &sin, sizeof (sin));
279 if (connect (*udpv4soc, (const struct sockaddr *) &storage, sock_len) < 0)
280 g_debug ("%s: connect() on udpv4soc to dissolve association failed: %s",
281 __func__, strerror (errno));
282 }
283
284 return error;
285 }
286
287 /**
288 * @brief Put all ports of a given port range into the ports array.
289 *
290 * @param range Pointer to a range_t.
291 * @param ports_array Pointer to an GArray.
292 */
293 void
fill_ports_array(gpointer range,gpointer ports_array)294 fill_ports_array (gpointer range, gpointer ports_array)
295 {
296 gboolean range_exclude;
297 int range_start;
298 int range_end;
299 int i;
300 /* Use uint16_t for port array elements. tcphdr port type is uint16_t. */
301 uint16_t port_sized;
302
303 range_start = ((range_t *) range)->start;
304 range_end = ((range_t *) range)->end;
305 range_exclude = ((range_t *) range)->exclude;
306
307 /* If range should be excluded do not use it. */
308 if (range_exclude)
309 return;
310
311 /* Only single port in range. */
312 if (range_end == 0 || (range_start == range_end))
313 {
314 port_sized = (uint16_t) range_start;
315 g_array_append_val (ports_array, port_sized);
316 return;
317 }
318 else
319 {
320 for (i = range_start; i <= range_end; i++)
321 {
322 port_sized = (uint16_t) i;
323 g_array_append_val (ports_array, port_sized);
324 }
325 }
326 }
327
328 boreas_error_t
close_all_needed_sockets(struct scanner * scanner,alive_test_t alive_test)329 close_all_needed_sockets (struct scanner *scanner, alive_test_t alive_test)
330 {
331 boreas_error_t error;
332
333 error = NO_ERROR;
334
335 if (alive_test & ALIVE_TEST_ICMP)
336 {
337 if ((close (scanner->icmpv4soc)) != 0)
338 {
339 g_warning ("%s: Error in close(): %s", __func__, strerror (errno));
340 error = -1;
341 }
342 if ((close (scanner->icmpv6soc)) != 0)
343 {
344 g_warning ("%s: Error in close(): %s", __func__, strerror (errno));
345 error = -1;
346 }
347 }
348
349 if ((alive_test & ALIVE_TEST_TCP_ACK_SERVICE)
350 || (alive_test & ALIVE_TEST_TCP_SYN_SERVICE))
351 {
352 if ((close (scanner->tcpv4soc)) != 0)
353 {
354 g_warning ("%s: Error in close(): %s", __func__, strerror (errno));
355 error = -1;
356 }
357 if ((close (scanner->tcpv6soc)) != 0)
358 {
359 g_warning ("%s: Error in close(): %s", __func__, strerror (errno));
360 error = -1;
361 }
362 if ((close (scanner->udpv4soc)) != 0)
363 {
364 g_warning ("%s: Error in close(): %s", __func__, strerror (errno));
365 error = -1;
366 }
367 if ((close (scanner->udpv6soc)) != 0)
368 {
369 g_warning ("%s: Error in close(): %s", __func__, strerror (errno));
370 error = -1;
371 }
372 }
373
374 if ((alive_test & ALIVE_TEST_ARP))
375 {
376 if ((close (scanner->arpv4soc)) != 0)
377 {
378 g_warning ("%s: Error in close(): %s", __func__, strerror (errno));
379 error = -1;
380 }
381 if ((close (scanner->arpv6soc)) != 0)
382 {
383 g_warning ("%s: Error in close(): %s", __func__, strerror (errno));
384 error = -1;
385 }
386 }
387
388 return error;
389 }
390
391 /**
392 * @brief Set the SO_BROADCAST socket option for given socket.
393 *
394 * @param socket The socket to apply the option to.
395 *
396 * @return 0 on success, boreas_error_t on error.
397 */
398 static boreas_error_t
set_broadcast(int socket)399 set_broadcast (int socket)
400 {
401 boreas_error_t error = NO_ERROR;
402 int broadcast = 1;
403 if (setsockopt (socket, SOL_SOCKET, SO_BROADCAST, &broadcast,
404 sizeof (broadcast))
405 < 0)
406 {
407 g_warning ("%s: failed to set socket option SO_BROADCAST: %s", __func__,
408 strerror (errno));
409 error = BOREAS_SETTING_SOCKET_OPTION_FAILED;
410 }
411 return error;
412 }
413
414 /**
415 * @brief Set a new socket of specified type.
416 *
417 * @param[in] socket_type What type of socket to get.
418 *
419 * @param[out] scanner_socket Location to save the socket into.
420 *
421 * @return 0 on success, boreas_error_t on error.
422 */
423 static boreas_error_t
set_socket(socket_type_t socket_type,int * scanner_socket)424 set_socket (socket_type_t socket_type, int *scanner_socket)
425 {
426 boreas_error_t error = NO_ERROR;
427 int soc = -1;
428 switch (socket_type)
429 {
430 case UDPV4:
431 {
432 soc = socket (AF_INET, SOCK_DGRAM, IPPROTO_UDP);
433 if (soc < 0)
434 {
435 g_warning ("%s: failed to open UDPV4 socket: %s", __func__,
436 strerror (errno));
437 error = BOREAS_OPENING_SOCKET_FAILED;
438 }
439 }
440 break;
441 case UDPV6:
442 {
443 soc = socket (AF_INET6, SOCK_DGRAM, IPPROTO_UDP);
444 if (soc < 0)
445 {
446 g_warning ("%s: failed to open UDPV4 socket: %s", __func__,
447 strerror (errno));
448 error = BOREAS_OPENING_SOCKET_FAILED;
449 }
450 }
451 break;
452 case TCPV4:
453 {
454 soc = socket (AF_INET, SOCK_RAW, IPPROTO_RAW);
455 if (soc < 0)
456 {
457 g_warning ("%s: failed to open TCPV4 socket: %s", __func__,
458 strerror (errno));
459 error = BOREAS_OPENING_SOCKET_FAILED;
460 }
461 else
462 {
463 int opt = 1;
464 if (setsockopt (soc, IPPROTO_IP, IP_HDRINCL, (char *) &opt,
465 sizeof (opt))
466 < 0)
467 {
468 g_warning (
469 "%s: failed to set socket options on TCPV4 socket: %s",
470 __func__, strerror (errno));
471 error = BOREAS_SETTING_SOCKET_OPTION_FAILED;
472 }
473 }
474 }
475 break;
476 case TCPV6:
477 {
478 soc = socket (AF_INET6, SOCK_RAW, IPPROTO_RAW);
479 if (soc < 0)
480 {
481 g_warning ("%s: failed to open TCPV6 socket: %s", __func__,
482 strerror (errno));
483 error = BOREAS_OPENING_SOCKET_FAILED;
484 }
485 else
486 {
487 int opt_on = 1;
488 if (setsockopt (soc, IPPROTO_IPV6, IP_HDRINCL,
489 (char *) &opt_on, // IPV6_HDRINCL
490 sizeof (opt_on))
491 < 0)
492 {
493 g_warning (
494 "%s: failed to set socket options on TCPV6 socket: %s",
495 __func__, strerror (errno));
496 error = BOREAS_SETTING_SOCKET_OPTION_FAILED;
497 }
498 }
499 }
500 break;
501 case ICMPV4:
502 {
503 soc = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP);
504 if (soc < 0)
505 {
506 g_warning ("%s: failed to open ICMPV4 socket: %s", __func__,
507 strerror (errno));
508 error = BOREAS_OPENING_SOCKET_FAILED;
509 }
510 }
511 break;
512 case ARPV6:
513 case ICMPV6:
514 {
515 soc = socket (AF_INET6, SOCK_RAW, IPPROTO_ICMPV6);
516 if (soc < 0)
517 {
518 g_warning ("%s: failed to open ARPV6/ICMPV6 socket: %s", __func__,
519 strerror (errno));
520 error = BOREAS_OPENING_SOCKET_FAILED;
521 }
522 }
523 break;
524 case ARPV4:
525 {
526 soc = socket (PF_LINK, SOCK_RAW, 0);
527 if (soc < 0)
528 {
529 g_warning ("%s: failed to open ARPV4 socket: %s", __func__,
530 strerror (errno));
531 return BOREAS_OPENING_SOCKET_FAILED;
532 }
533 }
534 break;
535 default:
536 error = BOREAS_OPENING_SOCKET_FAILED;
537 break;
538 }
539
540 /* set SO_BROADCAST socket option. If not set we get permission denied error
541 * on pinging broadcast address */
542 if (!error)
543 {
544 if ((error = set_broadcast (soc)) != 0)
545 return error;
546 }
547
548 *scanner_socket = soc;
549 return error;
550 }
551
552 /**
553 * @brief Set all sockets needed for the chosen detection methods.
554 *
555 * @param scanner Reference to scanner struct.
556 * @param alive_test Methods of alive detection to use provided as bitflag.
557 *
558 * @return 0 on success, boreas_error_t on error.
559 */
560 boreas_error_t
set_all_needed_sockets(struct scanner * scanner,alive_test_t alive_test)561 set_all_needed_sockets (struct scanner *scanner, alive_test_t alive_test)
562 {
563 boreas_error_t error = NO_ERROR;
564 if (alive_test & ALIVE_TEST_ICMP)
565 {
566 if ((error = set_socket (ICMPV4, &(scanner->icmpv4soc))) != 0)
567 return error;
568 if ((error = set_socket (ICMPV6, &(scanner->icmpv6soc))) != 0)
569 return error;
570 }
571
572 if ((alive_test & ALIVE_TEST_TCP_ACK_SERVICE)
573 || (alive_test & ALIVE_TEST_TCP_SYN_SERVICE))
574 {
575 if ((error = set_socket (TCPV4, &(scanner->tcpv4soc))) != 0)
576 return error;
577 if ((error = set_socket (TCPV6, &(scanner->tcpv6soc))) != 0)
578 return error;
579 if ((error = set_socket (UDPV4, &(scanner->udpv4soc))) != 0)
580 return error;
581 if ((error = set_socket (UDPV6, &(scanner->udpv6soc))) != 0)
582 return error;
583 }
584
585 if ((alive_test & ALIVE_TEST_ARP))
586 {
587 if ((error = set_socket (ARPV4, &(scanner->arpv4soc))) != 0)
588 return error;
589 if ((error = set_socket (ARPV6, &(scanner->arpv6soc))) != 0)
590 return error;
591 }
592
593 return error;
594 }
595
596 /**
597 * @brief Subtract two hashtables and count the remaining elements.
598 *
599 * The original hashtables are not changed during or after the count operation.
600 *
601 * @param A Base Hashtable.
602 * @param B Hashtable to be subtracted from A.
603 *
604 * @return count of remaining elements in A-B.
605 */
606 int
count_difference(GHashTable * hashtable_A,GHashTable * hashtable_B)607 count_difference (GHashTable *hashtable_A, GHashTable *hashtable_B)
608 {
609 int count = 0;
610
611 GHashTableIter target_hosts_iter;
612 gpointer key, value;
613
614 for (g_hash_table_iter_init (&target_hosts_iter, hashtable_A);
615 g_hash_table_iter_next (&target_hosts_iter, &key, &value);)
616 {
617 if (!g_hash_table_contains (hashtable_B, key))
618 {
619 count++;
620 }
621 }
622
623 return count;
624 }
625
626 /**
627 * @brief Check if socket send buffer is empty.
628 *
629 * @param[in] soc Socket.
630 * @param[out] err Set to -1 on error.
631 *
632 * @return 1 if so_sndbug is empyt, else 0.
633 */
634 static int
so_sndbuf_empty(int soc,int * err)635 so_sndbuf_empty (int soc, int *err)
636 {
637 int cur_so_sendbuf = -1;
638 if (ioctl (soc, TIOCOUTQ, &cur_so_sendbuf) == -1)
639 {
640 g_warning ("%s: ioctl error: %s", __func__, strerror (errno));
641 *err = -1;
642 return 0;
643 }
644 return cur_so_sendbuf ? 0 : 1;
645 }
646
647 /**
648 * @brief Wait until socket send buffer empty or timeout reached.
649 *
650 * @param soc Socket.
651 * @param timeout Timeout in seconds.
652 */
653 void
wait_until_so_sndbuf_empty(int soc,int timeout)654 wait_until_so_sndbuf_empty (int soc, int timeout)
655 {
656 int cnt = 0;
657 int err = 0;
658 int empty;
659
660 empty = so_sndbuf_empty (soc, &err);
661 for (; !empty && (err != -1) && (cnt / 10 != timeout);
662 empty = so_sndbuf_empty (soc, &err), cnt++)
663 {
664 usleep (100000);
665 }
666 }
667