address.c 60.7 KB
Newer Older
1
2
/* Copyright (c) 2003-2004, Roger Dingledine
 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
Nick Mathewson's avatar
Nick Mathewson committed
3
 * Copyright (c) 2007-2016, The Tor Project, Inc. */
4
5
6
/* See LICENSE for licensing information */

/**
7
 * \file address.c
8
 * \brief Functions to use and manipulate the tor_addr_t structure.
9
10
 **/

11
#define ADDRESS_PRIVATE
12

Nick Mathewson's avatar
Nick Mathewson committed
13
14
#include "orconfig.h"

15
#ifdef _WIN32
16
/* For access to structs needed by GetAdaptersAddresses */
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#ifndef WIN32_LEAN_AND_MEAN
#error "orconfig.h didn't define WIN32_LEAN_AND_MEAN"
#endif
#ifndef WINVER
#error "orconfig.h didn't define WINVER"
#endif
#ifndef _WIN32_WINNT
#error "orconfig.h didn't define _WIN32_WINNT"
#endif
#if WINVER < 0x0501
#error "winver too low"
#endif
#if _WIN32_WINNT < 0x0501
#error "winver too low"
#endif
32
#include <winsock2.h>
33
#include <process.h>
34
#include <windows.h>
35
#include <iphlpapi.h>
36
37
#endif

38
39
#include "compat.h"
#include "util.h"
40
#include "util_format.h"
41
42
43
44
45
#include "address.h"
#include "torlog.h"
#include "container.h"
#include "sandbox.h"

46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_ERRNO_H
#include <errno.h>
#endif
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#ifdef HAVE_NETDB_H
#include <netdb.h>
#endif
#ifdef HAVE_SYS_PARAM_H
#include <sys/param.h> /* FreeBSD needs this to know what version it is */
#endif
70
71
72
#ifdef HAVE_SYS_UN_H
#include <sys/un.h>
#endif
73
74
75
#ifdef HAVE_IFADDRS_H
#include <ifaddrs.h>
#endif
76
77
78
79
80
81
#ifdef HAVE_SYS_IOCTL_H
#include <sys/ioctl.h>
#endif
#ifdef HAVE_NET_IF_H
#include <net/if.h>
#endif
82
83
84
85
86
87
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

88
89
90
91
92
93
94
/* tor_addr_is_null() and maybe other functions rely on AF_UNSPEC being 0 to
 * work correctly. Bail out here if we've found a platform where AF_UNSPEC
 * isn't 0. */
#if AF_UNSPEC != 0
#error We rely on AF_UNSPEC being 0. Let us know about your platform, please!
#endif

95
/** Convert the tor_addr_t in <b>a</b>, with port in <b>port</b>, into a
96
 * sockaddr object in *<b>sa_out</b> of object size <b>len</b>.  If not enough
Sebastian Hahn's avatar
Sebastian Hahn committed
97
 * room is available in sa_out, or on error, return 0.  On success, return
98
99
 * the length of the sockaddr.
 *
Sebastian Hahn's avatar
Sebastian Hahn committed
100
101
 * Interface note: ordinarily, we return -1 for error.  We can't do that here,
 * since socklen_t is unsigned on some platforms.
102
 **/
103
104
105
socklen_t
tor_addr_to_sockaddr(const tor_addr_t *a,
                     uint16_t port,
106
107
                     struct sockaddr *sa_out,
                     socklen_t len)
108
{
109
110
  memset(sa_out, 0, len);

111
112
  sa_family_t family = tor_addr_family(a);
  if (family == AF_INET) {
113
    struct sockaddr_in *sin;
114
    if (len < (int)sizeof(struct sockaddr_in))
115
      return 0;
116
    sin = (struct sockaddr_in *)sa_out;
117
#ifdef HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
118
    sin->sin_len = sizeof(struct sockaddr_in);
119
#endif
120
    sin->sin_family = AF_INET;
121
122
    sin->sin_port = htons(port);
    sin->sin_addr.s_addr = tor_addr_to_ipv4n(a);
123
    return sizeof(struct sockaddr_in);
124
  } else if (family == AF_INET6) {
125
    struct sockaddr_in6 *sin6;
126
    if (len < (int)sizeof(struct sockaddr_in6))
127
      return 0;
128
    sin6 = (struct sockaddr_in6 *)sa_out;
129
#ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN
130
    sin6->sin6_len = sizeof(struct sockaddr_in6);
131
#endif
132
    sin6->sin6_family = AF_INET6;
133
    sin6->sin6_port = htons(port);
134
135
    memcpy(&sin6->sin6_addr, tor_addr_to_in6_assert(a),
           sizeof(struct in6_addr));
136
137
    return sizeof(struct sockaddr_in6);
  } else {
138
    return 0;
139
140
141
  }
}

142
143
144
145
146
147
148
149
150
/** Set address <b>a</b> to zero.  This address belongs to
 * the AF_UNIX family. */
static void
tor_addr_make_af_unix(tor_addr_t *a)
{
  memset(a, 0, sizeof(*a));
  a->family = AF_UNIX;
}

151
/** Set the tor_addr_t in <b>a</b> to contain the socket address contained in
152
153
154
 * <b>sa</b>.  IF <b>port_out</b> is non-NULL and <b>sa</b> contains a port,
 * set *<b>port_out</b> to that port. Return 0 on success and -1 on
 * failure. */
155
int
156
157
tor_addr_from_sockaddr(tor_addr_t *a, const struct sockaddr *sa,
                       uint16_t *port_out)
158
{
159
160
  tor_assert(a);
  tor_assert(sa);
161
162
163

  memset(a, 0, sizeof(*a));

164
165
  if (sa->sa_family == AF_INET) {
    struct sockaddr_in *sin = (struct sockaddr_in *) sa;
166
    tor_addr_from_ipv4n(a, sin->sin_addr.s_addr);
167
168
    if (port_out)
      *port_out = ntohs(sin->sin_port);
169
170
  } else if (sa->sa_family == AF_INET6) {
    struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
171
    tor_addr_from_in6(a, &sin6->sin6_addr);
172
173
    if (port_out)
      *port_out = ntohs(sin6->sin6_port);
174
175
176
  } else if (sa->sa_family == AF_UNIX) {
    tor_addr_make_af_unix(a);
    return 0;
177
  } else {
178
    tor_addr_make_unspec(a);
179
    return -1;
180
  }
181
182
183
  return 0;
}

184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
/** Return a newly allocated string holding the address described in
 * <b>sa</b>.  AF_UNIX, AF_UNSPEC, AF_INET, and AF_INET6 are supported. */
char *
tor_sockaddr_to_str(const struct sockaddr *sa)
{
  char address[TOR_ADDR_BUF_LEN];
  char *result;
  tor_addr_t addr;
  uint16_t port;
#ifdef HAVE_SYS_UN_H
  if (sa->sa_family == AF_UNIX) {
    struct sockaddr_un *s_un = (struct sockaddr_un *)sa;
    tor_asprintf(&result, "unix:%s", s_un->sun_path);
    return result;
  }
#endif
  if (sa->sa_family == AF_UNSPEC)
    return tor_strdup("unspec");

  if (tor_addr_from_sockaddr(&addr, sa, &port) < 0)
    return NULL;
  if (! tor_addr_to_str(address, &addr, sizeof(address), 1))
    return NULL;
  tor_asprintf(&result, "%s:%d", address, (int)port);
  return result;
}

211
212
213
214
215
216
217
/** Set address <b>a</b> to the unspecified address.  This address belongs to
 * no family. */
void
tor_addr_make_unspec(tor_addr_t *a)
{
  memset(a, 0, sizeof(*a));
  a->family = AF_UNSPEC;
218
219
}

Nick Mathewson's avatar
Nick Mathewson committed
220
/** Set address <b>a</b> to the null address in address family <b>family</b>.
221
222
 * The null address for AF_INET is 0.0.0.0.  The null address for AF_INET6 is
 * [::].  AF_UNSPEC is all null. */
223
224
225
226
227
228
229
void
tor_addr_make_null(tor_addr_t *a, sa_family_t family)
{
  memset(a, 0, sizeof(*a));
  a->family = family;
}

230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
/** Similar behavior to Unix gethostbyname: resolve <b>name</b>, and set
 * *<b>addr</b> to the proper IP address and family. The <b>family</b>
 * argument (which must be AF_INET, AF_INET6, or AF_UNSPEC) declares a
 * <i>preferred</i> family, though another one may be returned if only one
 * family is implemented for this address.
 *
 * Return 0 on success, -1 on failure; 1 on transient failure.
 */
int
tor_addr_lookup(const char *name, uint16_t family, tor_addr_t *addr)
{
  /* Perhaps eventually this should be replaced by a tor_getaddrinfo or
   * something.
   */
  struct in_addr iaddr;
  struct in6_addr iaddr6;
  tor_assert(name);
  tor_assert(addr);
248
  tor_assert(family == AF_INET || family == AF_INET6 || family == AF_UNSPEC);
249
250
251
252
253
  if (!*name) {
    /* Empty address is an error. */
    return -1;
  } else if (tor_inet_pton(AF_INET, name, &iaddr)) {
    /* It's an IPv4 IP. */
254
255
    if (family == AF_INET6)
      return -1;
256
    tor_addr_from_in(addr, &iaddr);
257
258
    return 0;
  } else if (tor_inet_pton(AF_INET6, name, &iaddr6)) {
259
260
    if (family == AF_INET)
      return -1;
261
    tor_addr_from_in6(addr, &iaddr6);
262
263
264
265
266
267
268
269
270
271
272
    return 0;
  } else {
#ifdef HAVE_GETADDRINFO
    int err;
    struct addrinfo *res=NULL, *res_p;
    struct addrinfo *best=NULL;
    struct addrinfo hints;
    int result = -1;
    memset(&hints, 0, sizeof(hints));
    hints.ai_family = family;
    hints.ai_socktype = SOCK_STREAM;
Nick Mathewson's avatar
Nick Mathewson committed
273
    err = sandbox_getaddrinfo(name, NULL, &hints, &res);
274
275
276
    /* The check for 'res' here shouldn't be necessary, but it makes static
     * analysis tools happy. */
    if (!err && res) {
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
      best = NULL;
      for (res_p = res; res_p; res_p = res_p->ai_next) {
        if (family == AF_UNSPEC) {
          if (res_p->ai_family == AF_INET) {
            best = res_p;
            break;
          } else if (res_p->ai_family == AF_INET6 && !best) {
            best = res_p;
          }
        } else if (family == res_p->ai_family) {
          best = res_p;
          break;
        }
      }
      if (!best)
        best = res;
      if (best->ai_family == AF_INET) {
294
295
        tor_addr_from_in(addr,
                         &((struct sockaddr_in*)best->ai_addr)->sin_addr);
296
297
        result = 0;
      } else if (best->ai_family == AF_INET6) {
298
299
        tor_addr_from_in6(addr,
                          &((struct sockaddr_in6*)best->ai_addr)->sin6_addr);
300
301
        result = 0;
      }
302
      sandbox_freeaddrinfo(res);
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
      return result;
    }
    return (err == EAI_AGAIN) ? 1 : -1;
#else
    struct hostent *ent;
    int err;
#ifdef HAVE_GETHOSTBYNAME_R_6_ARG
    char buf[2048];
    struct hostent hostent;
    int r;
    r = gethostbyname_r(name, &hostent, buf, sizeof(buf), &ent, &err);
#elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
    char buf[2048];
    struct hostent hostent;
    ent = gethostbyname_r(name, &hostent, buf, sizeof(buf), &err);
#elif defined(HAVE_GETHOSTBYNAME_R_3_ARG)
    struct hostent_data data;
    struct hostent hent;
    memset(&data, 0, sizeof(data));
    err = gethostbyname_r(name, &hent, &data);
    ent = err ? NULL : &hent;
#else
    ent = gethostbyname(name);
326
#ifdef _WIN32
327
328
329
330
331
332
333
    err = WSAGetLastError();
#else
    err = h_errno;
#endif
#endif /* endif HAVE_GETHOSTBYNAME_R_6_ARG. */
    if (ent) {
      if (ent->h_addrtype == AF_INET) {
334
        tor_addr_from_in(addr, (struct in_addr*) ent->h_addr);
335
      } else if (ent->h_addrtype == AF_INET6) {
336
        tor_addr_from_in6(addr, (struct in6_addr*) ent->h_addr);
337
338
339
340
341
      } else {
        tor_assert(0); /* gethostbyname() returned a bizarre addrtype */
      }
      return 0;
    }
342
#ifdef _WIN32
343
344
345
346
347
348
349
350
351
352
353
354
355
    return (err == WSATRY_AGAIN) ? 1 : -1;
#else
    return (err == TRY_AGAIN) ? 1 : -1;
#endif
#endif
  }
}

/** Return true iff <b>ip</b> is an IP reserved to localhost or local networks
 * in RFC1918 or RFC4193 or RFC4291. (fec0::/10, deprecated by RFC3879, is
 * also treated as internal for now.)
 */
int
356
357
tor_addr_is_internal_(const tor_addr_t *addr, int for_listening,
                      const char *filename, int lineno)
358
359
360
{
  uint32_t iph4 = 0;
  uint32_t iph6[4];
361
362

  tor_assert(addr);
363
  sa_family_t v_family = tor_addr_family(addr);
364
365
366
367
368

  if (v_family == AF_INET) {
    iph4 = tor_addr_to_ipv4h(addr);
  } else if (v_family == AF_INET6) {
    if (tor_addr_is_v4(addr)) { /* v4-mapped */
369
      uint32_t *addr32 = NULL;
370
      v_family = AF_INET;
371
372
373
374
375
376
377
      // Work around an incorrect NULL pointer dereference warning in
      // "clang --analyze" due to limited analysis depth
      addr32 = tor_addr_to_in6_addr32(addr);
      // To improve performance, wrap this assertion in:
      // #if !defined(__clang_analyzer__) || PARANOIA
      tor_assert(addr32);
      iph4 = ntohl(addr32[3]);
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
    }
  }

  if (v_family == AF_INET6) {
    const uint32_t *a32 = tor_addr_to_in6_addr32(addr);
    iph6[0] = ntohl(a32[0]);
    iph6[1] = ntohl(a32[1]);
    iph6[2] = ntohl(a32[2]);
    iph6[3] = ntohl(a32[3]);
    if (for_listening && !iph6[0] && !iph6[1] && !iph6[2] && !iph6[3]) /* :: */
      return 0;

    if (((iph6[0] & 0xfe000000) == 0xfc000000) || /* fc00/7  - RFC4193 */
        ((iph6[0] & 0xffc00000) == 0xfe800000) || /* fe80/10 - RFC4291 */
        ((iph6[0] & 0xffc00000) == 0xfec00000))   /* fec0/10 D- RFC3879 */
      return 1;

    if (!iph6[0] && !iph6[1] && !iph6[2] &&
        ((iph6[3] & 0xfffffffe) == 0x00000000))  /* ::/127 */
      return 1;

    return 0;
  } else if (v_family == AF_INET) {
    if (for_listening && !iph4) /* special case for binding to 0.0.0.0 */
      return 0;
    if (((iph4 & 0xff000000) == 0x0a000000) || /*       10/8 */
        ((iph4 & 0xff000000) == 0x00000000) || /*        0/8 */
        ((iph4 & 0xff000000) == 0x7f000000) || /*      127/8 */
        ((iph4 & 0xffff0000) == 0xa9fe0000) || /* 169.254/16 */
        ((iph4 & 0xfff00000) == 0xac100000) || /*  172.16/12 */
        ((iph4 & 0xffff0000) == 0xc0a80000))   /* 192.168/16 */
      return 1;
    return 0;
  }

  /* unknown address family... assume it's not safe for external use */
  /* rather than tor_assert(0) */
415
416
  log_warn(LD_BUG, "tor_addr_is_internal() called from %s:%d with a "
           "non-IP address of type %d", filename, lineno, (int)v_family);
417
  tor_fragile_assert();
418
419
420
421
422
423
424
425
426
  return 1;
}

/** Convert a tor_addr_t <b>addr</b> into a string, and store it in
 *  <b>dest</b> of size <b>len</b>.  Returns a pointer to dest on success,
 *  or NULL on failure.  If <b>decorate</b>, surround IPv6 addresses with
 *  brackets.
 */
const char *
427
tor_addr_to_str(char *dest, const tor_addr_t *addr, size_t len, int decorate)
428
429
430
431
432
433
{
  const char *ptr;
  tor_assert(addr && dest);

  switch (tor_addr_family(addr)) {
    case AF_INET:
434
435
      /* Shortest addr x.x.x.x + \0 */
      if (len < 8)
436
        return NULL;
437
      ptr = tor_inet_ntop(AF_INET, &addr->addr.in_addr, dest, len);
438
439
      break;
    case AF_INET6:
440
441
442
443
      /* Shortest addr [ :: ] + \0 */
      if (len < (3 + (decorate ? 2 : 0)))
        return NULL;

444
      if (decorate)
445
        ptr = tor_inet_ntop(AF_INET6, &addr->addr.in6_addr, dest+1, len-2);
446
      else
447
        ptr = tor_inet_ntop(AF_INET6, &addr->addr.in6_addr, dest, len);
448

449
450
451
      if (ptr && decorate) {
        *dest = '[';
        memcpy(dest+strlen(dest), "]", 2);
452
453
        tor_assert(ptr == dest+1);
        ptr = dest;
454
455
      }
      break;
456
457
458
459
    case AF_UNIX:
      tor_snprintf(dest, len, "AF_UNIX");
      ptr = dest;
      break;
460
461
462
463
464
465
    default:
      return NULL;
  }
  return ptr;
}

466
467
468
469
470
471
472
473
474
475
476
477
/** Parse an .in-addr.arpa or .ip6.arpa address from <b>address</b>.  Return 0
 * if this is not an .in-addr.arpa address or an .ip6.arpa address.  Return -1
 * if this is an ill-formed .in-addr.arpa address or an .ip6.arpa address.
 * Also return -1 if <b>family</b> is not AF_UNSPEC, and the parsed address
 * family does not match <b>family</b>.  On success, return 1, and store the
 * result, if any, into <b>result</b>, if provided.
 *
 * If <b>accept_regular</b> is set and the address is in neither recognized
 * reverse lookup hostname format, try parsing the address as a regular
 * IPv4 or IPv6 address too.
 */
int
478
tor_addr_parse_PTR_name(tor_addr_t *result, const char *address,
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
                                   int family, int accept_regular)
{
  if (!strcasecmpend(address, ".in-addr.arpa")) {
    /* We have an in-addr.arpa address. */
    char buf[INET_NTOA_BUF_LEN];
    size_t len;
    struct in_addr inaddr;
    if (family == AF_INET6)
      return -1;

    len = strlen(address) - strlen(".in-addr.arpa");
    if (len >= INET_NTOA_BUF_LEN)
      return -1; /* Too long. */

    memcpy(buf, address, len);
    buf[len] = '\0';
    if (tor_inet_aton(buf, &inaddr) == 0)
      return -1; /* malformed. */

    /* reverse the bytes */
499
    inaddr.s_addr = (uint32_t)
500
501
502
503
      (((inaddr.s_addr & 0x000000ff) << 24)
       |((inaddr.s_addr & 0x0000ff00) << 8)
       |((inaddr.s_addr & 0x00ff0000) >> 8)
       |((inaddr.s_addr & 0xff000000) >> 24));
504
505

    if (result) {
506
      tor_addr_from_in(result, &inaddr);
507
508
509
510
511
512
513
514
515
516
517
518
519
    }
    return 1;
  }

  if (!strcasecmpend(address, ".ip6.arpa")) {
    const char *cp;
    int n0, n1;
    struct in6_addr in6;

    if (family == AF_INET)
      return -1;

    cp = address;
520
    for (int i = 0; i < 16; ++i) {
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
      n0 = hex_decode_digit(*cp++); /* The low-order nybble appears first. */
      if (*cp++ != '.') return -1;  /* Then a dot. */
      n1 = hex_decode_digit(*cp++); /* The high-order nybble appears first. */
      if (*cp++ != '.') return -1;  /* Then another dot. */
      if (n0<0 || n1 < 0) /* Both nybbles must be hex. */
        return -1;

      /* We don't check the length of the string in here.  But that's okay,
       * since we already know that the string ends with ".ip6.arpa", and
       * there is no way to frameshift .ip6.arpa so it fits into the pattern
       * of hexdigit, period, hexdigit, period that we enforce above.
       */

      /* Assign from low-byte to high-byte. */
      in6.s6_addr[15-i] = n0 | (n1 << 4);
    }
    if (strcasecmp(cp, "ip6.arpa"))
      return -1;

    if (result) {
541
      tor_addr_from_in6(result, &in6);
542
543
544
545
546
547
    }
    return 1;
  }

  if (accept_regular) {
    tor_addr_t tmp;
548
    int r = tor_addr_parse(&tmp, address);
549
550
551
552
553
554
555
556
557
558
559
560
561
562
    if (r < 0)
      return 0;
    if (r != family && family != AF_UNSPEC)
      return -1;

    if (result)
      memcpy(result, &tmp, sizeof(tor_addr_t));

    return 1;
  }

  return 0;
}

563
564
565
566
/** Convert <b>addr</b> to an in-addr.arpa name or a .ip6.arpa name,
 * and store the result in the <b>outlen</b>-byte buffer at
 * <b>out</b>.  Return the number of chars written to <b>out</b>, not
 * including the trailing \0, on success. Returns -1 on failure. */
567
int
568
tor_addr_to_PTR_name(char *out, size_t outlen,
569
                     const tor_addr_t *addr)
570
{
571
572
573
  tor_assert(out);
  tor_assert(addr);

574
575
576
577
578
579
580
581
582
583
584
  if (addr->family == AF_INET) {
    uint32_t a = tor_addr_to_ipv4h(addr);

    return tor_snprintf(out, outlen, "%d.%d.%d.%d.in-addr.arpa",
                        (int)(uint8_t)((a    )&0xff),
                        (int)(uint8_t)((a>>8 )&0xff),
                        (int)(uint8_t)((a>>16)&0xff),
                        (int)(uint8_t)((a>>24)&0xff));
  } else if (addr->family == AF_INET6) {
    int i;
    char *cp = out;
585
    const uint8_t *bytes = tor_addr_to_in6_addr8(addr);
586
587
588
    if (outlen < REVERSE_LOOKUP_NAME_BUF_LEN)
      return -1;
    for (i = 15; i >= 0; --i) {
589
      uint8_t byte = bytes[i];
590
591
592
593
594
      *cp++ = "0123456789abcdef"[byte & 0x0f];
      *cp++ = '.';
      *cp++ = "0123456789abcdef"[byte >> 4];
      *cp++ = '.';
    }
Nick Mathewson's avatar
Nick Mathewson committed
595
    memcpy(cp, "ip6.arpa", 9); /* 8 characters plus NUL */
596
    return 32 * 2 + 8;
597
598
599
600
  }
  return -1;
}

601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
/** Parse a string <b>s</b> containing an IPv4/IPv6 address, and possibly
 *  a mask and port or port range.  Store the parsed address in
 *  <b>addr_out</b>, a mask (if any) in <b>mask_out</b>, and port(s) (if any)
 *  in <b>port_min_out</b> and <b>port_max_out</b>.
 *
 * The syntax is:
 *   Address OptMask OptPortRange
 *   Address ::= IPv4Address / "[" IPv6Address "]" / "*"
 *   OptMask ::= "/" Integer /
 *   OptPortRange ::= ":*" / ":" Integer / ":" Integer "-" Integer /
 *
 *  - If mask, minport, or maxport are NULL, we do not want these
 *    options to be set; treat them as an error if present.
 *  - If the string has no mask, the mask is set to /32 (IPv4) or /128 (IPv6).
 *  - If the string has one port, it is placed in both min and max port
 *    variables.
 *  - If the string has no port(s), port_(min|max)_out are set to 1 and 65535.
 *
 *  Return an address family on success, or -1 if an invalid address string is
 *  provided.
621
622
623
624
625
 *
 *  If 'flags & TAPMP_EXTENDED_STAR' is false, then the wildcard address '*'
 *  yield an IPv4 wildcard.
 *
 *  If 'flags & TAPMP_EXTENDED_STAR' is true, then the wildcard address '*'
626
627
 *  yields an AF_UNSPEC wildcard address, which expands to corresponding
 *  wildcard IPv4 and IPv6 rules, and the following change is made
628
629
630
631
632
 *  in the grammar above:
 *   Address ::= IPv4Address / "[" IPv6Address "]" / "*" / "*4" / "*6"
 *  with the new "*4" and "*6" productions creating a wildcard to match
 *  IPv4 or IPv6 addresses.
 *
633
634
635
636
637
638
639
 *  If 'flags & TAPMP_EXTENDED_STAR' and 'flags & TAPMP_STAR_IPV4_ONLY' are
 *  both true, then the wildcard address '*' yields an IPv4 wildcard.
 *
 *  If 'flags & TAPMP_EXTENDED_STAR' and 'flags & TAPMP_STAR_IPV6_ONLY' are
 *  both true, then the wildcard address '*' yields an IPv6 wildcard.
 *
 * TAPMP_STAR_IPV4_ONLY and TAPMP_STAR_IPV6_ONLY are mutually exclusive. */
640
int
641
642
643
tor_addr_parse_mask_ports(const char *s,
                          unsigned flags,
                          tor_addr_t *addr_out,
644
645
646
647
648
649
                          maskbits_t *maskbits_out,
                          uint16_t *port_min_out, uint16_t *port_max_out)
{
  char *base = NULL, *address, *mask = NULL, *port = NULL, *rbracket = NULL;
  char *endptr;
  int any_flag=0, v4map=0;
650
651
  sa_family_t family;
  struct in6_addr in6_tmp;
652
  struct in_addr in_tmp = { .s_addr = 0 };
653
654
655

  tor_assert(s);
  tor_assert(addr_out);
656
657
658
659
  /* We can either only want an IPv4 address or only want an IPv6 address,
   * but we can't only want IPv4 & IPv6 at the same time. */
  tor_assert(!((flags & TAPMP_STAR_IPV4_ONLY)
               && (flags & TAPMP_STAR_IPV6_ONLY)));
660

661
662
  /** Longest possible length for an address, mask, and port-range combination.
   * Includes IP, [], /mask, :, ports */
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
#define MAX_ADDRESS_LENGTH (TOR_ADDR_BUF_LEN+2+(1+INET_NTOA_BUF_LEN)+12+1)

  if (strlen(s) > MAX_ADDRESS_LENGTH) {
    log_warn(LD_GENERAL, "Impossibly long IP %s; rejecting", escaped(s));
    goto err;
  }
  base = tor_strdup(s);

  /* Break 'base' into separate strings. */
  address = base;
  if (*address == '[') {  /* Probably IPv6 */
    address++;
    rbracket = strchr(address, ']');
    if (!rbracket) {
      log_warn(LD_GENERAL,
               "No closing IPv6 bracket in address pattern; rejecting.");
      goto err;
    }
  }
  mask = strchr((rbracket?rbracket:address),'/');
  port = strchr((mask?mask:(rbracket?rbracket:address)), ':');
  if (port)
    *port++ = '\0';
  if (mask)
    *mask++ = '\0';
  if (rbracket)
    *rbracket = '\0';
  if (port && mask)
    tor_assert(port > mask);
  if (mask && rbracket)
    tor_assert(mask > rbracket);

  /* Now "address" is the a.b.c.d|'*'|abcd::1 part...
   *     "mask" is the Mask|Maskbits part...
   * and "port" is the *|port|min-max part.
   */

  /* Process the address portion */
  memset(addr_out, 0, sizeof(tor_addr_t));

  if (!strcmp(address, "*")) {
704
    if (flags & TAPMP_EXTENDED_STAR) {
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
      if (flags & TAPMP_STAR_IPV4_ONLY) {
        family = AF_INET;
        tor_addr_from_ipv4h(addr_out, 0);
      } else if (flags & TAPMP_STAR_IPV6_ONLY) {
        static char nil_bytes[16] = { [0]=0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0 };
        family = AF_INET6;
        tor_addr_from_ipv6_bytes(addr_out, nil_bytes);
      } else {
        family = AF_UNSPEC;
        tor_addr_make_unspec(addr_out);
        log_info(LD_GENERAL,
                 "'%s' expands into rules which apply to all IPv4 and IPv6 "
                 "addresses. (Use accept/reject *4:* for IPv4 or "
                 "accept[6]/reject[6] *6:* for IPv6.)", s);
      }
720
721
722
723
724
725
726
    } else {
      family = AF_INET;
      tor_addr_from_ipv4h(addr_out, 0);
    }
    any_flag = 1;
  } else if (!strcmp(address, "*4") && (flags & TAPMP_EXTENDED_STAR)) {
    family = AF_INET;
727
    tor_addr_from_ipv4h(addr_out, 0);
728
    any_flag = 1;
729
  } else if (!strcmp(address, "*6") && (flags & TAPMP_EXTENDED_STAR)) {
730
    static char nil_bytes[16] = { [0]=0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0 };
731
732
733
    family = AF_INET6;
    tor_addr_from_ipv6_bytes(addr_out, nil_bytes);
    any_flag = 1;
734
735
736
737
738
739
  } else if (tor_inet_pton(AF_INET6, address, &in6_tmp) > 0) {
    family = AF_INET6;
    tor_addr_from_in6(addr_out, &in6_tmp);
  } else if (tor_inet_pton(AF_INET, address, &in_tmp) > 0) {
    family = AF_INET;
    tor_addr_from_in(addr_out, &in_tmp);
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
  } else {
    log_warn(LD_GENERAL, "Malformed IP %s in address pattern; rejecting.",
             escaped(address));
    goto err;
  }

  v4map = tor_addr_is_v4(addr_out);

  /* Parse mask */
  if (maskbits_out) {
    int bits = 0;
    struct in_addr v4mask;

    if (mask) {  /* the caller (tried to) specify a mask */
      bits = (int) strtol(mask, &endptr, 10);
      if (!*endptr) {  /* strtol converted everything, so it was an integer */
        if ((bits<0 || bits>128) ||
757
            (family == AF_INET && bits > 32)) {
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
          log_warn(LD_GENERAL,
                   "Bad number of mask bits (%d) on address range; rejecting.",
                   bits);
          goto err;
        }
      } else {  /* mask might still be an address-style mask */
        if (tor_inet_pton(AF_INET, mask, &v4mask) > 0) {
          bits = addr_mask_get_bits(ntohl(v4mask.s_addr));
          if (bits < 0) {
            log_warn(LD_GENERAL,
                     "IPv4-style mask %s is not a prefix address; rejecting.",
                     escaped(mask));
            goto err;
          }
        } else { /* Not IPv4; we don't do address-style IPv6 masks. */
          log_warn(LD_GENERAL,
                   "Malformed mask on address range %s; rejecting.",
                   escaped(s));
          goto err;
        }
      }
779
      if (family == AF_INET6 && v4map) {
780
781
        if (bits > 32 && bits < 96) { /* Crazy */
          log_warn(LD_GENERAL,
782
                   "Bad mask bits %d for V4-mapped V6 address; rejecting.",
783
784
785
786
787
788
                   bits);
          goto err;
        }
        /* XXXX_IP6 is this really what we want? */
        bits = 96 + bits%32; /* map v4-mapped masks onto 96-128 bits */
      }
789
790
791
792
793
      if (any_flag) {
        log_warn(LD_GENERAL,
                 "Found bit prefix with wildcard address; rejecting");
        goto err;
      }
794
795
796
797
798
799
800
801
802
803
804
805
    } else { /* pick an appropriate mask, as none was given */
      if (any_flag)
        bits = 0;  /* This is okay whether it's V6 or V4 (FIX V4-mapped V6!) */
      else if (tor_addr_family(addr_out) == AF_INET)
        bits = 32;
      else if (tor_addr_family(addr_out) == AF_INET6)
        bits = 128;
    }
    *maskbits_out = (maskbits_t) bits;
  } else {
    if (mask) {
      log_warn(LD_GENERAL,
Nick Mathewson's avatar
Nick Mathewson committed
806
               "Unexpected mask in address %s; rejecting", escaped(s));
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
      goto err;
    }
  }

  /* Parse port(s) */
  if (port_min_out) {
    uint16_t port2;
    if (!port_max_out) /* caller specified one port; fake the second one */
      port_max_out = &port2;

    if (parse_port_range(port, port_min_out, port_max_out) < 0) {
      goto err;
    } else if ((*port_min_out != *port_max_out) && port_max_out == &port2) {
      log_warn(LD_GENERAL,
               "Wanted one port from address range, but there are two.");

      port_max_out = NULL;  /* caller specified one port, so set this back */
      goto err;
    }
  } else {
    if (port) {
      log_warn(LD_GENERAL,
Nick Mathewson's avatar
Nick Mathewson committed
829
               "Unexpected ports in address %s; rejecting", escaped(s));
830
831
832
833
834
835
836
837
838
839
840
      goto err;
    }
  }

  tor_free(base);
  return tor_addr_family(addr_out);
 err:
  tor_free(base);
  return -1;
}

Nick Mathewson's avatar
Nick Mathewson committed
841
/** Determine whether an address is IPv4, either native or IPv4-mapped IPv6.
842
 * Note that this is about representation only, as any decent stack will
Nick Mathewson's avatar
Nick Mathewson committed
843
 * reject IPv4-mapped addresses received on the wire (and won't use them
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
 * on the wire either).
 */
int
tor_addr_is_v4(const tor_addr_t *addr)
{
  tor_assert(addr);

  if (tor_addr_family(addr) == AF_INET)
    return 1;

  if (tor_addr_family(addr) == AF_INET6) {
    /* First two don't need to be ordered */
    uint32_t *a32 = tor_addr_to_in6_addr32(addr);
    if (a32[0] == 0 && a32[1] == 0 && ntohl(a32[2]) == 0x0000ffffu)
      return 1;
  }

  return 0; /* Not IPv4 - unknown family or a full-blood IPv6 address */
}

/** Determine whether an address <b>addr</b> is null, either all zeroes or
 *  belonging to family AF_UNSPEC.
 */
int
tor_addr_is_null(const tor_addr_t *addr)
{
  tor_assert(addr);

  switch (tor_addr_family(addr)) {
    case AF_INET6: {
      uint32_t *a32 = tor_addr_to_in6_addr32(addr);
      return (a32[0] == 0) && (a32[1] == 0) && (a32[2] == 0) && (a32[3] == 0);
    }
    case AF_INET:
      return (tor_addr_to_ipv4n(addr) == 0);
879
880
    case AF_UNIX:
      return 1;
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
    case AF_UNSPEC:
      return 1;
    default:
      log_warn(LD_BUG, "Called with unknown address family %d",
               (int)tor_addr_family(addr));
      return 0;
  }
  //return 1;
}

/** Return true iff <b>addr</b> is a loopback address */
int
tor_addr_is_loopback(const tor_addr_t *addr)
{
  tor_assert(addr);
  switch (tor_addr_family(addr)) {
    case AF_INET6: {
      /* ::1 */
      uint32_t *a32 = tor_addr_to_in6_addr32(addr);
900
901
      return (a32[0] == 0) && (a32[1] == 0) && (a32[2] == 0) &&
        (ntohl(a32[3]) == 1);
902
903
904
905
906
907
908
909
910
911
912
913
    }
    case AF_INET:
      /* 127.0.0.1 */
      return (tor_addr_to_ipv4h(addr) & 0xff000000) == 0x7f000000;
    case AF_UNSPEC:
      return 0;
    default:
      tor_fragile_assert();
      return 0;
  }
}

914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
/* Is addr valid?
 * Checks that addr is non-NULL and not tor_addr_is_null().
 * If for_listening is true, IPv4 addr 0.0.0.0 is allowed.
 * It means "bind to all addresses on the local machine". */
int
tor_addr_is_valid(const tor_addr_t *addr, int for_listening)
{
  /* NULL addresses are invalid regardless of for_listening */
  if (addr == NULL) {
    return 0;
  }

  /* Only allow IPv4 0.0.0.0 for_listening. */
  if (for_listening && addr->family == AF_INET
      && tor_addr_to_ipv4h(addr) == 0) {
    return 1;
  }

  /* Otherwise, the address is valid if it's not tor_addr_is_null() */
  return !tor_addr_is_null(addr);
}

/* Is the network-order IPv4 address v4n_addr valid?
 * Checks that addr is not zero.
 * Except if for_listening is true, where IPv4 addr 0.0.0.0 is allowed. */
int
tor_addr_is_valid_ipv4n(uint32_t v4n_addr, int for_listening)
{
  /* Any IPv4 address is valid with for_listening. */
  if (for_listening) {
    return 1;
  }

  /* Otherwise, zero addresses are invalid. */
  return v4n_addr != 0;
}

/* Is port valid?
 * Checks that port is not 0.
 * Except if for_listening is true, where port 0 is allowed.
 * It means "OS chooses a port". */
int
tor_port_is_valid(uint16_t port, int for_listening)
{
  /* Any port value is valid with for_listening. */
  if (for_listening) {
    return 1;
  }

  /* Otherwise, zero ports are invalid. */
  return port != 0;
}

967
/** Set <b>dest</b> to equal the IPv4 address in <b>v4addr</b> (given in
968
 * network order). */
969
void
970
tor_addr_from_ipv4n(tor_addr_t *dest, uint32_t v4addr)
971
972
{
  tor_assert(dest);
973
  memset(dest, 0, sizeof(tor_addr_t));
974
  dest->family = AF_INET;
975
976
977
978
979
980
981
982
983
984
  dest->addr.in_addr.s_addr = v4addr;
}

/** Set <b>dest</b> to equal the IPv6 address in the 16 bytes at
 * <b>ipv6_bytes</b>. */
void
tor_addr_from_ipv6_bytes(tor_addr_t *dest, const char *ipv6_bytes)
{
  tor_assert(dest);
  tor_assert(ipv6_bytes);
985
  memset(dest, 0, sizeof(tor_addr_t));
986
987
  dest->family = AF_INET6;
  memcpy(dest->addr.in6_addr.s6_addr, ipv6_bytes, 16);
988
989
}

Nick Mathewson's avatar
Nick Mathewson committed
990
/** Set <b>dest</b> equal to the IPv6 address in the in6_addr <b>in6</b>. */
991
992
993
994
995
996
void
tor_addr_from_in6(tor_addr_t *dest, const struct in6_addr *in6)
{
  tor_addr_from_ipv6_bytes(dest, (const char*)in6->s6_addr);
}

997
998
999
1000
/** Copy a tor_addr_t from <b>src</b> to <b>dest</b>.
 */
void
tor_addr_copy(tor_addr_t *dest, const tor_addr_t *src)
For faster browsing, not all history is shown. View entire blame