OpenVAS Scanner  7.0.1~git
network.c
Go to the documentation of this file.
1 /* Portions Copyright (C) 2009-2019 Greenbone Networks GmbH
2  * Based on work Copyright (C) 1998 - 2002 Renaud Deraison
3  * SSL Support Copyright (C) 2001 Michel Arboi
4  *
5  * SPDX-License-Identifier: GPL-2.0-or-later
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20  */
21 
27 #include "../nasl/nasl_debug.h" /* for nasl_*_filename */
28 
29 #include <arpa/inet.h> /* for inet_pton */
30 #include <errno.h>
31 #include <fcntl.h>
32 #include <glib.h>
33 #include <gnutls/gnutls.h>
34 #include <gnutls/x509.h>
35 #include <gvm/base/logging.h>
36 #include <gvm/base/networking.h>
37 #include <gvm/base/prefs.h>
38 #include <gvm/util/kb.h> /* for kb_item_get_str() */
39 #include <gvm/util/serverutils.h> /* for load_gnutls_file */
40 #include <signal.h>
41 #include <stdarg.h>
42 #include <stdio.h> /* for FILE */
43 #include <stdlib.h>
44 #include <string.h>
45 #include <sys/time.h> /* for gettimeofday */
46 #include <sys/types.h>
47 #include <unistd.h>
48 
49 #ifdef __FreeBSD__
50 #include <netinet/in.h>
51 #define s6_addr32 __u6_addr.__u6_addr32
52 #endif
53 
54 #include "network.h" /* for socket_close() */
55 #include "plugutils.h"
56 #include "support.h"
57 
58 #define TIMEOUT 20
59 
60 #ifndef INADDR_NONE
61 #define INADDR_NONE 0xffffffff
62 #endif
63 
64 #undef G_LOG_DOMAIN
65 
68 #define G_LOG_DOMAIN "lib misc"
69 
70 /*----------------------------------------------------------------*
71  * Low-level connection management *
72  *----------------------------------------------------------------*/
73 
75 typedef struct
76 {
77  int fd;
78  /*
79  * "transport" layer code when stream is encapsultated. Negative transport
80  * signals a free descriptor.
81  */
83  char *priority;
84  int timeout;
86  int port;
87 
88  gnutls_session_t tls_session;
89  gnutls_certificate_credentials_t tls_cred;
91  pid_t pid;
93  char *buf;
94  int bufsz, bufcnt, bufptr;
95  int last_err;
97 
104 #define OPENVAS_FD_MAX 1024
105 #define OPENVAS_FD_OFF 1000000
106 
108 
113 {
114  struct csc_hook_s *next;
115  int (*fnc) (int fd);
116 };
117 
121 static struct csc_hook_s *csc_hooks;
122 
126 #define OPENVAS_STREAM(x) \
127  (((x - OPENVAS_FD_OFF) < OPENVAS_FD_MAX) && ((x - OPENVAS_FD_OFF) >= 0))
128 
132 #define OVAS_CONNECTION_FROM_FD(fd) (connections + ((fd) -OPENVAS_FD_OFF))
133 
137 static int
138 pid_perror (const char *error)
139 {
140  g_debug ("[%d] %s : %s", getpid (), error, strerror (errno));
141  return 0;
142 }
143 
144 int
146 {
148 
149  if (!OPENVAS_STREAM (fd))
150  {
151  errno = EINVAL;
152  return -1;
153  }
154 
155  p = OVAS_CONNECTION_FROM_FD (fd);
156  return p->last_err;
157 }
158 
162 static int
164 {
165  int i;
166 
167  for (i = 0; i < OPENVAS_FD_MAX; i++)
168  {
169  if (connections[i].pid == 0) /* Not used */
170  {
171  bzero (&(connections[i]), sizeof (connections[i]));
172  connections[i].pid = getpid ();
173  return i + OPENVAS_FD_OFF;
174  }
175  }
176  g_message ("[%d] %s:%d : Out of OpenVAS file descriptors", getpid (),
177  __FILE__, __LINE__);
178  errno = EMFILE;
179  return -1;
180 }
181 
182 static int
183 release_connection_fd (int fd, int already_closed)
184 {
186 
187  if (!OPENVAS_STREAM (fd))
188  {
189  errno = EINVAL;
190  return -1;
191  }
192  p = OVAS_CONNECTION_FROM_FD (fd);
193 
194  g_free (p->buf);
195  p->buf = 0;
196 
197  /* TLS FIXME: we should call gnutls_bye somewhere. OTOH, the OpenSSL
198  * equivalent SSL_shutdown wasn't called anywhere in the OpenVAS
199  * (libopenvas nor elsewhere) code either.
200  */
201 
202  /* So far, fd is always a socket. If this is changed in the future, this
203  * code shall be fixed. */
204  if (p->fd >= 0)
205  {
206  g_debug ("[%d] release_connection_fd: fd > 0 fd=%d", getpid (), p->fd);
207  if (shutdown (p->fd, 2) < 0)
208  {
209  /*
210  * It's not uncommon to see that one fail, since a lot of
211  * services close the connection before we ask them to
212  * (ie: http), so we don't show this error by default
213  */
214  pid_perror ("release_connection_fd: shutdown()");
215  }
216  if (!already_closed && socket_close (p->fd) < 0)
217  pid_perror ("release_connection_fd: close()");
218  }
219 
220  if (p->tls_session != NULL)
221  gnutls_deinit (p->tls_session);
222  if (p->tls_cred != NULL)
223  gnutls_certificate_free_credentials (p->tls_cred);
224 
225  g_free (p->priority);
226  p->priority = NULL;
227 
228  bzero (p, sizeof (*p));
229  p->transport = -1;
230  p->pid = 0;
231 
232  return 0;
233 }
234 
235 /* ******** Compatibility function ******** */
236 
243 int
244 openvas_register_connection (int soc, void *ssl,
245  gnutls_certificate_credentials_t certcred,
246  openvas_encaps_t encaps)
247 {
248  int fd;
250 
251  if ((fd = get_connection_fd ()) < 0)
252  return -1;
253  p = OVAS_CONNECTION_FROM_FD (fd);
254 
255  p->tls_session = ssl;
256  p->tls_cred = certcred;
257 
258  p->timeout = TIMEOUT; /* default value */
259  p->port = 0; /* just used for debug */
260  p->fd = soc;
261  p->transport = encaps;
262  p->priority = NULL;
263  p->last_err = 0;
264 
265  return fd;
266 }
267 
268 int
270 {
272  if (!OPENVAS_STREAM (fd))
273  {
274  errno = EINVAL;
275  return -1;
276  }
277 
278  p = connections + (fd - OPENVAS_FD_OFF);
279  /* Fixme: Code duplicated from release_connection_fd. Check usage
280  of this function make sure that TLS stuff is also released in
281  case it is used here. */
282  g_free (p->priority);
283  p->priority = NULL;
284  bzero (p, sizeof (*p));
285  p->transport = -1;
286  return 0;
287 }
288 
289 /*----------------------------------------------------------------*
290  * High-level connection management *
291  *----------------------------------------------------------------*/
292 
293 static int __port_closed;
294 
295 static int
296 unblock_socket (int soc)
297 {
298  int flags = fcntl (soc, F_GETFL, 0);
299  if (flags < 0)
300  {
301  pid_perror ("fcntl(F_GETFL)");
302  return -1;
303  }
304  if (fcntl (soc, F_SETFL, O_NONBLOCK | flags) < 0)
305  {
306  pid_perror ("fcntl(F_SETFL,O_NONBLOCK)");
307  return -1;
308  }
309  return 0;
310 }
311 
312 static int
313 block_socket (int soc)
314 {
315  int flags = fcntl (soc, F_GETFL, 0);
316  if (flags < 0)
317  {
318  pid_perror ("fcntl(F_GETFL)");
319  return -1;
320  }
321  if (fcntl (soc, F_SETFL, (~O_NONBLOCK) & flags) < 0)
322  {
323  pid_perror ("fcntl(F_SETFL,~O_NONBLOCK)");
324  return -1;
325  }
326  return 0;
327 }
328 
329 /*
330  * Initialize the SSL library (error strings and algorithms) and try
331  * to set the pseudo random generator to something less silly than the
332  * default value: 1 according to SVID 3, BSD 4.3, ISO 9899 :-(
333  */
334 
335 void
336 tlserror (char *txt, int err)
337 {
338  g_message ("[%d] %s: %s", getpid (), txt, gnutls_strerror (err));
339 }
340 
341 static void
342 log_message_gnutls (int level, const char *msg)
343 {
344  g_debug ("LEVEL %d: %s", level, msg);
345 }
346 
350 int
352 {
353  gnutls_global_set_log_level (2);
354  gnutls_global_set_log_function (log_message_gnutls);
355 
356  int ret = gnutls_global_init ();
357  if (ret < 0)
358  {
359  tlserror ("gnutls_global_init", ret);
360  return -1;
361  }
362 
363  return 0;
364 }
365 
366 int
368 {
369  openvas_connection *fp;
370 
371  if (!OPENVAS_STREAM (fd))
372  {
373  g_message ("[%d] openvas_get_socket_from_connection: bad fd <%d>",
374  getpid (), fd);
375  return fd;
376  }
377  fp = connections + (fd - OPENVAS_FD_OFF);
378  if (fp->transport <= 0)
379  {
380  g_message ("openvas_get_socket_from_connection: fd <%d> is closed", fd);
381  return -1;
382  }
383  return fp->fd;
384 }
385 
386 gnutls_session_t
388 {
389  openvas_connection *fp;
390 
391  if (!OPENVAS_STREAM (fd))
392  return NULL;
393 
394  fp = connections + (fd - OPENVAS_FD_OFF);
395  return fp->tls_session;
396 }
397 
403 static int
404 set_gnutls_protocol (gnutls_session_t session, openvas_encaps_t encaps,
405  const char *priority)
406 {
407  const char *priorities;
408  const char *errloc;
409  int err;
410 
411  switch (encaps)
412  {
414  priorities = "NORMAL:-VERS-TLS-ALL:+VERS-SSL3.0:+ARCFOUR-128:%COMPAT";
415  break;
417  priorities = "NORMAL:-VERS-TLS-ALL:+VERS-TLS1.0:+ARCFOUR-128:%COMPAT";
418  break;
420  priorities = "NORMAL:-VERS-TLS-ALL:+VERS-TLS1.1:+ARCFOUR-128:%COMPAT";
421  break;
423  priorities = "NORMAL:-VERS-TLS-ALL:+VERS-TLS1.2:+ARCFOUR-128:%COMPAT";
424  break;
425  case OPENVAS_ENCAPS_SSLv23: /* Compatibility mode */
426  priorities =
427  "NORMAL:-VERS-TLS-ALL:+VERS-TLS1.0:+VERS-SSL3.0:+ARCFOUR-128:%COMPAT";
428  break;
429  default:
430  g_debug ("*Bug* at %s:%d. Unknown transport %d", __FILE__, __LINE__,
431  encaps);
432  /* fallthrough */
434  priorities = priority;
435  break;
436  }
437 
438  if ((err = gnutls_priority_set_direct (session, priorities, &errloc)))
439  {
440  g_message ("[%d] setting session priorities '%.20s': %s", getpid (),
441  errloc, gnutls_strerror (err));
442  return -1;
443  }
444 
445  return 0;
446 }
447 
456 static int
457 load_cert_and_key (gnutls_certificate_credentials_t xcred, const char *cert,
458  const char *key, const char *passwd)
459 {
460  gnutls_x509_crt_t x509_crt = NULL;
461  gnutls_x509_privkey_t x509_key = NULL;
462  gnutls_datum_t data;
463  int ret;
464  int result = 0;
465 
466  if (load_gnutls_file (cert, &data))
467  {
468  g_message ("[%d] load_cert_and_key: Error loading cert file %s",
469  getpid (), cert);
470  result = -1;
471  goto cleanup;
472  }
473  ret = gnutls_x509_crt_init (&x509_crt);
474  if (ret < 0)
475  {
476  tlserror ("gnutls_x509_crt_init", ret);
477  /* x509_crt may be != NULL even if gnutls_x509_crt_init fails */
478  x509_crt = NULL;
479  result = -1;
480  goto cleanup;
481  }
482  ret = gnutls_x509_crt_import (x509_crt, &data, GNUTLS_X509_FMT_PEM);
483  if (ret < 0)
484  {
485  tlserror ("gnutls_x509_crt_import", ret);
486  result = -1;
487  goto cleanup;
488  }
489  unload_gnutls_file (&data);
490 
491  if (load_gnutls_file (key, &data))
492  {
493  g_message ("[%d] load_cert_and_key: Error loading key file %s", getpid (),
494  key);
495  result = -1;
496  goto cleanup;
497  }
498  ret = gnutls_x509_privkey_init (&x509_key);
499  if (ret < 0)
500  {
501  tlserror ("gnutls_x509_privkey_init", ret);
502  /* x509_key may be != NULL even if gnutls_x509_privkey_init fails */
503  x509_key = NULL;
504  result = -1;
505  goto cleanup;
506  }
507  if (passwd)
508  {
509  ret = gnutls_x509_privkey_import_pkcs8 (x509_key, &data,
510  GNUTLS_X509_FMT_PEM, passwd, 0);
511  if (ret < 0)
512  {
513  tlserror ("gnutls_x509_privkey_import_pkcs8", ret);
514  result = -1;
515  goto cleanup;
516  }
517  }
518  else
519  {
520  ret = gnutls_x509_privkey_import (x509_key, &data, GNUTLS_X509_FMT_PEM);
521  if (ret < 0)
522  {
523  tlserror ("gnutls_x509_privkey_import", ret);
524  result = -1;
525  goto cleanup;
526  }
527  }
528  unload_gnutls_file (&data);
529 
530  ret = gnutls_certificate_set_x509_key (xcred, &x509_crt, 1, x509_key);
531  if (ret < 0)
532  {
533  tlserror ("gnutls_certificate_set_x509_key", ret);
534  result = -1;
535  goto cleanup;
536  }
537 
538 cleanup:
539 
540  if (x509_crt)
541  gnutls_x509_crt_deinit (x509_crt);
542  if (x509_key)
543  gnutls_x509_privkey_deinit (x509_key);
544 
545  return result;
546 }
547 
548 static int
549 is_ip_address (const char *str)
550 {
551  struct sockaddr_in sa;
552  struct sockaddr_in6 sa6;
553 
554  if (inet_pton (AF_INET, str, &(sa.sin_addr)) == 1)
555  return 1;
556 
557  return inet_pton (AF_INET6, str, &(sa6.sin6_addr)) == 1;
558 }
559 
560 static int
561 open_SSL_connection (openvas_connection *fp, const char *cert, const char *key,
562  const char *passwd, const char *cafile,
563  const char *hostname)
564 {
565  int ret, err, d;
566  time_t tictac;
567  fd_set fdw, fdr;
568  struct timeval to;
569 
570  ret = gnutls_init (&(fp->tls_session), GNUTLS_CLIENT);
571  if (ret < 0)
572  {
573  tlserror ("gnutls_init", ret);
574  return -1;
575  }
576 
577  /* set_gnutls_protocol handles OPENVAS_ENCAPS_SSLv2 by falling back
578  * to OPENVAS_ENCAPS_SSLv23. However, this function
579  * (open_SSL_connection) is called only by open_stream_connection and
580  * open_stream_connection will exit with an error code if called with
581  * OPENVAS_ENCAPS_SSLv2, so it should never end up calling
582  * open_SSL_connection with OPENVAS_ENCAPS_SSLv2.
583  */
584  if (set_gnutls_protocol (fp->tls_session, fp->transport, fp->priority) < 0)
585  return -1;
586 
587  if (hostname && !is_ip_address (hostname))
588  gnutls_server_name_set (fp->tls_session, GNUTLS_NAME_DNS, hostname,
589  strlen (hostname));
590 
591  ret = gnutls_certificate_allocate_credentials (&(fp->tls_cred));
592  if (ret < 0)
593  {
594  tlserror ("gnutls_certificate_allocate_credentials", ret);
595  return -1;
596  }
597  ret = gnutls_credentials_set (fp->tls_session, GNUTLS_CRD_CERTIFICATE,
598  fp->tls_cred);
599  if (ret < 0)
600  {
601  tlserror ("gnutls_credentials_set", ret);
602  return -1;
603  }
604 
605  if (cert != NULL && key != NULL)
606  {
607  if (load_cert_and_key (fp->tls_cred, cert, key, passwd) < 0)
608  return -1;
609  }
610 
611  if (cafile != NULL)
612  {
613  ret = gnutls_certificate_set_x509_trust_file (fp->tls_cred, cafile,
614  GNUTLS_X509_FMT_PEM);
615  if (ret < 0)
616  {
617  tlserror ("gnutls_certificate_set_x509_trust_file", ret);
618  return -1;
619  }
620  }
621 
622  unblock_socket (fp->fd);
623 
624  gnutls_transport_set_ptr (fp->tls_session,
625  (gnutls_transport_ptr_t) GSIZE_TO_POINTER (fp->fd));
626 
627  tictac = time (NULL);
628 
629  for (;;)
630  {
631  err = gnutls_handshake (fp->tls_session);
632 
633  if (err == 0)
634  return 1;
635 
636  if (err != GNUTLS_E_INTERRUPTED && err != GNUTLS_E_AGAIN
637  && err != GNUTLS_E_WARNING_ALERT_RECEIVED)
638  {
639  g_debug ("[%d] gnutls_handshake: %s", getpid (),
640  gnutls_strerror (err));
641  return -1;
642  }
643 
644  FD_ZERO (&fdr);
645  FD_SET (fp->fd, &fdr);
646  FD_ZERO (&fdw);
647  FD_SET (fp->fd, &fdw);
648 
649  do
650  {
651  d = tictac + fp->timeout - time (NULL);
652  if (d <= 0)
653  {
654  fp->last_err = ETIMEDOUT;
655  return -1;
656  }
657  to.tv_sec = d;
658  to.tv_usec = 0;
659  errno = 0;
660  if ((ret = select (fp->fd + 1, &fdr, &fdw, NULL, &to)) <= 0)
661  pid_perror ("select");
662  }
663  while (ret < 0 && errno == EINTR);
664 
665  if (ret <= 0)
666  {
667  fp->last_err = ETIMEDOUT;
668  return -1;
669  }
670  }
671 }
672 
673 /*
674  * @brief Upgrade an ENCAPS_IP socket to an SSL/TLS encapsulated one.
675  *
676  * @param[in] fd Socket file descriptor.
677  * @param[in] transport Encapsulation type.
678  * @param[in] arg Script args.
679  *
680  * @return -1 if error, socket file descriptor value otherwise.
681  */
682 int
684  struct script_infos *args)
685 {
686  char *cert = NULL, *key = NULL, *passwd = NULL, *cafile = NULL;
687  char *hostname = NULL;
688  openvas_connection *fp;
689  kb_t kb;
690  char buf[1024];
691 
692  if (!fd_is_stream (fd))
693  {
694  g_message ("Socket %d is not stream", fd);
695  return -1;
696  }
697  fp = OVAS_CONNECTION_FROM_FD (fd);
698  kb = plug_get_kb (args);
699  cert = kb_item_get_str (kb, "SSL/cert");
700  key = kb_item_get_str (kb, "SSL/key");
701  passwd = kb_item_get_str (kb, "SSL/password");
702  cafile = kb_item_get_str (kb, "SSL/CA");
703  snprintf (buf, sizeof (buf), "Host/SNI/%d/force_disable", fp->port);
704  if (kb_item_get_int (kb, buf) <= 0)
705  hostname = plug_get_host_fqdn (args);
706 
707  fp->transport = transport;
708  fp->priority = NULL;
709  if (open_SSL_connection (fp, cert, key, passwd, cafile, hostname) <= 0)
710  {
711  g_free (hostname);
712  g_message ("Function socket_negotiate_ssl called from %s: "
713  "SSL/TLS connection failed.",
715  release_connection_fd (fd, 0);
716  return -1;
717  }
718  g_free (hostname);
719  return fd;
720 }
721 
722 /*
723  * @brief Get the peer's certificate from an SSL/TLS encapsulated connection.
724  *
725  * @param[in] fd Socket file descriptor.
726  * @param[out] cert Memory pointer to fill cert pointer.
727  * @param[out] certlen Size of cert.
728  */
729 void
730 socket_get_cert (int fd, void **cert, int *certlen)
731 {
732  gnutls_session_t session;
733  const gnutls_datum_t *cert_list;
734  unsigned int cert_list_len = 0;
735 
736  if (!cert || !certlen)
737  return;
738  if (!fd_is_stream (fd))
739  {
740  g_message ("Socket %d is not stream", fd);
741  return;
742  }
744  if (!session)
745  {
746  g_message ("Socket %d is not SSL/TLS encapsulated", fd);
747  return;
748  }
749  if (gnutls_certificate_type_get (session) != GNUTLS_CRT_X509)
750  return;
751  cert_list = gnutls_certificate_get_peers (session, &cert_list_len);
752  if (cert_list_len == 0)
753  return;
754  *certlen = cert_list[0].size;
755  *cert = g_memdup (cert_list[0].data, *certlen);
756 }
757 
758 /*
759  * @brief Get the TLS version of a connection.
760  *
761  * @param[in] fd Socket file descriptor.
762  *
763  * @return OPENVAS_ENCAPS value if valid session and success, -1 if error.
764  */
765 int
767 {
768  gnutls_session_t session;
769  gnutls_protocol_t version;
770 
771  if (!fd_is_stream (fd))
772  {
773  g_message ("Socket %d is not stream", fd);
774  return -1;
775  }
777  if (!session)
778  {
779  g_message ("Socket %d is not SSL/TLS encapsulated", fd);
780  return -1;
781  }
782 
783  version = gnutls_protocol_get_version (session);
784  switch (version)
785  {
786  case GNUTLS_SSL3:
787  return OPENVAS_ENCAPS_SSLv3;
788  case GNUTLS_TLS1:
789  return OPENVAS_ENCAPS_TLSv1;
790  case GNUTLS_TLS1_1:
791  return OPENVAS_ENCAPS_TLSv11;
792  case GNUTLS_TLS1_2:
793  return OPENVAS_ENCAPS_TLSv12;
794  default:
795  return -1;
796  }
797 }
798 
799 /*
800  * @brief Get the session ID from an SSL/TLS encapsulated connection.
801  *
802  * @param[in] fd Socket file descriptor.
803  * @param[out] sid Pointer where to store Session ID pointer.
804  * @param[out] ssize Size of session id buffer.
805  */
806 void
807 socket_get_ssl_session_id (int fd, void **sid, size_t *ssize)
808 {
809  gnutls_session_t session;
810  void *tmp;
811  *ssize = GNUTLS_MAX_SESSION_ID;
812  int ret;
813 
814  if (!sid)
815  return;
816  if (!fd_is_stream (fd))
817  {
818  g_message ("Socket %d is not stream", fd);
819  return;
820  }
822  if (!session)
823  {
824  g_message ("Socket %d is not SSL/TLS encapsulated", fd);
825  return;
826  }
827  tmp = g_malloc0 (*ssize);
828  ret = gnutls_session_get_id (session, tmp, ssize);
829  if (ret == GNUTLS_E_SUCCESS)
830  *sid = tmp;
831  else
832  {
833  g_free (tmp);
834  *ssize = 0;
835  tlserror ("gnutls_session_id", ret);
836  }
837 }
838 
839 /*
840  * @brief Get the cipher suite used by a SSL/TLS connection.
841  *
842  * @param[in] fd Socket file descriptor.
843  *
844  * @return Cipher Suite ID, -1 if error.
845  */
846 int
848 {
849  gnutls_session_t session;
850  gnutls_kx_algorithm_t kx, kx2;
851  gnutls_cipher_algorithm_t cipher, cipher2;
852  gnutls_mac_algorithm_t mac, mac2;
853  size_t idx = 0;
854  unsigned char cs_id[2];
855 
856  if (!fd_is_stream (fd))
857  {
858  g_message ("Socket %d is not stream", fd);
859  return -1;
860  }
862  if (!session)
863  {
864  g_message ("Socket %d is not SSL/TLS encapsulated", fd);
865  return -1;
866  }
867 
868  kx = gnutls_kx_get (session);
869  cipher = gnutls_cipher_get (session);
870  mac = gnutls_mac_get (session);
871  while (
872  gnutls_cipher_suite_info (idx, (void *) cs_id, &kx2, &cipher2, &mac2, NULL))
873  {
874  if (kx == kx2 && cipher == cipher2 && mac == mac2)
875  return cs_id[0] + cs_id[1];
876  idx++;
877  }
878  return -1;
879 }
880 
881 /* Extended version of open_stream_connection to allow passing a
882  priority string.
883 
884  ABI_BREAK_NOTE: Merge this with open_stream_connection. */
885 int
886 open_stream_connection_ext (struct script_infos *args, unsigned int port,
887  int transport, int timeout, const char *priority)
888 {
889  int fd;
890  openvas_connection *fp;
891  char *cert = NULL;
892  char *key = NULL;
893  char *passwd = NULL;
894  char *cafile = NULL;
895  char *hostname = NULL;
896 
897  if (!priority)
898  priority = ""; /* To us an empty string is equivalent to NULL. */
899 
900  g_debug ("[%d] open_stream_connection: TCP:%d transport:%d timeout:%d "
901  " priority: '%s'",
902  getpid (), port, transport, timeout, priority);
903 
904  if (timeout == -2)
905  timeout = TIMEOUT;
906 
907  switch (transport)
908  {
909  case OPENVAS_ENCAPS_IP:
910 
918  break;
919 
920  default:
921  g_message ("open_stream_connection_ext(): unsupported transport"
922  " layer %d passed by %s",
923  transport, args->name);
924  errno = EINVAL;
925  return -1;
926  }
927 
928  if ((fd = get_connection_fd ()) < 0)
929  return -1;
930  fp = OVAS_CONNECTION_FROM_FD (fd);
931 
932  fp->transport = transport;
933  g_free (fp->priority);
934  if (*priority)
935  fp->priority = g_strdup (priority);
936  else
937  fp->priority = NULL;
938  fp->timeout = timeout;
939  fp->port = port;
940  fp->last_err = 0;
941 
942  fp->fd = open_sock_tcp (args, port, timeout);
943  if (fp->fd < 0)
944  goto failed;
945 
946  kb_t kb = plug_get_kb (args);
947  switch (transport)
948  {
949  int ret;
950  char buf[1024];
951 
952  case OPENVAS_ENCAPS_IP:
953  break;
960  cert = kb_item_get_str (kb, "SSL/cert");
961  key = kb_item_get_str (kb, "SSL/key");
962  passwd = kb_item_get_str (kb, "SSL/password");
963 
964  cafile = kb_item_get_str (kb, "SSL/CA");
965 
966  /* fall through */
967 
969  /* We do not need a client certificate in this case */
970  snprintf (buf, sizeof (buf), "Host/SNI/%d/force_disable", fp->port);
971  if (kb_item_get_int (kb, buf) <= 0)
972  hostname = plug_get_host_fqdn (args);
973  ret = open_SSL_connection (fp, cert, key, passwd, cafile, hostname);
974  g_free (hostname);
975  g_free (cert);
976  g_free (key);
977  g_free (passwd);
978  g_free (cafile);
979  if (ret <= 0)
980  goto failed;
981  break;
982  }
983 
984  return fd;
985 
986 failed:
987  release_connection_fd (fd, 0);
988  return -1;
989 }
990 
991 int
992 open_stream_connection (struct script_infos *args, unsigned int port,
993  int transport, int timeout)
994 {
995  return open_stream_connection_ext (args, port, transport, timeout,
996  "NORMAL:+ARCFOUR-128:%COMPAT");
997 }
998 
999 /* Same as open_stream_auto_encaps but allows to force auto detection
1000  of the protocols if FORCE is true. */
1001 int
1002 open_stream_auto_encaps_ext (struct script_infos *args, unsigned int port,
1003  int timeout, int force)
1004 {
1005  int fd, transport;
1006 
1007  if (force)
1008  {
1009  /* Try SSL/TLS first */
1010  transport = OPENVAS_ENCAPS_TLScustom;
1011  fd = open_stream_connection (args, port, transport, timeout);
1012  if (fd < 0)
1013  {
1014  transport = OPENVAS_ENCAPS_IP;
1015  fd = open_stream_connection (args, port, OPENVAS_ENCAPS_IP, timeout);
1016  if (fd < 0)
1017  return -1;
1018  }
1019  /* Store that encapsulation mode in the KB. */
1020  plug_set_port_transport (args, port, transport);
1021  return fd;
1022  }
1023  else
1024  {
1025  transport = plug_get_port_transport (args, port);
1026  fd = open_stream_connection (args, port, transport, timeout);
1027  return fd;
1028  }
1029  /*NOTREACHED*/
1030 }
1031 
1032 int
1033 stream_set_timeout (int fd, int timeout)
1034 {
1035  int old;
1036  openvas_connection *fp;
1037  if (!OPENVAS_STREAM (fd))
1038  {
1039  errno = EINVAL;
1040  return 0;
1041  }
1042  fp = OVAS_CONNECTION_FROM_FD (fd);
1043  old = fp->timeout;
1044  fp->timeout = timeout;
1045  return old;
1046 }
1047 
1048 static int
1049 read_stream_connection_unbuffered (int fd, void *buf0, int min_len, int max_len)
1050 {
1051  int ret, realfd, trp, t, select_status;
1052  int total = 0, flag = 0, timeout = TIMEOUT, waitall = 0;
1053  unsigned char *buf = (unsigned char *) buf0;
1054  openvas_connection *fp = NULL;
1055  fd_set fdr, fdw;
1056  struct timeval tv;
1057  time_t now, then;
1058 
1059  if (OPENVAS_STREAM (fd))
1060  {
1061  fp = OVAS_CONNECTION_FROM_FD (fd);
1062  trp = fp->transport;
1063  realfd = fp->fd;
1064  fp->last_err = 0;
1065  if (fp->timeout != -2)
1066  timeout = fp->timeout;
1067  }
1068  else
1069  {
1070  trp = OPENVAS_ENCAPS_IP;
1071  if (fd < 0 || fd > 1024)
1072  {
1073  errno = EBADF;
1074  return -1;
1075  }
1076  realfd = fd;
1077  }
1078 
1079 #ifndef INCR_TIMEOUT
1080 #define INCR_TIMEOUT 1
1081 #endif
1082 
1083  if (min_len == max_len || timeout <= 0)
1084  waitall = MSG_WAITALL;
1085  if (trp == OPENVAS_ENCAPS_IP)
1086  {
1087  for (t = 0; total < max_len && (timeout <= 0 || t < timeout);)
1088  {
1089  tv.tv_sec = INCR_TIMEOUT; /* Not timeout! */
1090  tv.tv_usec = 0;
1091  FD_ZERO (&fdr);
1092  FD_SET (realfd, &fdr);
1093  if (select (realfd + 1, &fdr, NULL, NULL, timeout > 0 ? &tv : NULL)
1094  <= 0)
1095  {
1096  t += INCR_TIMEOUT;
1097  /* Try to be smart */
1098  if (total > 0 && flag)
1099  return total;
1100  else if (total >= min_len)
1101  flag++;
1102  }
1103  else
1104  {
1105  errno = 0;
1106  ret = recv (realfd, buf + total, max_len - total, waitall);
1107  if (ret < 0)
1108  if (errno != EINTR)
1109  {
1110  return total;
1111  }
1112  else
1113  ret = 0;
1114  else if (ret == 0) /* EOF */
1115  {
1116  return total;
1117  }
1118  /*ret > 0 */
1119  total += ret;
1120  if (min_len > 0 && total >= min_len)
1121  return total;
1122  flag = 0;
1123  }
1124  }
1125  return total;
1126  }
1127 
1128  switch (trp)
1129  {
1130  /* OPENVAS_ENCAPS_IP was treated before with the non-OpenVAS fd */
1131  case OPENVAS_ENCAPS_SSLv2:
1132  case OPENVAS_ENCAPS_SSLv23:
1133  case OPENVAS_ENCAPS_SSLv3:
1134  case OPENVAS_ENCAPS_TLSv1:
1135  case OPENVAS_ENCAPS_TLSv11:
1136  case OPENVAS_ENCAPS_TLSv12:
1138  if (getpid () != fp->pid)
1139  {
1140  g_debug ("PID %d tries to use a SSL/TLS connection established "
1141  "by PID %d\n",
1142  getpid (), fp->pid);
1143  errno = EINVAL;
1144  return -1;
1145  }
1146 
1147  then = time (NULL);
1148  for (t = 0; timeout <= 0 || t < timeout; t = now - then)
1149  {
1150  now = time (NULL);
1151  tv.tv_sec = INCR_TIMEOUT;
1152  tv.tv_usec = 0;
1153  FD_ZERO (&fdr);
1154  FD_ZERO (&fdw);
1155  FD_SET (realfd, &fdr);
1156  FD_SET (realfd, &fdw);
1157 
1158  select_status = select (realfd + 1, &fdr, &fdw, NULL, &tv);
1159 
1160  if (select_status > 0)
1161  {
1162  /* TLS FIXME: handle rehandshake */
1163  ret = gnutls_record_recv (fp->tls_session, buf + total,
1164  max_len - total);
1165  if (ret > 0)
1166  {
1167  total += ret;
1168  if (total >= max_len)
1169  return total;
1170  }
1171  else if (ret != GNUTLS_E_INTERRUPTED && ret != GNUTLS_E_AGAIN)
1172  {
1173  /* This branch also handles the case where ret == 0,
1174  * i.e. that the connection has been closed. This is
1175  * for compatibility with the old OpenSSL based openvas
1176  * code which treated SSL_ERROR_ZERO_RETURN as an
1177  * error too.
1178  */
1179  if (ret < 0)
1180  pid_perror ("gnutls_record_recv");
1181  else
1182  g_debug ("gnutls_record_recv[%d]: EOF\n", getpid ());
1183  fp->last_err = EPIPE;
1184  return total;
1185  }
1186  }
1187 
1188  if (min_len > 0 && total >= min_len)
1189  return total;
1190  }
1191  if (t >= timeout)
1192  fp->last_err = ETIMEDOUT;
1193  return total;
1194 
1195  default:
1196  if (fp->transport || fp->fd != 0)
1197  g_message ("Function %s called from %s: "
1198  "Severe bug! Unhandled transport layer %d (fd=%d).",
1200  fp->transport, fd);
1201  else
1202  g_message ("read_stream_connection_unbuffered: "
1203  "fd=%d is closed",
1204  fd);
1205  errno = EINVAL;
1206  return -1;
1207  }
1208  /*NOTREACHED*/
1209 }
1210 
1211 int
1212 read_stream_connection_min (int fd, void *buf0, int min_len, int max_len)
1213 {
1214  openvas_connection *fp;
1215 
1216  if (OPENVAS_STREAM (fd))
1217  {
1218  fp = OVAS_CONNECTION_FROM_FD (fd);
1219  if (fp->buf != NULL)
1220  {
1221  int l1, l2;
1222 
1223  if (max_len == 1)
1224  min_len = 1; /* avoid "magic read" later */
1225  l2 = max_len > fp->bufcnt ? fp->bufcnt : max_len;
1226  if (l2 > 0)
1227  {
1228  memcpy (buf0, fp->buf + fp->bufptr, l2);
1229  fp->bufcnt -= l2;
1230  if (fp->bufcnt == 0)
1231  {
1232  fp->bufptr = 0;
1233  fp->buf[0] = '\0'; /* debug */
1234  }
1235  else
1236  fp->bufptr += l2;
1237  if (l2 >= min_len || l2 >= max_len)
1238  return l2;
1239  max_len -= l2;
1240  min_len -= l2;
1241  }
1242  if (min_len > fp->bufsz)
1243  {
1244  l1 = read_stream_connection_unbuffered (fd, (char *) buf0 + l2,
1245  min_len, max_len);
1246  if (l1 > 0)
1247  return l1 + l2;
1248  else
1249  return l2;
1250  }
1251  /* Fill buffer */
1252  l1 =
1253  read_stream_connection_unbuffered (fd, fp->buf, min_len, fp->bufsz);
1254  if (l1 <= 0)
1255  return l2;
1256 
1257  fp->bufcnt = l1;
1258  l1 = max_len > fp->bufcnt ? fp->bufcnt : max_len;
1259  memcpy ((char *) buf0 + l2, fp->buf + fp->bufptr, l1);
1260  fp->bufcnt -= l1;
1261  if (fp->bufcnt == 0)
1262  fp->bufptr = 0;
1263  else
1264  fp->bufptr += l1;
1265  return l1 + l2;
1266  }
1267  }
1268  return read_stream_connection_unbuffered (fd, buf0, min_len, max_len);
1269 }
1270 
1271 int
1272 read_stream_connection (int fd, void *buf0, int len)
1273 {
1274  return read_stream_connection_min (fd, buf0, -1, len);
1275 }
1276 
1277 static int
1278 write_stream_connection4 (int fd, void *buf0, int n, int i_opt)
1279 {
1280  int ret, count;
1281  unsigned char *buf = (unsigned char *) buf0;
1282  openvas_connection *fp;
1283  fd_set fdr, fdw;
1284  struct timeval tv;
1285  int e;
1286 
1287  if (!OPENVAS_STREAM (fd))
1288  {
1289  g_debug ("write_stream_connection: fd <%d> invalid\n", fd);
1290  errno = EINVAL;
1291  return -1;
1292  }
1293 
1294  fp = OVAS_CONNECTION_FROM_FD (fd);
1295  fp->last_err = 0;
1296 
1297  switch (fp->transport)
1298  {
1299  case OPENVAS_ENCAPS_IP:
1300  for (count = 0; count < n;)
1301  {
1302  ret = send (fp->fd, buf + count, n - count, i_opt);
1303 
1304  if (ret <= 0)
1305  {
1306  if (ret < 0)
1307  fp->last_err = errno;
1308  else
1309  fp->last_err = EPIPE;
1310  break;
1311  }
1312 
1313  count += ret;
1314  }
1315  break;
1316 
1317  case OPENVAS_ENCAPS_SSLv2:
1318  case OPENVAS_ENCAPS_SSLv23:
1319  case OPENVAS_ENCAPS_SSLv3:
1320  case OPENVAS_ENCAPS_TLSv1:
1321  case OPENVAS_ENCAPS_TLSv11:
1322  case OPENVAS_ENCAPS_TLSv12:
1324 
1325  /* i_opt ignored for SSL */
1326  for (count = 0; count < n;)
1327  {
1328  ret = gnutls_record_send (fp->tls_session, buf + count, n - count);
1329 
1330  if (ret > 0)
1331  {
1332  count += ret;
1333  }
1334  else if (ret != GNUTLS_E_INTERRUPTED && ret != GNUTLS_E_AGAIN)
1335  {
1336  /* This branch also handles the case where ret == 0,
1337  * i.e. that the connection has been closed. This is
1338  * for compatibility with the old openvas code which
1339  * treated SSL_ERROR_ZERO_RETURN as an error too.
1340  */
1341  if (ret < 0)
1342  pid_perror ("gnutls_record_send");
1343  else
1344  g_debug ("gnutls_record_send[%d]: EOF\n", getpid ());
1345  fp->last_err = EPIPE;
1346  break;
1347  }
1348 
1349  if (fp->timeout >= 0)
1350  tv.tv_sec = fp->timeout;
1351  else
1352  tv.tv_sec = TIMEOUT;
1353  tv.tv_usec = 0;
1354 
1355  do
1356  {
1357  errno = 0;
1358  FD_ZERO (&fdr);
1359  FD_ZERO (&fdw);
1360  FD_SET (fp->fd, &fdr);
1361  FD_SET (fp->fd, &fdw);
1362  e = select (fp->fd + 1, &fdr, &fdw, NULL, &tv);
1363  }
1364  while (e < 0 && errno == EINTR);
1365 
1366  if (e <= 0)
1367  {
1368  pid_perror ("select");
1369  fp->last_err = ETIMEDOUT;
1370  break;
1371  }
1372  }
1373  break;
1374 
1375  default:
1376  if (fp->transport || fp->fd != 0)
1377  g_message ("Function %s called from %s: "
1378  "Severe bug! Unhandled transport layer %d (fd=%d).",
1380  fp->transport, fd);
1381  else
1382  g_message ("read_stream_connection_unbuffered: fd=%d is "
1383  "closed",
1384  fd);
1385  errno = EINVAL;
1386  return -1;
1387  }
1388 
1389  if (count == 0 && n > 0)
1390  return -1;
1391  else
1392  return count;
1393 }
1394 
1395 int
1396 write_stream_connection (int fd, void *buf0, int n)
1397 {
1398  return write_stream_connection4 (fd, buf0, n, 0);
1399 }
1400 
1401 int
1402 nsend (int fd, void *data, int length, int i_opt)
1403 {
1404  int n = 0;
1405 
1406  if (OPENVAS_STREAM (fd))
1407  {
1408  if (connections[fd - OPENVAS_FD_OFF].fd < 0)
1409  g_message ("OpenVAS file descriptor %d closed ?!", fd);
1410  else
1411  return write_stream_connection4 (fd, data, length, i_opt);
1412  }
1413  /* Trying OS's send() */
1414  block_socket (fd); /* ??? */
1415  do
1416  {
1417  struct timeval tv = {0, 5};
1418  fd_set wr;
1419  int e;
1420 
1421  FD_ZERO (&wr);
1422  FD_SET (fd, &wr);
1423 
1424  errno = 0;
1425  e = select (fd + 1, NULL, &wr, NULL, &tv);
1426  if (e > 0)
1427  n = os_send (fd, data, length, i_opt);
1428  else if (e < 0 && errno == EINTR)
1429  continue;
1430  else
1431  break;
1432  }
1433  while (n <= 0 && errno == EINTR);
1434  if (n < 0)
1435  g_message ("[%d] nsend():send %s", getpid (), strerror (errno));
1436 
1437  return n;
1438 }
1439 
1440 int
1441 nrecv (int fd, void *data, int length, int i_opt)
1442 {
1443  int e;
1444  if (OPENVAS_STREAM (fd))
1445  {
1446  if (connections[fd - OPENVAS_FD_OFF].fd < 0)
1447  g_message ("OpenVAS file descriptor %d closed ?!", fd);
1448  else
1449  return read_stream_connection (fd, data, length);
1450  }
1451  /* Trying OS's recv()
1452  *
1453  * Do *NOT* use os_recv() here, as it will be blocking until the exact
1454  * amount of requested data arrives
1455  */
1456  block_socket (fd);
1457  do
1458  {
1459  e = recv (fd, data, length, i_opt);
1460  }
1461  while (e < 0 && errno == EINTR);
1462  return e;
1463 }
1464 
1478 void
1480 {
1481  struct csc_hook_s *hook;
1482 
1483  for (hook = csc_hooks; hook; hook = hook->next)
1484  if (hook->fnc == fnc)
1485  return; /* Already added. */
1486 
1487  hook = g_malloc0 (sizeof *hook);
1488  hook->fnc = fnc;
1489  hook->next = csc_hooks;
1490  csc_hooks = hook;
1491 }
1492 
1506 static int
1508 {
1509  struct csc_hook_s *hook;
1510 
1511  for (hook = csc_hooks; hook; hook = hook->next)
1512  if (hook->fnc && !hook->fnc (fd))
1513  return 0;
1514  return -1;
1515 }
1516 
1517 int
1519 {
1520  openvas_connection *fp;
1521  if (!OPENVAS_STREAM (fd))
1522  {
1523  errno = EINVAL;
1524  return -1;
1525  }
1526  fp = OVAS_CONNECTION_FROM_FD (fd);
1527  g_debug ("close_stream_connection TCP:%d (fd=%d)", fp->port, fd);
1528 
1529  if (!OPENVAS_STREAM (fd)) /* Will never happen if debug is on! */
1530  {
1531  if (fd < 0 || fd > 1024)
1532  {
1533  errno = EINVAL;
1534  return -1;
1535  }
1536  shutdown (fd, 2);
1537  return socket_close (fd);
1538  }
1539  if (!run_csc_hooks (fd))
1540  return release_connection_fd (fd, 1);
1541  else
1542  return release_connection_fd (fd, 0);
1543 }
1544 
1545 const char *
1547 {
1548  static char str[100];
1549  switch (code)
1550  {
1551  case OPENVAS_ENCAPS_AUTO:
1552  return "auto";
1553  case OPENVAS_ENCAPS_IP:
1554  return "IP";
1555  case OPENVAS_ENCAPS_SSLv2:
1556  return "SSLv2";
1557  case OPENVAS_ENCAPS_SSLv23:
1558  return "SSLv23";
1559  case OPENVAS_ENCAPS_SSLv3:
1560  return "SSLv3";
1561  case OPENVAS_ENCAPS_TLSv1:
1562  return "TLSv1";
1563  case OPENVAS_ENCAPS_TLSv11:
1564  return "TLSv11";
1565  case OPENVAS_ENCAPS_TLSv12:
1566  return "TLSv12";
1568  return "TLScustom";
1569  default:
1570  snprintf (str, sizeof (str), "[unknown transport layer - code %d (0x%x)]",
1571  code, code);
1572  return str;
1573  }
1574 }
1575 
1576 const char *
1578 {
1579  static char str[100];
1580  switch (code)
1581  {
1582  case OPENVAS_ENCAPS_IP:
1583  return "";
1584  case OPENVAS_ENCAPS_SSLv2:
1585  case OPENVAS_ENCAPS_SSLv23:
1586  case OPENVAS_ENCAPS_SSLv3:
1587  case OPENVAS_ENCAPS_TLSv1:
1588  case OPENVAS_ENCAPS_TLSv11:
1589  case OPENVAS_ENCAPS_TLSv12:
1591  return " through SSL";
1592  default:
1593  snprintf (str, sizeof (str),
1594  " through unknown transport layer - code %d (0x%x)", code,
1595  code);
1596  return str;
1597  }
1598 }
1599 
1600 static int
1601 open_socket (struct sockaddr *paddr, int type, int protocol, int timeout,
1602  int len)
1603 {
1604  fd_set fd_w;
1605  struct timeval to;
1606  int soc, x;
1607  int opt;
1608  unsigned int opt_sz;
1609  int family;
1610 
1611  __port_closed = 0;
1612 
1613  if (paddr->sa_family == AF_INET)
1614  {
1615  family = AF_INET;
1616  if ((soc = socket (AF_INET, type, protocol)) < 0)
1617  {
1618  pid_perror ("socket");
1619  return -1;
1620  }
1621  }
1622  else
1623  {
1624  family = AF_INET6;
1625  if ((soc = socket (AF_INET6, type, protocol)) < 0)
1626  {
1627  pid_perror ("socket");
1628  return -1;
1629  }
1630  }
1631 
1632  if (timeout == -2)
1633  timeout = TIMEOUT;
1634 
1635  if (timeout > 0)
1636  if (unblock_socket (soc) < 0)
1637  {
1638  close (soc);
1639  return -1;
1640  }
1641 
1642  gvm_source_set_socket (soc, 0, family);
1643 
1644  if (connect (soc, paddr, len) < 0)
1645  {
1646  pid_perror ("connect");
1647  again:
1648  switch (errno)
1649  {
1650  case EINPROGRESS:
1651  case EAGAIN:
1652  FD_ZERO (&fd_w);
1653  FD_SET (soc, &fd_w);
1654  to.tv_sec = timeout;
1655  to.tv_usec = 0;
1656  x = select (soc + 1, NULL, &fd_w, NULL, &to);
1657  if (x == 0)
1658  {
1659  pid_perror ("connect->select: timeout");
1660  socket_close (soc);
1661  errno = ETIMEDOUT;
1662  return -1;
1663  }
1664  else if (x < 0)
1665  {
1666  if (errno == EINTR)
1667  {
1668  errno = EAGAIN;
1669  goto again;
1670  }
1671  pid_perror ("select");
1672  socket_close (soc);
1673  return -1;
1674  }
1675 
1676  opt = 0;
1677  opt_sz = sizeof (opt);
1678  if (getsockopt (soc, SOL_SOCKET, SO_ERROR, &opt, &opt_sz) < 0)
1679  {
1680  pid_perror ("getsockopt");
1681  socket_close (soc);
1682  return -1;
1683  }
1684  if (opt == 0)
1685  break;
1686  errno = opt;
1687  pid_perror ("SO_ERROR");
1688  /* fallthrough */
1689  default:
1690  __port_closed = 1;
1691  socket_close (soc);
1692  return -1;
1693  }
1694  }
1695  block_socket (soc);
1696  return soc;
1697 }
1698 
1699 int
1700 open_sock_opt_hn (const char *hostname, unsigned int port, int type,
1701  int protocol, int timeout)
1702 {
1703  struct sockaddr_in addr;
1704  struct sockaddr_in6 addr6;
1705  struct in6_addr in6addr;
1706 
1707  gvm_resolve_as_addr6 (hostname, &in6addr);
1708  if (IN6_IS_ADDR_V4MAPPED (&in6addr))
1709  {
1710  bzero ((void *) &addr, sizeof (addr));
1711  addr.sin_family = AF_INET;
1712  addr.sin_port = htons ((unsigned short) port);
1713  addr.sin_addr.s_addr = in6addr.s6_addr32[3];
1714  return open_socket ((struct sockaddr *) &addr, type, protocol, timeout,
1715  sizeof (struct sockaddr_in));
1716  }
1717  else
1718  {
1719  bzero ((void *) &addr6, sizeof (addr6));
1720  addr6.sin6_family = AF_INET6;
1721  addr6.sin6_port = htons ((unsigned short) port);
1722  memcpy (&addr6.sin6_addr, &in6addr, sizeof (struct in6_addr));
1723  return open_socket ((struct sockaddr *) &addr6, type, protocol, timeout,
1724  sizeof (struct sockaddr_in6));
1725  }
1726 }
1727 
1728 int
1729 open_sock_tcp (struct script_infos *args, unsigned int port, int timeout)
1730 {
1731  int ret, retry = 0;
1732  const char *timeout_retry;
1733 
1734  timeout_retry = prefs_get ("timeout_retry");
1735  if (timeout_retry)
1736  retry = atoi (timeout_retry);
1737  if (retry < 0)
1738  retry = 0;
1739 
1740  while (retry >= 0)
1741  {
1742  errno = 0;
1743  ret = open_sock_option (args, port, SOCK_STREAM, IPPROTO_TCP, timeout);
1744  if (ret >= 0 || errno != ETIMEDOUT)
1745  break;
1746  retry--;
1747  }
1748  if (ret < 0 && errno == ETIMEDOUT)
1749  {
1750  int log_count, attempts = 0;
1751  char *ip_str = plug_get_host_ip_str (args), buffer[1024];
1752  kb_t kb = plug_get_kb (args);
1753  const char *max_attempts;
1754 
1755  max_attempts = prefs_get ("open_sock_max_attempts");
1756  if (max_attempts)
1757  attempts = atoi (max_attempts);
1758  if (attempts < 0)
1759  attempts = 0;
1760 
1761  g_snprintf (buffer, sizeof (buffer), "ConnectTimeout/%s/%d", ip_str,
1762  port);
1763  log_count = kb_item_get_int (kb, buffer);
1764  if (log_count == -1)
1765  log_count = 0;
1766  if (log_count < 3)
1767  {
1768  g_message ("open_sock_tcp: %s:%d time-out.", ip_str, port);
1769  log_count++;
1770  kb_item_set_int (kb, buffer, log_count);
1771  }
1772  if ((log_count >= attempts) && (attempts != 0))
1773  {
1774  /* After some unsuccessfully attempts, the port is set to closed to
1775  * avoid new attempts from other plugins.
1776  */
1777  if (host_get_port_state (args, port) > 0)
1778  {
1779  char ip_str[INET6_ADDRSTRLEN];
1780 
1781  g_snprintf (buffer, sizeof (buffer), "Ports/tcp/%d", port);
1782  g_message ("open_sock_tcp: %s:%d too many timeouts. "
1783  "This port will be set to closed.",
1784  ip_str, port);
1785  kb_item_set_int (kb, buffer, 0);
1786 
1787  addr6_to_str (args->ip, ip_str);
1788  snprintf (buffer, sizeof (buffer),
1789  "ERRMSG|||%s|||%d/tcp||| |||Too many timeouts. The port"
1790  " was set to closed.",
1791  plug_current_vhost () ?: " ", port);
1792  kb_item_push_str (args->key, "internal/results", buffer);
1793  }
1794  }
1795  g_free (ip_str);
1796  }
1797 
1798  return ret;
1799 }
1800 
1801 int
1802 open_sock_option (struct script_infos *args, unsigned int port, int type,
1803  int protocol, int timeout)
1804 {
1805  struct sockaddr_in addr;
1806  struct sockaddr_in6 addr6;
1807  struct in6_addr *t;
1808 
1809  t = plug_get_host_ip (args);
1810  if (!t)
1811  {
1812  g_message ("ERROR ! NO ADDRESS ASSOCIATED WITH NAME");
1813  return -1;
1814  }
1815  if (IN6_ARE_ADDR_EQUAL (t, &in6addr_any))
1816  return -1;
1817  if (IN6_IS_ADDR_V4MAPPED (t))
1818  {
1819  bzero ((void *) &addr, sizeof (addr));
1820  addr.sin_family = AF_INET;
1821  addr.sin_port = htons ((unsigned short) port);
1822  addr.sin_addr.s_addr = t->s6_addr32[3];
1823  return open_socket ((struct sockaddr *) &addr, type, protocol, timeout,
1824  sizeof (struct sockaddr_in));
1825  }
1826  else
1827  {
1828  bzero ((void *) &addr6, sizeof (addr6));
1829  addr6.sin6_family = AF_INET6;
1830  addr6.sin6_port = htons ((unsigned short) port);
1831  memcpy (&addr6.sin6_addr, t, sizeof (struct in6_addr));
1832  return open_socket ((struct sockaddr *) &addr6, type, protocol, timeout,
1833  sizeof (struct sockaddr_in6));
1834  }
1835 }
1836 
1845 int
1846 recv_line (int soc, char *buf, size_t bufsiz)
1847 {
1848  int n;
1849  unsigned int ret = 0;
1850 
1851  /* Dirty SSL hack */
1852  if (OPENVAS_STREAM (soc))
1853  {
1854  unsigned int ret = 0;
1855  buf[0] = '\0';
1856 
1857  do
1858  {
1859  n = read_stream_connection_min (soc, buf + ret, 1, 1);
1860  switch (n)
1861  {
1862  case -1:
1863  if (ret == 0)
1864  return -1;
1865  else
1866  return ret;
1867  break;
1868 
1869  case 0:
1870  return ret;
1871  break;
1872 
1873  default:
1874  ret++;
1875  }
1876  }
1877  while (buf[ret - 1] != '\0' && buf[ret - 1] != '\n' && ret < bufsiz);
1878 
1879  if (ret > 0)
1880  {
1881  if (buf[ret - 1] != '\0')
1882  {
1883  if (ret < bufsiz)
1884  buf[ret] = '\0';
1885  else
1886  buf[bufsiz - 1] = '\0';
1887  }
1888  }
1889 
1890  return ret;
1891  }
1892  else
1893  {
1894  fd_set rd;
1895 
1896  do
1897  {
1898  int e;
1899  again:
1900  errno = 0;
1901  FD_ZERO (&rd);
1902  FD_SET (soc, &rd);
1903  e = select (soc + 1, &rd, NULL, NULL, NULL);
1904  if (e == 0 && !FD_ISSET (soc, &rd))
1905  return -1;
1906  if (e < 0 && errno == EINTR)
1907  goto again;
1908  if (e > 0)
1909  {
1910  n = recv (soc, buf + ret, 1, 0);
1911  switch (n)
1912  {
1913  case -1:
1914  if (errno == EINTR)
1915  continue;
1916  if (ret == 0)
1917  return -1;
1918  else
1919  return ret;
1920  break;
1921  case 0:
1922  return ret;
1923  break;
1924  default:
1925  ret++;
1926  }
1927  }
1928  else
1929  break;
1930  }
1931  while (buf[ret - 1] != '\0' && buf[ret - 1] != '\n' && ret < bufsiz);
1932 
1933  if (ret > 0)
1934  {
1935  if (buf[ret - 1] != '\0')
1936  {
1937  if (ret < bufsiz)
1938  buf[ret] = '\0';
1939  else
1940  buf[bufsiz - 1] = '\0';
1941  }
1942  }
1943  }
1944 
1945  return ret;
1946 }
1947 
1948 int
1949 socket_close (int soc)
1950 {
1951  return close (soc);
1952 }
1953 
1954 /*
1955  * Select() routines
1956  */
1957 
1958 int
1960 {
1961  return OPENVAS_STREAM (fd); /* Should probably be smarter... */
1962 }
1963 
1964 int
1966 {
1967  openvas_connection *p;
1968  if (!OPENVAS_STREAM (fd))
1969  return -1;
1970  p = OVAS_CONNECTION_FROM_FD (fd);
1971  return p->bufsz;
1972 }
1973 
1974 int
1975 stream_set_buffer (int fd, int sz)
1976 {
1977  openvas_connection *p;
1978  char *b;
1979 
1980  if (!OPENVAS_STREAM (fd))
1981  return -1;
1982 
1983  p = OVAS_CONNECTION_FROM_FD (fd);
1984  if (sz < p->bufcnt)
1985  return -1; /* Do not want to lose data */
1986 
1987  if (sz == 0)
1988  {
1989  g_free (p->buf);
1990  p->buf = NULL;
1991  p->bufsz = 0;
1992  return 0;
1993  }
1994  else if (p->buf == 0)
1995  {
1996  p->buf = g_malloc0 (sz);
1997  if (p->buf == NULL)
1998  return -1;
1999  p->bufsz = sz;
2000  p->bufptr = 0;
2001  p->bufcnt = 0;
2002  return 0;
2003  }
2004  else
2005  {
2006  if (p->bufcnt > 0)
2007  {
2008  memmove (p->buf, p->buf + p->bufptr, p->bufcnt);
2009  p->bufptr = 0;
2010  }
2011  b = g_realloc (p->buf, sz);
2012  if (b == NULL)
2013  return -1;
2014  p->buf = b;
2015  p->bufsz = sz;
2016  return 0;
2017  }
2018 }
2019 
2020 /*------------------------------------------------------------------*/
2021 
2022 int
2023 os_send (int soc, void *buf, int len, int opt)
2024 {
2025  char *buf0 = (char *) buf;
2026  int e, n;
2027  for (n = 0; n < len;)
2028  {
2029  errno = 0;
2030  e = send (soc, buf0 + n, len - n, opt);
2031  if (e < 0 && errno == EINTR)
2032  continue;
2033  else if (e <= 0)
2034  return -1;
2035  else
2036  n += e;
2037  }
2038  return n;
2039 }
2040 
2041 int
2042 os_recv (int soc, void *buf, int len, int opt)
2043 {
2044  char *buf0 = (char *) buf;
2045  int e, n;
2046  for (n = 0; n < len;)
2047  {
2048  errno = 0;
2049  e = recv (soc, buf0 + n, len - n, opt);
2050  if (e < 0 && errno == EINTR)
2051  continue;
2052  else if (e <= 0)
2053  return -1;
2054  else
2055  n += e;
2056  }
2057  return n;
2058 }
2059 
2060 /* This is a helper function for nasl_get_sock_info. It is used to
2061  retrieve information about SOCK. */
2062 int
2063 get_sock_infos (int sock, int *r_transport, void **r_tls_session)
2064 {
2065  openvas_connection *fp;
2066 
2067  if (!OPENVAS_STREAM (sock))
2068  return ENOTSOCK;
2069  fp = &(connections[sock - OPENVAS_FD_OFF]);
2070 
2071  *r_transport = fp->transport;
2072  *r_tls_session = fp->tls_session;
2073  return 0;
2074 }
2075 
2076 /*
2077  * 0 is considered as the biggest number, since it
2078  * ends our string
2079  */
2080 static int
2081 qsort_compar (const void *a, const void *b)
2082 {
2083  u_short *aa = (u_short *) a;
2084  u_short *bb = (u_short *) b;
2085  if (*aa == 0)
2086  return 1;
2087  else if (*bb == 0)
2088  return -1;
2089  else
2090  return *aa - *bb;
2091 }
2092 
2102 unsigned short *
2103 getpts (char *origexpr, int *len)
2104 {
2105  int exlen;
2106  char *p, *q;
2107  unsigned short *tmp, *ports;
2108  int i = 0, j = 0, start, end;
2109  char *expr;
2110  char *mem;
2111  char *s_start, *s_end;
2112  static unsigned short *last_ret = NULL;
2113  static char *last_expr = NULL;
2114  static int last_num;
2115 
2116  expr = g_strdup (origexpr);
2117  exlen = strlen (origexpr);
2118  mem = expr;
2119 
2120  if (last_expr != NULL)
2121  {
2122  if (strcmp (last_expr, expr) == 0)
2123  {
2124  if (len != NULL)
2125  *len = last_num;
2126  g_free (mem);
2127  return last_ret;
2128  }
2129  else
2130  {
2131  g_free (last_expr);
2132  last_expr = NULL;
2133  g_free (&last_ret);
2134  last_ret = NULL;
2135  }
2136  }
2137 
2138  ports = g_malloc0 (65536 * sizeof (short));
2139  for (; j < exlen; j++)
2140  if (expr[j] != ' ')
2141  expr[i++] = expr[j];
2142  expr[i] = '\0';
2143 
2144  if ((s_start = strstr (expr, "T:")) != NULL)
2145  expr = &(s_start[2]);
2146 
2147  if ((s_end = strstr (expr, "U:")) != NULL)
2148  {
2149  if (s_end[-1] == ',')
2150  s_end--;
2151  s_end[0] = '\0';
2152  }
2153 
2154  i = 0;
2155  while ((p = strchr (expr, ',')))
2156  {
2157  *p = '\0';
2158  if (*expr == '-')
2159  {
2160  start = 1;
2161  end = atoi (expr + 1);
2162  }
2163  else
2164  {
2165  start = end = atoi (expr);
2166  if ((q = strchr (expr, '-')) && *(q + 1))
2167  end = atoi (q + 1);
2168  else if (q && !*(q + 1))
2169  end = 65535;
2170  }
2171  if (start < 1)
2172  start = 1;
2173  if (start > end)
2174  {
2175  g_free (mem);
2176  g_free (ports);
2177  return NULL;
2178  }
2179  for (j = start; j <= end; j++)
2180  ports[i++] = j;
2181  expr = p + 1;
2182  }
2183  if (*expr == '-')
2184  {
2185  start = 1;
2186  end = atoi (expr + 1);
2187  }
2188  else
2189  {
2190  start = end = atoi (expr);
2191  if ((q = strchr (expr, '-')) && *(q + 1))
2192  end = atoi (q + 1);
2193  else if (q && !*(q + 1))
2194  end = 65535;
2195  }
2196  if (start < 1)
2197  start = 1;
2198  if (start > end)
2199  {
2200  g_free (mem);
2201  g_free (ports);
2202  return NULL;
2203  }
2204  for (j = start; j <= end; j++)
2205  ports[i++] = j;
2206  ports[i++] = 0;
2207 
2208  qsort (ports, i, sizeof (u_short), qsort_compar);
2209  tmp = g_realloc (ports, i * sizeof (short));
2210  if (len != NULL)
2211  *len = i - 1;
2212  g_free (mem);
2213 
2214  last_ret = tmp;
2215  last_expr = g_strdup (origexpr);
2216  last_num = i - 1;
2217  return tmp;
2218 }
static int get_connection_fd(void)
Returns a free file descriptor.
Definition: network.c:163
char * plug_get_host_fqdn(struct script_infos *args)
Definition: plugutils.c:211
Header file for module plugutils.
Support macros for special platforms.
Object to store a list of hooks for close_stream_connection.
Definition: network.c:112
static int set_gnutls_protocol(gnutls_session_t session, openvas_encaps_t encaps, const char *priority)
Definition: network.c:404
const char * get_encaps_name(openvas_encaps_t code)
Definition: network.c:1546
#define OPENVAS_FD_OFF
Definition: network.c:105
gnutls_session_t tls_session
Definition: network.c:88
int os_send(int soc, void *buf, int len, int opt)
Definition: network.c:2023
static int release_connection_fd(int fd, int already_closed)
Definition: network.c:183
static void log_message_gnutls(int level, const char *msg)
Definition: network.c:342
#define OVAS_CONNECTION_FROM_FD(fd)
Definition: network.c:132
#define INCR_TIMEOUT
int(* fnc)(int fd)
Definition: network.c:115
int openvas_deregister_connection(int fd)
Definition: network.c:269
int openvas_get_socket_from_connection(int fd)
Definition: network.c:367
static struct csc_hook_s * csc_hooks
Linked list of hooks to be run by close_stream_connection.
Definition: network.c:121
char * name
Definition: scanneraux.h:49
kb_t plug_get_kb(struct script_infos *args)
Definition: plugutils.c:658
enum openvas_encaps openvas_encaps_t
static int __port_closed
Definition: network.c:293
static pid_t pid
int openvas_register_connection(int soc, void *ssl, gnutls_certificate_credentials_t certcred, openvas_encaps_t encaps)
Definition: network.c:244
const char * plug_current_vhost(void)
Definition: plugutils.c:57
static int open_socket(struct sockaddr *paddr, int type, int protocol, int timeout, int len)
Definition: network.c:1601
int recv_line(int soc, char *buf, size_t bufsiz)
Reads a text from the socket stream into the argument buffer, always.
Definition: network.c:1846
static openvas_connection connections[OPENVAS_FD_MAX]
Definition: network.c:107
int stream_set_buffer(int fd, int sz)
Definition: network.c:1975
int open_stream_auto_encaps_ext(struct script_infos *args, unsigned int port, int timeout, int force)
Definition: network.c:1002
int openvas_SSL_init()
Initializes SSL support.
Definition: network.c:351
const char * nasl_get_function_name()
Definition: nasl_debug.c:91
const char * nasl_get_plugin_filename()
Get the current launched plugin filename.
Definition: nasl_debug.c:52
gnutls_session_t ovas_get_tlssession_from_connection(int fd)
Definition: network.c:387
int fd_is_stream(int fd)
Definition: network.c:1959
int nsend(int fd, void *data, int length, int i_opt)
Definition: network.c:1402
openvas_encaps_t transport
Definition: network.c:82
int read_stream_connection(int fd, void *buf0, int len)
Definition: network.c:1272
int open_sock_tcp(struct script_infos *args, unsigned int port, int timeout)
Definition: network.c:1729
gnutls_certificate_credentials_t tls_cred
Definition: network.c:89
void add_close_stream_connection_hook(int(*fnc)(int fd))
Register a hook function for close_stream_connection.
Definition: network.c:1479
int socket_get_ssl_version(int fd)
Definition: network.c:766
void socket_get_cert(int fd, void **cert, int *certlen)
Definition: network.c:730
unsigned short * getpts(char *origexpr, int *len)
Converts a string like "-100,200-1024,3000-4000,60000-" into an array.
Definition: network.c:2103
static int load_cert_and_key(gnutls_certificate_credentials_t xcred, const char *cert, const char *key, const char *passwd)
Loads a certificate and the corresponding private key from PEM files.
Definition: network.c:457
int plug_get_port_transport(struct script_infos *args, int port)
Definition: plugutils.c:885
static int run_csc_hooks(int fd)
Run the hooks for close_stream_connection.
Definition: network.c:1507
#define OPENVAS_STREAM(x)
Definition: network.c:126
int host_get_port_state(struct script_infos *plugdata, int portnum)
Definition: plugutils.c:154
static int unblock_socket(int soc)
Definition: network.c:296
int read_stream_connection_min(int fd, void *buf0, int min_len, int max_len)
Definition: network.c:1212
#define TIMEOUT
Definition: network.c:58
struct in6_addr * plug_get_host_ip(struct script_infos *args)
Definition: plugutils.c:285
int stream_get_buffer_sz(int fd)
Definition: network.c:1965
struct in6_addr * ip
Definition: scanneraux.h:51
Header file for module network.
static int is_ip_address(const char *str)
Definition: network.c:549
void plug_set_port_transport(struct script_infos *args, int port, int tr)
Definition: plugutils.c:872
int nrecv(int fd, void *data, int length, int i_opt)
Definition: network.c:1441
int socket_negotiate_ssl(int fd, openvas_encaps_t transport, struct script_infos *args)
Definition: network.c:683
static int read_stream_connection_unbuffered(int fd, void *buf0, int min_len, int max_len)
Definition: network.c:1049
int socket_get_ssl_ciphersuite(int fd)
Definition: network.c:847
int stream_get_err(int fd)
Definition: network.c:145
static int block_socket(int soc)
Definition: network.c:313
struct timeval timeval(unsigned long val)
int write_stream_connection(int fd, void *buf0, int n)
Definition: network.c:1396
int open_sock_option(struct script_infos *args, unsigned int port, int type, int protocol, int timeout)
Definition: network.c:1802
static int write_stream_connection4(int fd, void *buf0, int n, int i_opt)
Definition: network.c:1278
int open_sock_opt_hn(const char *hostname, unsigned int port, int type, int protocol, int timeout)
Definition: network.c:1700
const char * get_encaps_through(openvas_encaps_t code)
Definition: network.c:1577
static int open_SSL_connection(openvas_connection *fp, const char *cert, const char *key, const char *passwd, const char *cafile, const char *hostname)
Definition: network.c:561
void socket_get_ssl_session_id(int fd, void **sid, size_t *ssize)
Definition: network.c:807
char * plug_get_host_ip_str(struct script_infos *desc)
Definition: plugutils.c:291
const char * hostname
Definition: pluginlaunch.c:76
int open_stream_connection_ext(struct script_infos *args, unsigned int port, int transport, int timeout, const char *priority)
Definition: network.c:886
int get_sock_infos(int sock, int *r_transport, void **r_tls_session)
Definition: network.c:2063
char * priority
Definition: network.c:83
static int qsort_compar(const void *a, const void *b)
Definition: network.c:2081
int os_recv(int soc, void *buf, int len, int opt)
Definition: network.c:2042
int socket_close(int soc)
Definition: network.c:1949
struct csc_hook_s * next
Definition: network.c:114
#define code
int stream_set_timeout(int fd, int timeout)
Definition: network.c:1033
static int pid_perror(const char *error)
Definition: network.c:138
#define OPENVAS_FD_MAX
Definition: network.c:104
int open_stream_connection(struct script_infos *args, unsigned int port, int transport, int timeout)
Definition: network.c:992
void tlserror(char *txt, int err)
Definition: network.c:336
int close_stream_connection(int fd)
Definition: network.c:1518