aboutsummaryrefslogtreecommitdiff
path: root/utils/find_roa/find_roa.c
blob: e91aead364acf3b630fa8f533738548083fdbeca (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
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
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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
/*
 * Copyright (C) 2006--2008  American Registry for Internet Numbers ("ARIN")
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND ARIN DISCLAIMS ALL WARRANTIES WITH
 * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS.  IN NO EVENT SHALL ARIN BE LIABLE FOR ANY SPECIAL, DIRECT,
 * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
 * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
 * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 * PERFORMANCE OF THIS SOFTWARE.
 */

/* $Id$ */

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <unistd.h>
#include <string.h>
#include <dirent.h>
#include <limits.h>

#include <openssl/bio.h>
#include <openssl/pem.h>
#include <openssl/err.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <openssl/safestack.h>
#include <openssl/conf.h>
#include <openssl/rand.h>
#include <openssl/asn1.h>
#include <openssl/asn1t.h>
#include <openssl/cms.h>

#include <rpki/roa.h>

#ifndef FILENAME_MAX
#define	FILENAME_MAX		1024
#endif

#ifndef ADDR_RAW_BUF_LEN
#define ADDR_RAW_BUF_LEN	16
#endif



/*
 * Error handling.
 */

#define _lose(_msg_, _file_)							\
  do {										\
    if (_file_)									\
      fprintf(stderr, "%s:%d: %s: %s\n", __FILE__, __LINE__, _msg_, _file_);	\
    else									\
      fprintf(stderr, "%s:%d: %s\n", __FILE__, __LINE__, _msg_);		\
    fprintf(stderr, "%s: %s\n", _msg_, _file_);					\
  } while (0)

#define lose(_msg_, _file_)			\
  do {						\
    _lose(_msg_, _file_);			\
    goto done;					\
  } while (0)
 
#define lose_errno(_msg_, _file_)		\
  do {						\
    _lose(_msg_, _file_);			\
    perror(NULL);				\
    goto done;					\
  } while (0)
 
#define lose_openssl(_msg_, _file_)		\
  do {						\
    _lose(_msg_, _file_);			\
    ERR_print_errors_fp(stderr);		\
    goto done;					\
  } while (0)


/*
 * Extract a ROA prefix from the ASN.1 bitstring encoding.
 */
static int extract_roa_prefix(unsigned char *addr,
			      unsigned *prefixlen,
			      const ASN1_BIT_STRING *bs,
			      const unsigned afi)
{
  unsigned length;

  switch (afi) {
  case IANA_AFI_IPV4: length =  4; break;
  case IANA_AFI_IPV6: length = 16; break;
  default: return 0;
  }

  if (bs->length < 0 || bs->length > length)
    return 0;

  if (bs->length > 0) {
    memcpy(addr, bs->data, bs->length);
    if ((bs->flags & 7) != 0) {
      unsigned char mask = 0xFF >> (8 - (bs->flags & 7));
      addr[bs->length - 1] &= ~mask;
    }
  }

  memset(addr + bs->length, 0, length - bs->length);

  *prefixlen = (bs->length * 8) - (bs->flags & 7);

  return 1;
}

/*
 * Check str for a trailing suffix.
 */
static int has_suffix(const char *str, const char *suffix)
{
  size_t len_str, len_suffix;
  assert(str != NULL && suffix != NULL);
  len_str = strlen(str);
  len_suffix = strlen(suffix);
  return len_str >= len_suffix && !strcmp(str + len_str - len_suffix, suffix);
}

/*
 * Handle one object.
 */
static void file_handler(const char *filename, const unsigned prefix_afi, const unsigned char *prefix, const unsigned long prefixlen)
{
  unsigned char roa_prefix[ADDR_RAW_BUF_LEN];
  unsigned roa_prefixlen, roa_maxprefixlen, plen;
  CMS_ContentInfo *cms = NULL;
  BIO *b = NULL;
  ROA *r = NULL;
  int i, j, k, n;
  unsigned long asid;

  if (!(b = BIO_new_file(filename, "rb")))
    lose_openssl("Couldn't open CMS file", filename);

  if ((cms = d2i_CMS_bio(b, NULL)) == NULL)
    lose_openssl("Couldn't read CMS file", filename);

  BIO_free(b);

  if ((b = BIO_new(BIO_s_mem())) == NULL)
    lose_openssl("Couldn't open ROA", filename);

  if (CMS_verify(cms, NULL, NULL, NULL, b, CMS_NOCRL | CMS_NO_SIGNER_CERT_VERIFY | CMS_NO_ATTR_VERIFY | CMS_NO_CONTENT_VERIFY) <= 0)
    lose_openssl("Couldn't parse ROA CMS", filename);

  if ((r = ASN1_item_d2i_bio(ASN1_ITEM_rptr(ROA), b, NULL)) == NULL)
    lose_openssl("Couldn't parse ROA", filename);

  asid = (unsigned long) ASN1_INTEGER_get(r->asID);

  for (i = 0; i < sk_ROAIPAddressFamily_num(r->ipAddrBlocks); i++) {
    ROAIPAddressFamily *f = sk_ROAIPAddressFamily_value(r->ipAddrBlocks, i);

    /*
     * AFI must match, SAFI must be null
     */
    if (f->addressFamily->length != 2 ||
	prefix_afi != ((f->addressFamily->data[0] << 8) | (f->addressFamily->data[1])))
      continue;

    for (j = 0; j < sk_ROAIPAddress_num(f->addresses); j++) {
      ROAIPAddress *a = sk_ROAIPAddress_value(f->addresses, j);

      if (!extract_roa_prefix(roa_prefix, &roa_prefixlen, a->IPAddress, prefix_afi))
	lose("Malformed ROA", filename);

      /*
       * If the prefix we're looking for is bigger than the ROA
       * prefix, the ROA can't possibly cover.
       */
      if (prefixlen < roa_prefixlen)
	continue;

      if (a->maxLength)
	roa_maxprefixlen = ASN1_INTEGER_get(a->maxLength);
      else
	roa_maxprefixlen = roa_prefixlen;

      /*
       * If the prefix we're looking for is smaller than the smallest
       * allowed slice of the ROA prefix, the ROA can't possibly
       * cover.
       */
      if (prefixlen > roa_maxprefixlen)
	continue;

      /*
       * If we get this far, we have to compare prefixes.
       */
      assert(roa_prefixlen <= ADDR_RAW_BUF_LEN * 8);
      plen = prefixlen < roa_prefixlen ? prefixlen : roa_prefixlen;
      k = 0;
      while (plen >= 8 && prefix[k] == roa_prefix[k]) {
	plen -= 8;
	k++;
      }
      if (plen > 8 || ((prefix[k] ^ roa_prefix[k]) & (0xFF << (8 - plen))) != 0)
	continue;

      /*
       * If we get here, we have a match.
       */
      printf("ASN %lu prefix ", asid);
      switch (prefix_afi) {
      case IANA_AFI_IPV4:
	printf("%u.%u.%u.%u", prefix[0], prefix[1], prefix[2], prefix[3]);
	break;
      case IANA_AFI_IPV6:
	for (n = 16; n > 1 && prefix[n-1] == 0x00 && prefix[n-2] == 0x00; n -= 2)
	  ;
	for (k = 0; k < n; k += 2)
	  printf("%x%s", (prefix[k] << 8) | prefix[k+1], (k < 14 ? ":" : ""));
	if (k < 16)
	  printf(":");
	break;
      }
      printf("/%lu ROA %s\n", prefixlen, filename);
      goto done;
    }
  }

 done:
  BIO_free(b);
  CMS_ContentInfo_free(cms);
  ROA_free(r);
}

/*
 * Walk a directory tree
 */
static int handle_directory(const char *name, const unsigned prefix_afi, const unsigned char *prefix, const unsigned long prefixlen)
{
  char path[FILENAME_MAX];
  struct dirent *d;
  size_t len;
  DIR *dir;
  int ret = 0, need_slash;

  assert(name);
  len = strlen(name);
  assert(len > 0 && len < sizeof(path));
  need_slash = name[len - 1] != '/';

  if ((dir = opendir(name)) == NULL)
    lose_errno("Couldn't open directory", name);

  while ((d = readdir(dir)) != NULL) {
    if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
      continue;
    if (len + strlen(d->d_name) + need_slash >= sizeof(path))
      lose("Constructed path name too long", d->d_name);
    strcpy(path, name);
    if (need_slash)
      strcat(path, "/");
    strcat(path, d->d_name);
    switch (d->d_type) {
    case DT_DIR:
      if (!handle_directory(path, prefix_afi, prefix, prefixlen))
	lose("Directory walk failed", path);
      continue;
    default:
      if (has_suffix(path, ".roa"))
	file_handler(path, prefix_afi, prefix, prefixlen);
      continue;
    }
  }

  ret = 1;

 done:
  if (dir)
    closedir(dir);
  return ret;
}

int main (int argc, char *argv[])
{
  unsigned char prefix[ADDR_RAW_BUF_LEN];
  unsigned long prefixlen;
  unsigned afi;
  char *s = NULL, *p = NULL;
  int i, len, ret = 1;

  if (argc < 3) {
    fprintf(stderr, "usage: %s authtree prefix [prefix...]\n", argv[0]);
    return 1;
  }

  OpenSSL_add_all_algorithms();
  ERR_load_crypto_strings();

  for (i = 2; i < argc; i++) {

    if ((s = strdup(argv[i])) == NULL)
      lose("Couldn't strdup()", argv[i]);

    if ((p = strchr(s, '/')) != NULL)
      *p++ = '\0';

    len = a2i_ipadd(prefix, s);

    switch (len) {
    case  4: afi = IANA_AFI_IPV4; break;
    case 16: afi = IANA_AFI_IPV6; break;
    default: lose("Unknown AFI", argv[i]);
    }

    if (p) {
      if (*p == '\0' ||
	  (prefixlen = strtoul(p, &p, 10)) == ULONG_MAX ||
	  *p != '\0' || 
	  prefixlen > ADDR_RAW_BUF_LEN * 8)
	lose("Bad prefix length", argv[i]);
    } else  {
      prefixlen = len * 8;
    }

    assert(prefixlen <= ADDR_RAW_BUF_LEN * 8);

    free(s);
    p = s = NULL;

    if (!handle_directory(argv[1], afi, prefix, prefixlen))
      goto done;

  }

  ret = 0;

 done:
  if (s)
    free(s);
  return ret;
}