attack.c 34.1 KB
Newer Older
1
/* OpenVAS
2
* $Id: attack.c 22719 2015-07-08 09:56:25Z mwiegand $
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
* Description: Launches the plugins, and manages multithreading.
*
* Authors: - Renaud Deraison <deraison@nessus.org> (Original pre-fork develoment)
*	   - Tim Brown <mailto:timb@openvas.org> (Initial fork)
*	   - Laban Mwangi <mailto:labanm@openvas.org> (Renaming work)
*	   - Tarik El-Yassem <mailto:tarik@openvas.org> (Headers section)
*	   - Geoff Galitz <mailto:geoff@eifel-consulting.eu (Minor debug edits)
*
* Copyright:
* Portions Copyright (C) 2006 Software in the Public Interest, Inc.
* Based on work Copyright (C) 1998 - 2006 Tenable Network Security, Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*/

#include <string.h>    /* for strlen() */
#include <unistd.h>    /* for close() */
#include <errno.h>     /* for errno() */
#include <sys/wait.h>  /* for waitpid() */
#include <arpa/inet.h> /* for inet_ntoa() */
#include <stdlib.h>    /* for exit() */

#include <glib.h>
37
#include <fcntl.h>
38

39 40 41
#include <openvas/base/openvas_hosts.h>
#include <openvas/base/openvas_networking.h>
#include <openvas/misc/openvas_proctitle.h>
42
#include <openvas/misc/kb.h>
43 44 45 46
#include <openvas/misc/network.h>        /* for auth_printf */
#include <openvas/misc/nvt_categories.h> /* for ACT_INIT */
#include <openvas/misc/pcap_openvas.h>   /* for v6_is_local_ip */
#include <openvas/misc/plugutils.h>      /* for plug_get_launch */
47 48
#include <openvas/misc/prefs.h>          /* for prefs_get() */
#include <openvas/misc/internal_com.h>
49

50 51
#include <openvas/base/nvticache.h>     /* for nvticache_t */

52 53 54 55
#include "attack.h"
#include "comm.h"
#include "hosts.h"
#include "log.h"
56
#include "ntp.h"
57 58 59 60 61 62 63 64 65 66 67 68 69 70
#include "pluginlaunch.h"
#include "pluginload.h"
#include "pluginscheduler.h"
#include "plugs_req.h"
#include "processes.h"
#include "sighand.h"
#include "utils.h"


#define ERR_HOST_DEAD -1
#define ERR_CANT_FORK -2

#define MAX_FORK_RETRIES 10

71 72
extern struct arglist *global_plugins;

73 74 75 76 77 78 79 80 81 82 83
/**
 * Bundles information about target(s), configuration (globals arglist) and
 * scheduler.
 */
struct attack_start_args
{
  struct arglist *globals;
  struct in6_addr hostip;
  char *host_mac_addr;
  plugins_scheduler_t sched;
  int thread_socket;
84 85 86
  int parent_socket;
  kb_t *net_kb;
  char *fqdn;
87 88
};

89 90 91 92 93
enum net_scan_status {
  NSS_NONE = 0,
  NSS_BUSY,
  NSS_DONE,
};
94 95 96 97 98 99 100

/*******************************************************

		PRIVATE FUNCTIONS

********************************************************/

101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
/**
 * @brief Sends the status of a host's scan.
 */
static int
comm_send_status (int soc, char *hostname, int curr, int max)
{
  char buffer[2048];

  if (soc < 0 || soc > 1024)
    return -1;

  if (strlen (hostname) > (sizeof (buffer) - 50))
    return -1;

  snprintf (buffer, sizeof (buffer),
            "SERVER <|> STATUS <|> %s <|> %d/%d <|> SERVER\n",
            hostname, curr, max);

  internal_send (soc, buffer, INTERNAL_COMM_MSG_TYPE_DATA);

  return 0;
}

static void
error_message_to_client (int soc, const char *msg, const char *hostname,
                         const char *port)
{
  send_printf (soc, "SERVER <|> ERRMSG <|> %s <|> %s <|> %s <|>  <|> SERVER\n",
               hostname ? hostname : "", port ? port : "",
               msg ? msg : "No error.");
}

static void
report_kb_failure (int soc, int errcode)
{
  gchar *msg;

  errcode = abs (errcode);
  msg = g_strdup_printf ("WARNING: Cannot connect to KB at '%s': %s'",
                         prefs_get ("kb_location"), strerror (errcode));
  log_write ("%s", msg);
  error_message_to_client (soc, msg, NULL, NULL);
  g_free (msg);
}
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159

static void
fork_sleep (int n)
{
  time_t then, now;

  now = then = time (NULL);
  while (now - then < n)
    {
      waitpid (-1, NULL, WNOHANG);
      usleep (10000);
      now = time (NULL);
    }
}

160 161
static enum net_scan_status
network_scan_status (struct arglist *globals)
162
{
163
  gchar *nss;
164

165 166 167 168 169 170 171 172 173 174
  nss = arg_get_value (globals, "network_scan_status");
  if (nss == NULL)
    return NSS_NONE;

  if (g_ascii_strcasecmp (nss, "busy") == 0)
    return NSS_BUSY;
  else if (g_ascii_strcasecmp (nss, "done") == 0)
    return NSS_DONE;
  else
    return NSS_NONE;
175 176 177 178 179 180 181
}

/**
 * @brief Inits an arglist which can be used by the plugins.
 *
 * The arglist will have following keys and (type, value):
 *  - NAME (string, The hostname parameter)
182
 *  - FQDN (string, Fully qualified domain name, e.g. host.domain.net)
183 184 185 186 187 188 189 190 191 192 193 194
 *  - MAC  (string, The mac parameter if non-NULL)
 *  - IP   (*in_adrr, The ip parameter)
 *  - VHOSTS (string, comma separated list of vhosts for this IP)
 *
 * @param mac      MAC- adress of host or NULL.
 * @param hostname Hostname to be set.
 * @param ip       in_adress struct to be set.
 * @param vhosts   vhosts list to be set
 *
 * @return A 'hostinfo' arglist.
 */
static struct arglist *
195 196
attack_init_hostinfos_vhosts (char *mac, char *hostname, struct in6_addr *ip,
                              char *vhosts, char *fqdn)
197 198 199
{
  struct arglist *hostinfos;

200
  hostinfos = g_malloc0 (sizeof (struct arglist));
201 202
  if (mac)
    {
203 204
      arg_add_value (hostinfos, "NAME", ARG_STRING, mac);
      arg_add_value (hostinfos, "MAC", ARG_STRING, mac);
205 206
    }
  else
207
    arg_add_value (hostinfos, "NAME", ARG_STRING, g_strdup (hostname));
208

209
  if (fqdn)
210 211
    arg_add_value (hostinfos, "FQDN", ARG_STRING, g_strdup (fqdn));
  arg_add_value (hostinfos, "IP", ARG_PTR, ip);
212
  if (vhosts)
213
    arg_add_value (hostinfos, "VHOSTS", ARG_STRING, g_strdup (vhosts));
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
  return (hostinfos);
}

/**
 * @brief Inits an arglist which can be used by the plugins.
 *
 * The arglist will have following keys and (type, value):
 *  - FQDN (string, Fully qualified domain name, e.g. host.domain.net)
 *  - NAME (string, The hostname parameter)
 *  - MAC  (string, The mac parameter if non-NULL)
 *  - IP   (*in_adrr, The ip parameter)
 *
 * @param mac      MAC- adress of host or NULL.
 * @param hostname Hostname to be set.
 * @param ip       in_adress struct to be set.
 *
 * @return A 'hostinfo' arglist.
 */
static struct arglist *
233 234
attack_init_hostinfos (char *mac, char *hostname, struct in6_addr *ip,
                       char *fqdn)
235 236 237
{
  struct arglist *hostinfos;

238
  hostinfos = g_malloc0 (sizeof (struct arglist));
239 240
  if (mac)
    {
241 242
      arg_add_value (hostinfos, "NAME", ARG_STRING, mac);
      arg_add_value (hostinfos, "MAC", ARG_STRING, mac);
243 244
    }
  else
245
    arg_add_value (hostinfos, "NAME", ARG_STRING, g_strdup (hostname));
246
  if (fqdn)
247
    arg_add_value (hostinfos, "FQDN", ARG_STRING, g_strdup (fqdn));
248

249
  arg_add_value (hostinfos, "IP", ARG_PTR, ip);
250 251 252
  return (hostinfos);
}

253 254 255 256 257 258 259 260
int global_scan_stop = 0;

static int
scan_is_stopped ()
{
 return global_scan_stop;
}

261 262 263 264 265 266 267 268 269 270 271 272
/**
 * @brief Launches a nvt. Respects safe check preference (i.e. does not try
 * @brief destructive nvt if save_checks is yes).
 *
 * Does not launch a plugin twice if !save_kb_replay.
 *
 * @param new_kb  If TRUE, kb is new and shall be saved.
 *
 * @return ERR_HOST_DEAD if host died, ERR_CANT_FORK if forking failed,
 *         0 otherwise.
 */
static int
273 274
launch_plugin (struct arglist *globals, struct scheduler_plugin *plugin,
               char *hostname, struct arglist *hostinfos, kb_t kb)
275 276
{
  struct arglist *args = plugin->arglist->value;
277
  int optimize = prefs_get_bool ("optimize_test");
278
  int category = plugin->category;
Mati's avatar
Mati committed
279
  gboolean network_scan = FALSE;
280

281 282 283 284 285 286 287 288 289 290
  if (scan_is_stopped ())
    {
      if (category != ACT_END)
        {
          plugin->running_state = PLUGIN_STATUS_DONE;
          return 0;
        }
      else
        log_write ("Stopped scan wrap-up: Launching %s", plugin->arglist->name);
    }
291

292 293 294
  if (network_scan_status (globals) == NSS_BUSY)
    network_scan = TRUE;
  if (plug_get_launch (args) != LAUNCH_DISABLED)    /* can we launch it ? */
295 296 297
    {
      char *error;

298
      if (prefs_get_bool ("safe_checks")
299 300 301
          && (category == ACT_DESTRUCTIVE_ATTACK || category == ACT_KILL_HOST
              || category == ACT_FLOOD || category == ACT_DENIAL))
        {
302
          if (prefs_get_bool ("log_whole_attack"))
303
            log_write
304 305 306
              ("Not launching %s against %s %s (this is not an error)",
               nvticache_get_filename ((const char *)plugin->arglist->name),
               hostname,
307
               "because safe checks are enabled");
308
          plugin->running_state = PLUGIN_STATUS_DONE;
309 310 311
          return 0;
        }

312
      if (network_scan)
313
        {
314
          char asc_id[100], *oid;
315

316 317
          oid = plugin->arglist->name;
          assert (oid);
318 319
          snprintf (asc_id, sizeof (asc_id), "Launched/%s", oid);

320
          if (kb_item_get_int (kb, asc_id) > 0)
321
            {
322 323 324 325 326 327
              if (prefs_get_bool ("log_whole_attack"))
                log_write ("Not launching %s against %s because it has already "
                           "been lanched in the past (this is not an error)",
                           nvticache_get_filename ((const char *)plugin->arglist->name),
                           hostname);
              plugin->running_state = PLUGIN_STATUS_DONE;
328 329 330 331 332 333 334 335
              return 0;
            }
          else
            {
              kb_item_add_int (kb, asc_id, 1);
            }
        }

Mati's avatar
Mati committed
336 337 338
      /* Do not launch NVT if mandatory key is missing (e.g. an important tool
       * was not found). This is ignored during network wide scanning phases. */
      if (network_scan || mandatory_requirements_met (kb, plugin))
339 340 341 342 343 344
        error = NULL;
      else
        error = "because a mandatory key is missing";

      if (!error
          && (!optimize
345
              || !(error = requirements_plugin (kb, plugin))))
346 347
        {
          int pid;
348
          char *oid, *src;
349

350 351
          oid = plugin->arglist->name;
          src = nvticache_get_src (oid);
352
          /* Start the plugin */
353 354
          pid = plugin_launch (globals, plugin, hostinfos, kb, src);
          g_free (src);
355 356
          if (pid < 0)
            {
357
              plugin->running_state = PLUGIN_STATUS_UNRUN;
358 359 360
              return ERR_CANT_FORK;
            }

361 362 363 364
          if (prefs_get_bool ("log_whole_attack"))
            log_write ("Launching %s against %s [%d]",
                       nvticache_get_filename ((const char *)plugin->arglist->name),
                       hostname, pid);
365 366 367 368 369

          /* Stop the test if the host is 'dead' */
          if (kb_item_get_int (kb, "Host/dead") > 0
              || kb_item_get_int (kb, "Host/ping_failed") > 0)
            {
370
              log_write ("The remote host (%s) is dead", hostname);
371
              pluginlaunch_stop ();
372
              plugin->running_state = PLUGIN_STATUS_DONE;
373 374 375 376 377
              return ERR_HOST_DEAD;
            }
        }
      else                      /* requirements_plugin() failed */
        {
378 379
          plugin->running_state = PLUGIN_STATUS_DONE;
          if (prefs_get_bool ("log_whole_attack"))
380
            log_write
381 382 383
              ("Not launching %s against %s %s (this is not an error)",
               nvticache_get_filename ((const char *)plugin->arglist->name),
               hostname,
384 385 386 387
               error);
        }
    }                           /* if(plugins->launch) */
  else
388
    plugin->running_state = PLUGIN_STATUS_DONE;
389 390 391 392

  return 0;
}

393 394
static int
kb_duplicate(kb_t dst, kb_t src, const gchar *filter)
395
{
396
  struct kb_item *items, *p_itm;
397

398 399
  items = kb_item_get_pattern(src, filter ? filter : "*");
  for (p_itm = items; p_itm != NULL; p_itm = p_itm->next)
400
    {
401
      gchar *newname;
402

403 404 405
      newname = strstr(p_itm->name, "/");
      if (newname == NULL)
        newname = p_itm->name;
406
      else
407
        newname += 1; /* Skip the '/' */
408

409
      kb_item_add_str(dst, newname, p_itm->v_str);
410
    }
411
  return 0;
412 413 414 415 416 417 418 419 420 421 422 423 424 425
}

/**
 * @brief Inits or loads the knowledge base for a single host.
 *
 * Fills the knowledge base with host-specific login information for local
 * checks if defined.
 *
 * @param globals     Global preference arglist.
 * @param hostname    Name of the host.
 * @param new_kb[out] TRUE if the kb is new and shall be saved.
 *
 * @return A knowledge base.
 */
426 427
static kb_t
init_host_kb (struct arglist *globals, char *hostname,
428
              struct arglist *hostinfos, kb_t *network_kb)
429
{
430 431 432 433 434 435 436 437 438 439
  kb_t kb;
  gchar *vhosts, *hostname_pattern, *hoststr;
  enum net_scan_status nss;
  const gchar *kb_path = prefs_get ("kb_location");
  int rc, soc;
  struct in6_addr *hostip;

  nss = network_scan_status (globals);
  soc = arg_get_value_int (globals, "global_socket");
  switch (nss)
440
    {
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
      case NSS_DONE:
        rc = kb_new (&kb, kb_path);
        if (rc)
          {
            report_kb_failure (soc, rc);
            return NULL;
          }

        hostname_pattern = g_strdup_printf ("%s/*", hostname);
        kb_duplicate(kb, *network_kb, hostname_pattern);
        g_free(hostname_pattern);
        break;

      case NSS_BUSY:
        assert (network_kb != NULL);
        assert (*network_kb != NULL);
        kb = *network_kb;
        break;

      default:
        rc = kb_new (&kb, kb_path);
        if (rc)
          {
            report_kb_failure (soc, rc);
            return NULL;
          }
467 468
    }

469 470 471 472 473 474
  /* Add Hostname and Host-IP */
  hoststr = arg_get_value (hostinfos, "FQDN");
  if (hoststr)
    kb_item_add_str (kb, "Hostname", hoststr);
  hostip = arg_get_value (hostinfos, "IP");
  if (hostip)
475
    {
476 477 478 479
      char ipstr[INET6_ADDRSTRLEN];

      if (IN6_IS_ADDR_V4MAPPED (hostip))
        inet_ntop (AF_INET, ((char *) (hostip)) + 12, ipstr, sizeof (ipstr));
480
      else
481 482
        inet_ntop (AF_INET6, hostip, ipstr, sizeof (ipstr));
      kb_item_add_str (kb, "Host-IP", ipstr);
483
    }
484 485 486

  /* If vhosts is set, split it and put it in the KB. */
  vhosts = (gchar *)arg_get_value (hostinfos, "VHOSTS");
487 488 489
  if (vhosts)
    {
      gchar **vhosts_array = g_strsplit (vhosts, ",", 0);
490
      int i;
491

492 493 494 495
      for (i = 0; vhosts_array[i] != NULL; i++)
        kb_item_add_str (kb, "hostinfos/vhosts", vhosts_array[i]);

      g_strfreev (vhosts_array);
496 497 498 499 500 501 502 503 504
    }

  return kb;
}

/**
 * @brief Attack one host.
 */
static void
505 506
attack_host (struct arglist *globals, struct arglist *hostinfos,
             char *hostname, plugins_scheduler_t sched, kb_t *net_kb)
507 508
{
  /* Used for the status */
509
  int num_plugs, forks_retry = 0, global_socket;
510
  kb_t kb;
511
  struct arglist *plugins = global_plugins;
512

513
  proctitle_set ("openvassd: testing %s", arg_get_value (hostinfos, "NAME"));
514

515 516 517 518
  global_socket = arg_get_value_int (globals, "global_socket");
  kb = init_host_kb (globals, hostname, hostinfos, net_kb);
  if (kb == NULL)
    return;
519

520
  kb_lnk_reset (kb);
521

522
  num_plugs = get_active_plugins_number (plugins);
523 524

  /* launch the plugins */
525
  pluginlaunch_init ();
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543

  for (;;)
    {
      struct scheduler_plugin *plugin;
      pid_t parent;

      /* Check that our father is still alive */
      parent = getppid ();
      if (parent <= 1 || process_alive (parent) == 0)
        {
          pluginlaunch_stop ();
          return;
        }

      plugin = plugins_scheduler_next (sched);
      if (plugin != NULL && plugin != PLUG_RUNNING)
        {
          int e;
544
          static int last_status = 0, cur_plug = 0;
545 546

        again:
547
          e = launch_plugin (globals, plugin, hostname, hostinfos, kb);
548
          if (e < 0)
549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
            {
              /*
               * Remote host died
               */
              if (e == ERR_HOST_DEAD)
                goto host_died;
              else if (e == ERR_CANT_FORK)
                {
                  if (forks_retry < MAX_FORK_RETRIES)
                    {
                      forks_retry++;
                      log_write ("fork() failed - sleeping %d seconds (%s)",
                                 forks_retry, strerror (errno));
                      fork_sleep (forks_retry);
                      goto again;
                    }
                  else
                    {
                      log_write ("fork() failed too many times - aborting");
                      goto host_died;
                    }
                }
            }
572 573 574 575 576 577 578 579 580 581 582 583 584

          if ((cur_plug * 100) / num_plugs >= last_status
              && !scan_is_stopped ())
            {
              last_status = (cur_plug * 100) / num_plugs + 2;
              if (comm_send_status
                   (global_socket, hostname, cur_plug, num_plugs) < 0)
                {
                  pluginlaunch_stop ();
                  goto host_died;
                }
            }
          cur_plug++;
585 586 587 588 589 590 591 592
        }
      else if (plugin == NULL)
        break;
      else
        pluginlaunch_wait_for_free_process ();
    }

  pluginlaunch_wait ();
593 594
  if (!scan_is_stopped ())
    comm_send_status (global_socket, hostname, num_plugs, num_plugs);
595 596 597 598 599

host_died:
  pluginlaunch_stop ();
  plugins_scheduler_free (sched);

600 601
  if (net_kb == NULL || kb != *net_kb)
    kb_delete (kb);
602 603 604 605 606 607 608 609 610
}

/**
 * @brief Set up some data and jump into attack_host()
 */
static void
attack_start (struct attack_start_args *args)
{
  struct arglist *globals = args->globals;
611
  char host_str[INET6_ADDRSTRLEN];
612
  char *mac = args->host_mac_addr;
613 614
  struct arglist *plugs = global_plugins;
  struct in6_addr *hostip = &args->hostip;
615
  struct arglist *hostinfos;
616 617 618 619
  const char *non_simult = prefs_get ("non_simult_ports");
  const char *vhosts = prefs_get ("vhosts");
  const char *vhosts_ip = prefs_get ("vhosts_ip");
  int thread_socket;
620
  struct timeval then;
621
  plugins_scheduler_t sched = args->sched;
622
  kb_t *net_kb = args->net_kb;
623

624 625 626 627 628
  /* Stringify the IP address. */
  if (IN6_IS_ADDR_V4MAPPED (&args->hostip))
    inet_ntop (AF_INET, ((char *)(&args->hostip))+12, host_str,
               sizeof (host_str));
  else
629
    inet_ntop (AF_INET6, &args->hostip, host_str, sizeof (host_str));
630

631
  close (args->parent_socket);
632
  thread_socket = args->thread_socket;
633 634
  gettimeofday (&then, NULL);

635 636
  arg_add_value (preferences_get (), "non_simult_ports_list", ARG_ARGLIST,
                 (void *) list2arglist ((char *)non_simult));
637 638

  /* Options regarding the communication with our parent */
639 640 641 642
  close (arg_get_value_int (globals, "parent_socket"));
  arg_del_value (globals, "parent_socket");
  openvas_deregister_connection (arg_get_value_int (globals, "global_socket"));
  arg_set_value (globals, "global_socket", GSIZE_TO_POINTER (thread_socket));
643 644

  if (vhosts == NULL || vhosts_ip == NULL)
645
    hostinfos = attack_init_hostinfos (mac, host_str, hostip, args->fqdn);
646 647 648 649 650 651 652
  else
    {
      char *txt_ip;
      struct in_addr inaddr;
      inaddr.s_addr = hostip->s6_addr32[3];

      if (IN6_IS_ADDR_V4MAPPED (hostip))
653
        txt_ip = g_strdup (inet_ntoa (inaddr));
654
      else
655
        {
656 657
          char name[INET6_ADDRSTRLEN];
          txt_ip = g_strdup (inet_ntop (AF_INET6, hostip, name, sizeof (name)));
658
        }
659 660
      if (strcmp (vhosts_ip, txt_ip) != 0)
        vhosts = NULL;
661 662
      g_free (txt_ip);
      hostinfos = attack_init_hostinfos_vhosts (mac, host_str, hostip, (char *)vhosts,
663
                                                args->fqdn);
664 665 666
    }

  if (mac)
667
    strcpy (host_str, mac);
668

669 670
  plugins_set_socket (plugs, thread_socket);
  ntp_timestamp_host_scan_starts (thread_socket, host_str);
671 672

  // Start scan
673
  attack_host (globals, hostinfos, host_str, sched, net_kb);
674

675
  if (!scan_is_stopped ())
676
    {
677
      struct timeval now;
678

679 680 681 682 683 684 685 686 687 688 689
      ntp_timestamp_host_scan_ends (thread_socket, host_str);
      gettimeofday (&now, NULL);
      if (now.tv_usec < then.tv_usec)
        {
          then.tv_sec++;
          now.tv_usec += 1000000;
        }
        log_write ("Finished testing %s. Time : %ld.%.2ld secs", host_str,
                   (long) (now.tv_sec - then.tv_sec),
                   (long) ((now.tv_usec - then.tv_usec) / 10000));
    }
690 691 692
  shutdown (thread_socket, 2);
  close (thread_socket);
  g_free (args->fqdn);
693 694
}

695
static void
696
apply_hosts_preferences (openvas_hosts_t *hosts)
697
{
698 699
  const char *ordering = prefs_get ("hosts_ordering"),
             *exclude_hosts = prefs_get ("exclude_hosts");
700

701
  if (hosts == NULL)
702 703 704 705 706 707 708 709
    return;

  /* Hosts ordering strategy: sequential, random, reversed... */
  if (ordering)
    {
      if (!strcmp (ordering, "random"))
        {
          openvas_hosts_shuffle (hosts);
710
          log_write ("hosts_ordering: Random.");
711 712 713 714
        }
      else if (!strcmp (ordering, "reverse"))
        {
          openvas_hosts_reverse (hosts);
715
          log_write ("hosts_ordering: Reverse.");
716 717 718
        }
    }
  else
719
    log_write ("hosts_ordering: Sequential.");
720 721 722 723 724 725 726 727

  /* Exclude hosts ? */
  if (exclude_hosts)
    {
      /* Exclude hosts, resolving hostnames. */
      int ret = openvas_hosts_exclude (hosts, exclude_hosts, 1);

      if (ret >= 0)
728
        log_write ("exclude_hosts: Skipped %d host(s).", ret);
729
      else
730
        log_write ("exclude_hosts: Error.");
731 732 733
    }

  /* Reverse-lookup unify ? */
734 735
  if (prefs_get_bool ("reverse_lookup_unify"))
    log_write ("reverse_lookup_unify: Skipped %d host(s).",
736 737 738
               openvas_hosts_reverse_lookup_unify (hosts));

  /* Hosts that reverse-lookup only ? */
739 740
  if (prefs_get_bool ("reverse_lookup_only"))
    log_write ("reverse_lookup_only: Skipped %d host(s).",
741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777
               openvas_hosts_reverse_lookup_only (hosts));
}

static int
str_in_comma_list (const char *str, const char *comma_list)
{
  gchar **element, **split;

  if (str == NULL || comma_list == NULL)
    return 0;

  split = g_strsplit (comma_list, ",", 0);
  element = split;
  while (*element)
    {
      gchar *stripped = g_strstrip (*element);

      if (stripped && strcmp (stripped, str) == 0)
        {
          g_strfreev (split);
          return 1;
        }

      element++;
    }

  g_strfreev (split);
  return 0;
}

/*
 * Checks if a network interface is authorized to be used as source interface.
 *
 * @return 0 if iface is NULL, -1 if unauthorized by ifaces_deny/ifaces_allow,
 * -2 if by sys_ifaces_deny/sys_ifaces_allow, 1 otherwise.
 */
static int
778
iface_authorized (const char *iface)
779 780 781 782 783 784
{
  const char *ifaces_list;

  if (iface == NULL)
    return 0;

785
  ifaces_list = prefs_get ("ifaces_deny");
786 787
  if (ifaces_list && str_in_comma_list (iface, ifaces_list))
    return -1;
788
  ifaces_list = prefs_get ("ifaces_allow");
789 790 791
  if (ifaces_list && !str_in_comma_list (iface, ifaces_list))
    return -1;
  /* sys_* preferences are similar, but can't be overriden by the client. */
792
  ifaces_list = prefs_get ("sys_ifaces_deny");
793 794
  if (ifaces_list && str_in_comma_list (iface, ifaces_list))
    return -2;
795
  ifaces_list = prefs_get ("sys_ifaces_allow");
796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837
  if (ifaces_list && !str_in_comma_list (iface, ifaces_list))
    return -2;

  return 1;
}

/*
 * Checks if a host is authorized to be scanned.
 *
 * @param[in]   host    Host to check access to.
 * @param[in]   addr    Pointer to address so a hostname isn't resolved multiple
 *                      times.
 * @param[in]   hosts_allow   Hosts whitelist.
 * @param[in]   hosts_deny    Hosts blacklist.
 *
 * @return 1 if host authorized, 0 otherwise.
 */
static int
host_authorized (const openvas_host_t *host, const struct in6_addr *addr,
                 const openvas_hosts_t *hosts_allow,
                 const openvas_hosts_t *hosts_deny)
{
  /* Check Hosts Access. */
  if (host == NULL)
    return 0;

  if (hosts_deny && openvas_host_in_hosts (host, addr, hosts_deny))
    return 0;
  if (hosts_allow && !openvas_host_in_hosts (host, addr, hosts_allow))
    return 0;

  return 1;
}

/*
 * Applies the source_iface scanner preference, if allowed by ifaces_allow and
 * ifaces_deny preferences.
 *
 * @return 0 if source_iface preference applied or not found, -1 if
 * unauthorized value, -2 if iface can't be used.
 */
static int
838
apply_source_iface_preference (int soc)
839
{
840
  const char *source_iface = prefs_get ("source_iface");
841 842 843 844 845
  int ret;

  if (source_iface == NULL)
    return 0;

846
  ret = iface_authorized (source_iface);
847 848 849 850
  if (ret == -1)
    {
      gchar *msg = g_strdup_printf ("Unauthorized source interface: %s",
                                    source_iface);
851
      log_write ("source_iface: Unauthorized source interface %s.",
852
                 source_iface);
853
      error_message_to_client (soc, msg, NULL, NULL);
854 855 856 857 858 859 860 861 862 863

      g_free (msg);
      return -1;
    }
  else if (ret == -2)
    {
      gchar *msg = g_strdup_printf ("Unauthorized source interface: %s"
                                    " (system-wide restriction.)",
                                    source_iface);
      log_write ("source_iface: Unauthorized source interface %s."
864
                 " (sys_* preference restriction.)",
865
                 source_iface);
866
      error_message_to_client (soc, msg, NULL, NULL);
867 868 869 870 871 872 873 874 875

      g_free (msg);
      return -1;
    }

  if (openvas_source_iface_init (source_iface))
    {
      gchar *msg = g_strdup_printf ("Erroneous source interface: %s",
                                    source_iface);
876 877
      log_write ("source_iface: Error with %s interface.", source_iface);
      error_message_to_client (soc, msg, NULL, NULL);
878 879 880 881 882 883 884 885 886

      g_free (msg);
      return -2;
    }
  else
    {
      char *ipstr, *ip6str;
      ipstr = openvas_source_addr_str ();
      ip6str = openvas_source_addr6_str ();
887
      log_write ("source_iface: Using %s (%s / %s).", source_iface,
888 889 890 891 892 893 894
                 ipstr, ip6str);

      g_free (ipstr);
      g_free (ip6str);
      return 0;
    }
}
895

896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917
static int
check_kb_access (int soc)
{
  int rc;
  kb_t kb;

  rc = kb_new (&kb, prefs_get ("kb_location"));
  if (rc)
      report_kb_failure (soc, rc);
  else
    kb_delete (kb);

  return rc;
}

static void
handle_scan_stop_signal ()
{
  pluginlaunch_stop ();
  global_scan_stop = 1;
}

918 919 920
/**
 * @brief Attack a whole network.
 */
921
void
922
attack_network (struct arglist *globals, kb_t *network_kb)
923
{
924
  int max_hosts = 0, max_checks;
925
  int num_tested = 0;
926
  const char *hostlist;
927 928 929
  openvas_hosts_t *hosts, *hosts_allow, *hosts_deny;
  openvas_hosts_t *sys_hosts_allow, *sys_hosts_deny;
  openvas_host_t *host;
930 931 932 933 934 935 936
  int global_socket = -1;
  struct arglist *plugins = NULL;
  plugins_scheduler_t sched;
  int fork_retries = 0;
  GHashTable *files;
  struct timeval then, now;

937 938 939
  const gchar *network_targets, *port_range;
  gboolean network_phase = FALSE;
  gboolean do_network_scan = FALSE;
940 941 942

  gettimeofday (&then, NULL);

943 944 945 946
  if (prefs_get_bool ("network_scan"))
    do_network_scan = TRUE;
  else
    do_network_scan = FALSE;
947

948
  network_targets = prefs_get ("network_targets");
949 950
  if (network_targets != NULL)
    arg_add_value (globals, "network_targets", ARG_STRING,
951 952
                   (char *) network_targets);

953 954
  if (do_network_scan)
    {
955 956 957 958
      enum net_scan_status nss;

      nss = network_scan_status (globals);
      switch (nss)
959
        {
960 961 962 963 964 965 966 967 968 969 970 971 972
          case NSS_DONE:
            network_phase = FALSE;
            break;

          case NSS_BUSY:
            network_phase = TRUE;
            break;

          default:
            arg_add_value (globals, "network_scan_status", ARG_STRING,
                           "busy");
            network_phase = TRUE;
            break;
973 974
        }
    }
975 976
  else
    network_kb = NULL;
977 978 979

  num_tested = 0;

980
  global_socket = arg_get_value_int (globals, "global_socket");
981

982 983 984 985
  plugins = global_plugins;

  if (check_kb_access(global_socket))
      return;
986 987

  /* Init and check Target List */
988
  hostlist = prefs_get ("TARGET");
989 990
  if (hostlist == NULL)
    {
991 992
      error_message_to_client (global_socket, "Missing target hosts", NULL,
                               NULL);
993
      return;
994 995
    }

996
  /* Verify the port range is a valid one */
997
  port_range = prefs_get ("port_range");
998
  if (validate_port_range (port_range))
999
    {
1000 1001
      error_message_to_client (global_socket, "Invalid port range", NULL,
                               port_range);
1002
      return;
1003 1004 1005
    }

  /* Initialize the attack. */
1006
  sched = plugins_scheduler_init (plugins,
1007
    prefs_get_bool ("auto_enable_dependencies"), network_phase);
1008

1009 1010
  max_hosts = get_max_hosts_number ();
  max_checks = get_max_checks_number ();
1011 1012 1013 1014 1015

  if (network_phase)
    {
      if (network_targets == NULL)
        {
1016
          log_write ("WARNING: In network phase, but without targets! Stopping.");
1017
          host = NULL;
1018 1019 1020
        }
      else
        {
1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
          int rc;

          log_write ("Start a new scan. Target(s) : %s, "
                     "in network phase with target %s",
                     hostlist, network_targets);

          rc = kb_new (network_kb, prefs_get ("kb_location"));
          if (rc)
            {
              report_kb_failure (global_socket, rc);
              host = NULL;
            }
          else
            kb_lnk_reset (*network_kb);
1035 1036 1037 1038
        }
    }
  else
    {
1039 1040
      log_write ("Starts a new scan. Target(s) : %s, with max_hosts = %d and "
                 "max_checks = %d", hostlist, max_hosts, max_checks);
1041 1042
    }

1043 1044
  hosts = openvas_hosts_new (hostlist);
  /* Apply Hosts preferences. */
1045
  apply_hosts_preferences (hosts);
1046

1047
  /* Don't start if the provided interface is unauthorized. */
1048
  if (apply_source_iface_preference (global_socket) != 0)
1049
    {
1050
      openvas_hosts_free (hosts);
1051 1052
      error_message_to_client
       (global_socket, "Interface not authorized for scanning", NULL, NULL);
1053
      return;
1054
    }
1055
  /* hosts_allow/deny lists. */
1056 1057
  hosts_allow = openvas_hosts_new (prefs_get ("hosts_allow"));
  hosts_deny = openvas_hosts_new (prefs_get ("hosts_deny"));
1058
  /* sys_* preferences, which can't be overriden by the client. */
1059 1060
  sys_hosts_allow = openvas_hosts_new (prefs_get ("sys_hosts_allow"));
  sys_hosts_deny = openvas_hosts_new (prefs_get ("sys_hosts_deny"));
1061 1062
  host = openvas_hosts_next (hosts);
  if (host == NULL)
1063 1064 1065 1066 1067
    goto stop;
  hosts_init (global_socket, max_hosts);
  /*
   * Start the attack !
   */
1068
  openvas_signal (SIGUSR1, handle_scan_stop_signal);
1069
  while (host && !scan_is_stopped ())
1070 1071
    {
      int pid;
1072 1073
      char *hostname;
      struct in6_addr host_ip;
1074

1075 1076 1077
      hostname = openvas_host_reverse_lookup (host);
      if (!hostname)
        hostname = openvas_host_value_str (host);
1078
      if (openvas_host_get_addr6 (host, &host_ip) == -1)
1079
        {
1080 1081
          log_write ("Couldn't resolve target %s", hostname);
          error_message_to_client (global_socket, "Couldn't resolve hostname.",
1082 1083 1084 1085
                                   hostname, NULL);
          g_free (hostname);
          host = openvas_hosts_next (hosts);
          continue;
1086 1087 1088
        }

      /* Do we have the right to test this host ? */
1089
      if (!host_authorized (host, &host_ip, hosts_allow, hosts_deny))
1090
        {
1091
          error_message_to_client (global_socket, "Host access denied.",
1092 1093 1094 1095 1096 1097
                                   hostname, NULL);
          log_write ("Host %s access denied.", hostname);
        }
      else if (!host_authorized (host, &host_ip, sys_hosts_allow,
                                 sys_hosts_deny))
        {
1098 1099 1100
          error_message_to_client
           (global_socket, "Host access denied (system-wide restriction.)",
            hostname, NULL);
1101 1102
          log_write ("Host %s access denied (sys_* preference restriction.)",
                     hostname);
1103 1104
        }
      else
1105
        {
1106
          struct attack_start_args args;
1107
          char *MAC = NULL, *txt_ip;
1108
          int mac_err = -1;
1109
          int soc[2];
1110

1111
          if (prefs_get_bool ("use_mac_addr") && v6_is_local_ip (&host_ip))
1112 1113 1114 1115 1116
            {
              mac_err = v6_get_mac_addr (&host_ip, &MAC);
              if (mac_err > 0)
                {
                  /* remote host is down */
1117 1118
                  g_free (hostname);
                  host = openvas_hosts_next (hosts);
1119 1120 1121 1122
                  continue;
                }
            }

1123 1124 1125
          if (socketpair (AF_UNIX, SOCK_STREAM, 0, soc) < 0)
            goto scan_stop;
          if (hosts_new (globals, hostname, soc[1]) < 0)
1126 1127
            goto scan_stop;

1128 1129 1130 1131 1132 1133 1134 1135
          if (scan_is_stopped ())
            {
              close (soc[0]);
              close (soc[1]);
              g_free (MAC);
              g_free (hostname);
              continue;
            }
1136 1137
          args.globals = globals;
          memcpy (&args.hostip, &host_ip, sizeof (struct in6_addr));
1138
          args.fqdn = hostname;
1139 1140
          args.host_mac_addr = MAC;
          args.sched = sched;
1141 1142 1143
          args.thread_socket = soc[0];
          args.parent_socket = soc[1];
          args.net_kb = network_kb;
1144 1145 1146

        forkagain:
          pid = create_process ((process_func_t) attack_start, &args);
1147 1148
          /* Close child process' socket. */
          close (args.thread_socket);
1149 1150 1151 1152 1153 1154
          if (pid < 0)
            {
              fork_retries++;
              if (fork_retries > MAX_FORK_RETRIES)
                {
                  /* Forking failed - we go to the wait queue. */
1155
                  log_write ("fork() failed - %s. %s won't be tested",
1156
                             strerror (errno), hostname);
1157 1158
                  if (MAC)
                    g_free (MAC);
1159 1160 1161
                  goto stop;
                }

1162 1163 1164
              log_write ("fork() failed - "
                         "sleeping %d seconds and trying again...",
                         fork_retries);
1165 1166 1167
              fork_sleep (fork_retries);
              goto forkagain;
            }
1168
          txt_ip = addr6_as_str (&args.hostip);
1169 1170
          hosts_set_pid (hostname, pid);
          if (network_phase)
1171
            log_write ("Testing %s (network level) [%d]",
1172
                       network_targets, pid);
1173
          else
1174 1175 1176
            log_write ("Testing %s (%s) [%d]", hostname, txt_ip, pid);
         g_free (txt_ip);
         g_free (MAC);
1177 1178 1179 1180 1181 1182
        }

      num_tested++;

      if (network_phase)
        {
1183
          host = NULL;
1184
          arg_set_value (globals, "network_scan_status", "done");
1185 1186 1187
        }
      else
        {
1188 1189
          g_free (hostname);
          host = openvas_hosts_next (hosts);
1190 1191 1192 1193 1194 1195 1196 1197
        }
    }

  /* Every host is being tested... We have to wait for the processes
   * to terminate. */
  while (hosts_read (globals) == 0)
    ;

1198
  log_write ("Test complete");
1199 1200 1201 1202 1203

scan_stop:
  /* Free the memory used by the files uploaded by the user, if any. */
  files = arg_get_value (globals, "files_translation");
  if (files)
1204
    g_hash_table_destroy (files);
1205 1206

stop:
Mati's avatar
Mati committed
1207

1208 1209 1210 1211 1212
  openvas_hosts_free (hosts);
  openvas_hosts_free (hosts_allow);
  openvas_hosts_free (hosts_deny);
  openvas_hosts_free (sys_hosts_allow);
  openvas_hosts_free (sys_hosts_deny);
1213 1214 1215 1216

  plugins_scheduler_free (sched);

  gettimeofday (&now, NULL);
1217
  log_write ("Total time to scan all hosts : %ld seconds",
1218 1219
             now.tv_sec - then.tv_sec);

1220 1221
  if (do_network_scan && network_phase && !scan_is_stopped ())
    attack_network (globals, network_kb);
1222
}