hostname.cc 16.7 KB
Newer Older
1
/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
unknown's avatar
unknown committed
2

unknown's avatar
unknown committed
3 4
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
unknown's avatar
unknown committed
5
   the Free Software Foundation; version 2 of the License.
unknown's avatar
unknown committed
6

unknown's avatar
unknown committed
7 8 9 10
   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.
unknown's avatar
unknown committed
11

unknown's avatar
unknown committed
12 13 14 15 16
   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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */


unknown's avatar
unknown committed
17 18 19 20
/**
  @file

  @brief
21
  Get hostname for an IP address.
unknown's avatar
unknown committed
22

23 24
  Hostnames are checked with reverse name lookup and checked that they
  doesn't resemble an IP address.
unknown's avatar
unknown committed
25 26
*/

27 28 29 30 31 32
#include "sql_priv.h"
#include "hostname.h"
#include "my_global.h"
#ifndef __WIN__
#include <netdb.h>        // getservbyname, servent
#endif
unknown's avatar
unknown committed
33 34
#include "hash_filo.h"
#include <m_ctype.h>
35 36 37 38
#include "log.h"                                // sql_print_warning,
                                                // sql_print_information
#include "violite.h"                            // vio_getnameinfo,
                                                // vio_get_normalized_ip_string
unknown's avatar
unknown committed
39 40 41
#ifdef	__cplusplus
extern "C" {					// Because of SCO 3.2V4.2
#endif
42
#if !defined( __WIN__)
unknown's avatar
unknown committed
43 44 45 46 47 48 49 50 51
#ifdef HAVE_SYS_UN_H
#include <sys/un.h>
#endif
#include <sys/utsname.h>
#endif // __WIN__
#ifdef	__cplusplus
}
#endif

52 53 54 55 56 57 58 59 60 61 62 63
/*
  HOST_ENTRY_KEY_SIZE -- size of IP address string in the hash cache.
*/

#define HOST_ENTRY_KEY_SIZE INET6_ADDRSTRLEN

/**
  An entry in the hostname hash table cache.

  Host name cache does two things:
    - caches host names to save DNS look ups;
    - counts connect errors from IP.
unknown's avatar
unknown committed
64

65 66 67 68 69
  Host name can be NULL (that means DNS look up failed), but connect errors
  still are counted.
*/

class Host_entry :public hash_filo_element
unknown's avatar
unknown committed
70 71
{
public:
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
  /**
    Client IP address. This is the key used with the hash table.

    The client IP address is always expressed in IPv6, even when the
    network IPv6 stack is not present.

    This IP address is never used to connect to a socket.
  */
  char ip_key[HOST_ENTRY_KEY_SIZE];

  /**
    Number of errors during handshake phase from the IP address.
  */
  uint connect_errors;

  /**
    One of the host names for the IP address. May be NULL.
  */
  const char *hostname;
unknown's avatar
unknown committed
91 92 93 94 95 96 97 98 99 100 101
};

static hash_filo *hostname_cache;

void hostname_cache_refresh()
{
  hostname_cache->clear();
}

bool hostname_cache_init()
{
102 103 104 105 106 107 108
  Host_entry tmp;
  uint key_offset= (uint) ((char*) (&tmp.ip_key) - (char*) &tmp);

  if (!(hostname_cache= new hash_filo(HOST_CACHE_SIZE,
                                      key_offset, HOST_ENTRY_KEY_SIZE,
                                      NULL, (my_hash_free_key) free,
                                      &my_charset_bin)))
unknown's avatar
unknown committed
109
    return 1;
110

unknown's avatar
unknown committed
111
  hostname_cache->clear();
112

unknown's avatar
unknown committed
113 114 115 116 117
  return 0;
}

void hostname_cache_free()
{
118 119
  delete hostname_cache;
  hostname_cache= NULL;
unknown's avatar
unknown committed
120 121
}

122 123 124 125 126
static void prepare_hostname_cache_key(const char *ip_string,
                                       char *ip_key)
{
  int ip_string_length= strlen(ip_string);
  DBUG_ASSERT(ip_string_length < HOST_ENTRY_KEY_SIZE);
127

128
  memset(ip_key, 0, HOST_ENTRY_KEY_SIZE);
129
  memcpy(ip_key, ip_string, ip_string_length);
130 131 132
}

static inline Host_entry *hostname_cache_search(const char *ip_key)
unknown's avatar
unknown committed
133
{
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
  return (Host_entry *) hostname_cache->search((uchar *) ip_key, 0);
}

static bool add_hostname_impl(const char *ip_key, const char *hostname)
{
  if (hostname_cache_search(ip_key))
    return FALSE;

  size_t hostname_size= hostname ? strlen(hostname) + 1 : 0;

  Host_entry *entry= (Host_entry *) malloc(sizeof (Host_entry) + hostname_size);

  if (!entry)
    return TRUE;

  char *hostname_copy;

151
  memcpy(&entry->ip_key, ip_key, HOST_ENTRY_KEY_SIZE);
152 153

  if (hostname_size)
unknown's avatar
unknown committed
154
  {
155 156
    hostname_copy= (char *) (entry + 1);
    memcpy(hostname_copy, hostname, hostname_size);
unknown's avatar
unknown committed
157

158 159 160
    DBUG_PRINT("info", ("Adding '%s' -> '%s' to the hostname cache...'",
                        (const char *) ip_key,
                        (const char *) hostname_copy));
unknown's avatar
unknown committed
161
  }
162 163 164 165 166 167 168 169 170 171
  else
  {
    hostname_copy= NULL;

    DBUG_PRINT("info", ("Adding '%s' -> NULL to the hostname cache...'",
                        (const char *) ip_key));
  }

  entry->hostname= hostname_copy;
  entry->connect_errors= 0;
unknown's avatar
unknown committed
172

173 174
  return hostname_cache->add(entry);
}
unknown's avatar
unknown committed
175

176
static bool add_hostname(const char *ip_key, const char *hostname)
unknown's avatar
unknown committed
177
{
178 179 180
  if (specialflag & SPECIAL_NO_HOST_CACHE)
    return FALSE;

Marc Alff's avatar
Marc Alff committed
181
  mysql_mutex_lock(&hostname_cache->lock);
182 183 184

  bool err_status= add_hostname_impl(ip_key, hostname);

Marc Alff's avatar
Marc Alff committed
185
  mysql_mutex_unlock(&hostname_cache->lock);
186 187

  return err_status;
unknown's avatar
unknown committed
188 189
}

190
void inc_host_errors(const char *ip_string)
unknown's avatar
unknown committed
191
{
192 193 194 195 196 197
  if (!ip_string)
    return;

  char ip_key[HOST_ENTRY_KEY_SIZE];
  prepare_hostname_cache_key(ip_string, ip_key);

Marc Alff's avatar
Marc Alff committed
198
  mysql_mutex_lock(&hostname_cache->lock);
199 200 201 202 203 204

  Host_entry *entry= hostname_cache_search(ip_key);

  if (entry)
    entry->connect_errors++;

Marc Alff's avatar
Marc Alff committed
205
  mysql_mutex_unlock(&hostname_cache->lock);
unknown's avatar
unknown committed
206 207
}

208 209

void reset_host_errors(const char *ip_string)
unknown's avatar
unknown committed
210
{
211 212 213 214 215 216
  if (!ip_string)
    return;

  char ip_key[HOST_ENTRY_KEY_SIZE];
  prepare_hostname_cache_key(ip_string, ip_key);

Marc Alff's avatar
Marc Alff committed
217
  mysql_mutex_lock(&hostname_cache->lock);
218 219 220 221 222 223

  Host_entry *entry= hostname_cache_search(ip_key);

  if (entry)
    entry->connect_errors= 0;

Marc Alff's avatar
Marc Alff committed
224
  mysql_mutex_unlock(&hostname_cache->lock);
unknown's avatar
unknown committed
225 226 227
}


228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
static inline bool is_ip_loopback(const struct sockaddr *ip)
{
  switch (ip->sa_family) {
  case AF_INET:
    {
      /* Check for IPv4 127.0.0.1. */
      struct in_addr *ip4= &((struct sockaddr_in *) ip)->sin_addr;
      return ntohl(ip4->s_addr) == INADDR_LOOPBACK;
    }

#ifdef HAVE_IPV6
  case AF_INET6:
    {
      /* Check for IPv6 ::1. */
      struct in6_addr *ip6= &((struct sockaddr_in6 *) ip)->sin6_addr;
      return IN6_IS_ADDR_LOOPBACK(ip6);
    }
#endif /* HAVE_IPV6 */

  default:
    return FALSE;
  }
}

static inline bool is_hostname_valid(const char *hostname)
unknown's avatar
unknown committed
253
{
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
  /*
    A hostname is invalid if it starts with a number followed by a dot
    (IPv4 address).
  */

  if (!my_isdigit(&my_charset_latin1, hostname[0]))
    return TRUE;

  const char *p= hostname + 1;

  while (my_isdigit(&my_charset_latin1, *p))
    ++p;

  return *p != '.';
}

/**
  Resolve IP-address to host name.

  This function does the following things:
    - resolves IP-address;
    - employs Forward Confirmed Reverse DNS technique to validate IP-address;
    - returns host name if IP-address is validated;
    - set value to out-variable connect_errors -- this variable represents the
      number of connection errors from the specified IP-address.

  NOTE: connect_errors are counted (are supported) only for the clients
  where IP-address can be resolved and FCrDNS check is passed.

  @param [in]  ip_storage IP address (sockaddr). Must be set.
  @param [in]  ip_string  IP address (string). Must be set.
  @param [out] hostname
  @param [out] connect_errors

  @return Error status
  @retval FALSE Success
  @retval TRUE Error

  The function does not set/report MySQL server error in case of failure.
  It's caller's responsibility to handle failures of this function
  properly.
*/

bool ip_to_hostname(struct sockaddr_storage *ip_storage,
                    const char *ip_string,
                    char **hostname, uint *connect_errors)
{
  const struct sockaddr *ip= (const sockaddr *) ip_storage;
  int err_code;
  bool err_status;

unknown's avatar
unknown committed
305
  DBUG_ENTER("ip_to_hostname");
306 307 308
  DBUG_PRINT("info", ("IP address: '%s'; family: %d.",
                      (const char *) ip_string,
                      (int) ip->sa_family));
309

310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
  /* Check if we have loopback address (127.0.0.1 or ::1). */

  if (is_ip_loopback(ip))
  {
    DBUG_PRINT("info", ("Loopback address detected."));

    *connect_errors= 0; /* Do not count connect errors from localhost. */
    *hostname= (char *) my_localhost;

    DBUG_RETURN(FALSE);
  }

  /* Prepare host name cache key. */

  char ip_key[HOST_ENTRY_KEY_SIZE];
  prepare_hostname_cache_key(ip_string, ip_key);

  /* Check first if we have host name in the cache. */
unknown's avatar
unknown committed
328 329 330

  if (!(specialflag & SPECIAL_NO_HOST_CACHE))
  {
Marc Alff's avatar
Marc Alff committed
331
    mysql_mutex_lock(&hostname_cache->lock);
332 333 334 335

    Host_entry *entry= hostname_cache_search(ip_key);

    if (entry)
unknown's avatar
unknown committed
336
    {
337 338 339 340 341 342 343 344 345 346 347 348
      *connect_errors= entry->connect_errors;
      *hostname= NULL;

      if (entry->hostname)
        *hostname= my_strdup(entry->hostname, MYF(0));

      DBUG_PRINT("info",("IP (%s) has been found in the cache. "
                         "Hostname: '%s'; connect_errors: %d",
                         (const char *) ip_key,
                         (const char *) (*hostname? *hostname : "null"),
                         (int) *connect_errors));

Marc Alff's avatar
Marc Alff committed
349
      mysql_mutex_unlock(&hostname_cache->lock);
350 351

      DBUG_RETURN(FALSE);
unknown's avatar
unknown committed
352
    }
353

Marc Alff's avatar
Marc Alff committed
354
    mysql_mutex_unlock(&hostname_cache->lock);
unknown's avatar
unknown committed
355 356
  }

357 358 359 360 361 362 363 364 365 366 367 368
  /*
    Resolve host name. Return an error if a host name can not be resolved
    (instead of returning the numeric form of the host name).
  */

  char hostname_buffer[NI_MAXHOST];

  DBUG_PRINT("info", ("Resolving '%s'...", (const char *) ip_key));

  err_code= vio_getnameinfo(ip, hostname_buffer, NI_MAXHOST, NULL, 0,
                            NI_NAMEREQD);

369 370 371 372 373 374 375 376
  /* BEGIN : DEBUG */
  DBUG_EXECUTE_IF("addr_fake_ipv4",
                  {
                    strcpy(hostname_buffer, "santa.claus.ipv4.example.com");
                    err_code= 0;
                  };);
  /* END   : DEBUG */

377
  if (err_code)
unknown's avatar
unknown committed
378
  {
379
    // NOTE: gai_strerror() returns a string ending by a dot.
380

381 382 383
    DBUG_PRINT("error", ("IP address '%s' could not be resolved: %s",
                         (const char *) ip_key,
                         (const char *) gai_strerror(err_code)));
384

385 386 387
    sql_print_warning("IP address '%s' could not be resolved: %s",
                      (const char *) ip_key,
                      (const char *) gai_strerror(err_code));
388

389 390 391 392 393
    if (vio_is_no_name_error(err_code))
    {
      /*
        The no-name error means that there is no reverse address mapping
        for the IP address. A host name can not be resolved.
394

395 396 397
        If it is not the no-name error, we should not cache the hostname
        (or rather its absence), because the failure might be transient.
      */
398

399
      add_hostname(ip_key, NULL);
400

401 402 403
      *hostname= NULL;
      *connect_errors= 0; /* New IP added to the cache. */
    }
unknown's avatar
unknown committed
404

405
    DBUG_RETURN(FALSE);
unknown's avatar
unknown committed
406
  }
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427

  DBUG_PRINT("info", ("IP '%s' resolved to '%s'.",
                      (const char *) ip_key,
                      (const char *) hostname_buffer));

  /*
    Validate hostname: the server does not accept host names, which
    resemble IP addresses.

    The thing is that theoretically, a host name can be in a form of IPv4
    address (123.example.org, or 1.2 or even 1.2.3.4). We have to deny such
    host names because ACL-systems is not designed to work with them.

    For example, it is possible to specify a host name mask (like
    192.168.1.%) for an ACL rule. Then, if IPv4-like hostnames are allowed,
    there is a security hole: instead of allowing access for
    192.168.1.0/255 network (which was assumed by the user), the access
    will be allowed for host names like 192.168.1.example.org.
  */

  if (!is_hostname_valid(hostname_buffer))
unknown's avatar
unknown committed
428
  {
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
    DBUG_PRINT("error", ("IP address '%s' has been resolved "
                         "to the host name '%s', which resembles "
                         "IPv4-address itself.",
                         (const char *) ip_key,
                         (const char *) hostname_buffer));

    sql_print_warning("IP address '%s' has been resolved "
                      "to the host name '%s', which resembles "
                      "IPv4-address itself.",
                      (const char *) ip_key,
                      (const char *) hostname_buffer);

    err_status= add_hostname(ip_key, NULL);

    *hostname= NULL;
    *connect_errors= 0; /* New IP added to the cache. */

    DBUG_RETURN(err_status);
unknown's avatar
unknown committed
447
  }
448

449 450 451 452 453 454
  /*
    To avoid crashing the server in DBUG_EXECUTE_IF,
    Define a variable which depicts state of addr_info_list.
  */
  bool free_addr_info_list= false;

455 456 457 458 459 460 461 462 463 464 465 466 467 468
  /* Get IP-addresses for the resolved host name (FCrDNS technique). */

  struct addrinfo hints;
  struct addrinfo *addr_info_list;

  memset(&hints, 0, sizeof (struct addrinfo));
  hints.ai_flags= AI_PASSIVE;
  hints.ai_socktype= SOCK_STREAM;
  hints.ai_family= AF_UNSPEC;

  DBUG_PRINT("info", ("Getting IP addresses for hostname '%s'...",
                      (const char *) hostname_buffer));

  err_code= getaddrinfo(hostname_buffer, NULL, &hints, &addr_info_list);
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
  if (err_code == 0)
    free_addr_info_list= true;

  /* BEGIN : DEBUG */
  DBUG_EXECUTE_IF("addr_fake_ipv4",
                  {
                    if (free_addr_info_list)
                      freeaddrinfo(addr_info_list);

                    struct sockaddr_in *debug_addr;
                    static struct sockaddr_in debug_sock_addr[2];
                    static struct addrinfo debug_addr_info[2];
                    /* Simulating ipv4 192.0.2.5 */
                    debug_addr= & debug_sock_addr[0];
                    debug_addr->sin_family= AF_INET;
                    debug_addr->sin_addr.s_addr= inet_addr("192.0.2.5");

                    /* Simulating ipv4 192.0.2.4 */
                    debug_addr= & debug_sock_addr[1];
                    debug_addr->sin_family= AF_INET;
                    debug_addr->sin_addr.s_addr= inet_addr("192.0.2.4");

                    debug_addr_info[0].ai_addr= (struct sockaddr*) & debug_sock_addr[0];
                    debug_addr_info[0].ai_addrlen= sizeof (struct sockaddr_in);
                    debug_addr_info[0].ai_next= & debug_addr_info[1];

                    debug_addr_info[1].ai_addr= (struct sockaddr*) & debug_sock_addr[1];
                    debug_addr_info[1].ai_addrlen= sizeof (struct sockaddr_in);
                    debug_addr_info[1].ai_next= NULL;

                    addr_info_list= & debug_addr_info[0];
                    err_code= 0;
                    free_addr_info_list= false;
                  };);

  /* END   : DEBUG */
505 506

  if (err_code == EAI_NONAME)
507
  {
508 509 510 511 512 513 514 515 516 517 518 519 520
    /*
      Don't cache responses when the DNS server is down, as otherwise
      transient DNS failure may leave any number of clients (those
      that attempted to connect during the outage) unable to connect
      indefinitely.
    */

    err_status= add_hostname(ip_key, NULL);

    *hostname= NULL;
    *connect_errors= 0; /* New IP added to the cache. */

    DBUG_RETURN(err_status);
521
  }
522
  else if (err_code)
unknown's avatar
unknown committed
523
  {
524 525
    DBUG_PRINT("error", ("getaddrinfo() failed with error code %d.", err_code));
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
526 527
  }

528 529 530 531 532 533 534
  /* Check that getaddrinfo() returned the used IP (FCrDNS technique). */

  DBUG_PRINT("info", ("The following IP addresses found for '%s':",
                      (const char *) hostname_buffer));

  for (struct addrinfo *addr_info= addr_info_list;
       addr_info; addr_info= addr_info->ai_next)
unknown's avatar
unknown committed
535
  {
536 537 538 539 540 541 542 543 544 545 546 547
    char ip_buffer[HOST_ENTRY_KEY_SIZE];

    {
      err_status=
        vio_get_normalized_ip_string(addr_info->ai_addr, addr_info->ai_addrlen,
                                     ip_buffer, sizeof (ip_buffer));
      DBUG_ASSERT(!err_status);
    }

    DBUG_PRINT("info", ("  - '%s'", (const char *) ip_buffer));

    if (strcmp(ip_key, ip_buffer) == 0)
unknown's avatar
unknown committed
548
    {
549 550 551 552 553 554 555 556
      /* Copy host name string to be stored in the cache. */

      *hostname= my_strdup(hostname_buffer, MYF(0));

      if (!*hostname)
      {
        DBUG_PRINT("error", ("Out of memory."));

557 558
        if (free_addr_info_list)
          freeaddrinfo(addr_info_list);
559 560 561 562
        DBUG_RETURN(TRUE);
      }

      break;
unknown's avatar
unknown committed
563 564 565
    }
  }

566 567 568
  /* Log resolved IP-addresses if no match was found. */

  if (!*hostname)
unknown's avatar
unknown committed
569
  {
570 571 572 573 574 575 576 577
    sql_print_information("Hostname '%s' does not resolve to '%s'.",
                          (const char *) hostname_buffer,
                          (const char *) ip_key);
    sql_print_information("Hostname '%s' has the following IP addresses:",
                          (const char *) hostname_buffer);

    for (struct addrinfo *addr_info= addr_info_list;
         addr_info; addr_info= addr_info->ai_next)
unknown's avatar
unknown committed
578
    {
579 580 581 582 583 584 585 586
      char ip_buffer[HOST_ENTRY_KEY_SIZE];

      err_status=
        vio_get_normalized_ip_string(addr_info->ai_addr, addr_info->ai_addrlen,
                                     ip_buffer, sizeof (ip_buffer));
      DBUG_ASSERT(!err_status);

      sql_print_information(" - %s\n", (const char *) ip_buffer);
unknown's avatar
unknown committed
587 588
    }
  }
589

590 591
  /* Free the result of getaddrinfo(). */

592 593
  if (free_addr_info_list)
    freeaddrinfo(addr_info_list);
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611

  /* Add an entry for the IP to the cache. */

  if (*hostname)
  {
    err_status= add_hostname(ip_key, *hostname);
    *connect_errors= 0;
  }
  else
  {
    DBUG_PRINT("error",("Couldn't verify hostname with getaddrinfo()."));

    err_status= add_hostname(ip_key, NULL);
    *hostname= NULL;
    *connect_errors= 0;
  }

  DBUG_RETURN(err_status);
unknown's avatar
unknown committed
612
}